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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tanweirush/TodayHistory | TodayHistory/data/THData.swift | 1 | 2516 | //
// THData.swift
// TodayHistory
//
// Created by 谭伟 on 15/9/10.
// Copyright (c) 2015年 谭伟. All rights reserved.
//
import UIKit
typealias netDataRefreshOver = (success:Bool, page:Int, newLine:Int)->Void
class THData: NSObject, NetWorkManagerDelegate {
private var nets: NSMutableArray = NSMutableArray()
private var lastPage: Int = 0
private var refresh: netDataRefreshOver?
private var _list: NSMutableArray! = NSMutableArray()
var list: NSArray! {
get
{
return _list;
}
}
func destroy()
{
_list.removeAllObjects()
self.refresh = nil
self.lastPage = 0
for net in nets
{
(net as! NetWorkManager).stopLoad()
}
nets.removeAllObjects()
}
func getTodayHistory(page: Int, dayNum:Int, refresh: netDataRefreshOver)
{
let cal = NSCalendar.currentCalendar()
let flags: NSCalendarUnit = [.Month, .Day]
let secs = Double(dayNum)*24*60*60
let date = NSDate(timeIntervalSinceNow: secs)
let nowCom = cal.components(flags, fromDate: date)
let net = NetWorkManager()
net.delegate = self
net.getTodayHistoryWithDay(Day: nowCom.day, Month: nowCom.month, page: page)
nets.addObject(net)
self.refresh = refresh
}
func todayHistoryRequestData(todays: NSArray, page: Int, sender: NetWorkManager)
{
nets.removeObject(sender)
if (page > Globle.AutoPageLoadTag)
{
if (page == Globle.AutoPageLoadTag + 1)
{
_list.removeAllObjects()
}
lastPage = 1
let modes = THMode.makeArrayWithData(todays)
_list.addObjectsFromArray(modes as [AnyObject])
self.refresh?(success: true, page: page, newLine:todays.count)
}
else if (lastPage == page - 1 || page == 1)
{
if todays.count == 0
{
self.refresh?(success: true, page: page, newLine:todays.count)
return
}
lastPage = page
let modes = THMode.makeArrayWithData(todays)
_list.addObjectsFromArray(modes as [AnyObject])
self.refresh?(success: true, page: page, newLine:todays.count)
}
else
{
self.refresh?(success: false, page: page, newLine:todays.count)
}
}
}
| mit | b26b67ab599440d926856a1934e1b1de | 27.477273 | 84 | 0.559058 | 4.381119 | false | false | false | false |
XcqRomance/SwiftFrameworkDemo | BookRoomKit/BookRoomKit/BookViewController.swift | 1 | 756 | //
// TestViewController.swift
// BookRoomKit
//
// Created by romance on 2016/12/26.
// Copyright © 2016年 romance. All rights reserved.
//
import UIKit
class BookViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let image = UIImage(named: "bookroom_down_bg_blue", in: bundle, compatibleWith: nil)
let imageView = UIImageView(image: image)
imageView.center = view.center
view.addSubview(imageView)
let label = UILabel()
label.text = "hello word"
label.sizeToFit()
label.center = view.center
label.font = UIFont(name: "Kreon-Bold", size: 17)
view.addSubview(label)
}
}
| mit | 69a875acc47bb546bc1c1638201e14a7 | 24.965517 | 90 | 0.652058 | 3.984127 | false | false | false | false |
acort3255/Emby.ApiClient.Swift | Emby.ApiClient/model/connect/ConnectAuthorizationRequest.swift | 4 | 1589 | //
// ConnectAuthorizationRequest.swift
// Emby.ApiClient
//
// Created by Vedran Ozir on 07/10/15.
// Copyright © 2015 Vedran Ozir. All rights reserved.
//
import Foundation
//package mediabrowser.model.connect;
public class ConnectAuthorizationRequest
{
// private String SendingUserId;
// public final String getSendingUserId()
// {
// return SendingUserId;
// }
// public final void setSendingUserId(String value)
// {
// SendingUserId = value;
// }
// private String ConnectUserName;
// public final String getConnectUserName()
// {
// return ConnectUserName;
// }
// public final void setConnectUserName(String value)
// {
// ConnectUserName = value;
// }
// private String[] EnabledLibraries;
// public final String[] getEnabledLibraries()
// {
// return EnabledLibraries;
// }
// public final void setEnabledLibraries(String[] value)
// {
// EnabledLibraries = value;
// }
// private boolean EnableLiveTv;
// public final boolean getEnableLiveTv()
// {
// return EnableLiveTv;
// }
// public final void setEnableLiveTv(boolean value)
// {
// EnableLiveTv = value;
// }
// private String[] EnabledChannels;
// public final String[] getEnabledChannels()
// {
// return EnabledChannels;
// }
// public final void setEnabledChannels(String[] value)
// {
// EnabledChannels = value;
// }
//
// public ConnectAuthorizationRequest()
// {
// setEnabledLibraries(new String[] { });
// setEnabledChannels(new String[] { });
// }
} | mit | 041c36bf7fac8eb1785e782ba2beb47f | 23.446154 | 59 | 0.634761 | 3.745283 | false | false | false | false |
simpleandpretty/decider-ios | MessagesExtension/MessagesViewController.swift | 1 | 8064 | import UIKit
import Messages
import AVKit
import AVFoundation
class MessagesViewController: MSMessagesAppViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Conversation Handling
override func willBecomeActive(with conversation: MSConversation) {
// Called when the extension is about to move from the inactive to active state.
// This will happen when the extension is about to present UI.
// Use this method to configure the extension and restore previously stored state.
print("willBecomeActive")
presentViewController(for: conversation, with: presentationStyle)
}
override func didResignActive(with conversation: MSConversation) {
// Called when the extension is about to move from the active to inactive state.
// This will happen when the user dissmises the extension, changes to a different
// conversation or quits Messages.
// Use this method to release shared resources, save user data, invalidate timers,
// and store enough state information to restore your extension to its current state
// in case it is terminated later.
print("resignActive")
}
override func didReceive(_ message: MSMessage, conversation: MSConversation) {
// Called when a message arrives that was generated by another instance of this
// extension on a remote device.
// Use this method to trigger UI updates in response to the message.
print("didReceive")
}
override func didStartSending(_ message: MSMessage, conversation: MSConversation) {
// Called when the user taps the send button.
}
override func didCancelSending(_ message: MSMessage, conversation: MSConversation) {
// Called when the user deletes the message without sending it.
// Use this to clean up state related to the deleted message.
}
override func willTransition(to presentationStyle: MSMessagesAppPresentationStyle) {
// Called before the extension transitions to a new presentation style.
// Use this method to prepare for the change in presentation style.
print("willTransition")
}
override func didTransition(to presentationStyle: MSMessagesAppPresentationStyle) {
// Called after the extension transitions to a new presentation style.
// Use this method to finalize any behaviors associated with the change in presentation style.
print("didTransition")
for child in childViewControllers where child is PropagatePresentationStyle {
if let progateStyleVC = child as? PropagatePresentationStyle {
progateStyleVC.propagate(presentationStyle: presentationStyle)
}
}
}
private func presentViewController(for conversation: MSConversation, with presentationStyle: MSMessagesAppPresentationStyle) {
// Determine the controller to present.
let controller: UIViewController
if conversation.selectedMessage == nil {
controller = instantiateFightMoveViewController(conversation: conversation, presentationStyle: presentationStyle)
} else {
if let message = conversation.selectedMessage,
let url = message.url,
let fight = Fight.decode(fromURL: url),
fight.result == .notEnded,
message.senderParticipantIdentifier != conversation.localParticipantIdentifier
{
controller = instantiateFightMoveViewController(conversation: conversation, presentationStyle: presentationStyle)
} else {
controller = instantiatePlayFightViewController(conversation: conversation, presentationStyle: presentationStyle)
}
}
// Remove any existing child controllers.
for child in childViewControllers {
child.willMove(toParentViewController: nil)
child.view.removeFromSuperview()
child.removeFromParentViewController()
}
// Embed the new controller.
addChildViewController(controller)
controller.view.frame = view.bounds
controller.view.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(controller.view)
controller.view.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
controller.view.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
controller.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
controller.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
controller.didMove(toParentViewController: self)
}
private func instantiateFightMoveViewController(conversation:MSConversation, presentationStyle: MSMessagesAppPresentationStyle) -> UIViewController {
guard
let controller = storyboard?.instantiateViewController(withIdentifier: FightMoveViewController.storyboardIdentifier) as? FightMoveViewController
else {
fatalError("Unable to instantiate a FightMoveViewController from the storyboard")
}
controller.setup(conversation: conversation)
controller.propagate(presentationStyle: presentationStyle)
controller.delegate = self
return controller
}
private func instantiatePlayFightViewController(conversation:MSConversation, presentationStyle: MSMessagesAppPresentationStyle) -> UIViewController {
guard
let controller = storyboard?.instantiateViewController(withIdentifier: PlayFightViewController.storyboardIdentifier) as? PlayFightViewController
else {
fatalError("Unable to instantiate a PlayFightViewController from the storyboard")
}
controller.setup(conversation: conversation)
controller.delegate = self
return controller
}
private func instantiateVideoViewController(conversation:MSConversation) -> UIViewController {
guard
let message = conversation.selectedMessage,
let url = message.url,
let fight = Fight.decode(fromURL: url)
else {
return UIViewController()
}
var videosURL = [URL]()
if let attack = fight.attackerOption {
videosURL.append(MediaResources.mediaURL(forGameOption: attack))
}
if let defense = fight.defenderOption {
videosURL.append(MediaResources.mediaURL(forGameOption: defense))
}
var playerItems = [AVPlayerItem]()
for fileURL in videosURL {
let asset = AVURLAsset(url:fileURL, options:nil)
let playerItem = AVPlayerItem(asset: asset)
playerItems.append(playerItem)
}
let player = AVQueuePlayer(items: playerItems)
let controller = AVPlayerViewController()
let label = UILabel()
label.text = "Hello World";
label.sizeToFit()
label.textColor = UIColor.white
controller.player = player
controller.contentOverlayView?.addSubview(label)
controller.showsPlaybackControls = true
player.play()
return controller
}
}
extension MessagesViewController: FightMoveControllerDelegate {
func fightMoveControllerDidSelectMove(_ controller: FightMoveViewController) {
self.dismiss()
}
}
extension MessagesViewController: PlayFightViewControllerDelegate {
func playFightViewControllerDidSelectMakeOfficial(_ controller: PlayFightViewController) {
self.dismiss()
}
}
public protocol PropagatePresentationStyle: class {
func propagate(presentationStyle: MSMessagesAppPresentationStyle)
}
| gpl-3.0 | 2cdfb6eafecb5733903beaaf1c2a01aa | 40.142857 | 156 | 0.68812 | 6.165138 | false | false | false | false |
Rag0n/QuNotes | Carthage/Checkouts/FlexLayout/Example/FlexLayoutSample/UI/Examples/RaywenderlichTutorial/Subviews/ShowTableViewCell.swift | 1 | 1978 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Created by Luc Dion on 2017-08-23.
import UIKit
class ShowTableViewCell: UITableViewCell {
static var reuseIdentifier = "ShowTableViewCell"
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
self.textLabel?.textColor = .white
self.textLabel?.font = .systemFont(ofSize: 14.0)
self.textLabel?.numberOfLines = 2
self.textLabel?.adjustsFontSizeToFitWidth = true
self.textLabel?.minimumScaleFactor = 0.8
self.detailTextLabel?.textColor = .lightGray
let accessoryView = UIImageView(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
accessoryView.image = UIImage(named: "download")
self.accessoryView = accessoryView
self.backgroundColor = .clear
self.separatorInset = .zero
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func configure(show: Show) {
self.textLabel?.text = show.title
self.detailTextLabel?.text = show.length
self.imageView?.image = UIImage(named: show.image)
}
}
| gpl-3.0 | f0fb06df1fd0552e7b65cf841a68af5e | 42 | 89 | 0.700202 | 4.777778 | false | false | false | false |
ishkawa/Result | Result/Result.swift | 8 | 6629 | // Copyright (c) 2015 Rob Rix. All rights reserved.
/// An enum representing either a failure with an explanatory error, or a success with a result value.
public enum Result<T, Error: ErrorType>: ResultType, CustomStringConvertible, CustomDebugStringConvertible {
case Success(T)
case Failure(Error)
// MARK: Constructors
/// Constructs a success wrapping a `value`.
public init(value: T) {
self = .Success(value)
}
/// Constructs a failure wrapping an `error`.
public init(error: Error) {
self = .Failure(error)
}
/// Constructs a result from an Optional, failing with `Error` if `nil`
public init(_ value: T?, @autoclosure failWith: () -> Error) {
self = value.map(Result.Success) ?? .Failure(failWith())
}
/// Constructs a result from a function that uses `throw`, failing with `Error` if throws
public init(@autoclosure _ f: () throws -> T) {
do {
self = .Success(try f())
} catch {
self = .Failure(error as! Error)
}
}
// MARK: Deconstruction
/// Returns the value from `Success` Results or `throw`s the error
public func dematerialize() throws -> T {
switch self {
case let .Success(value):
return value
case let .Failure(error):
throw error
}
}
/// Case analysis for Result.
///
/// Returns the value produced by applying `ifFailure` to `Failure` Results, or `ifSuccess` to `Success` Results.
public func analysis<Result>(@noescape ifSuccess ifSuccess: T -> Result, @noescape ifFailure: Error -> Result) -> Result {
switch self {
case let .Success(value):
return ifSuccess(value)
case let .Failure(value):
return ifFailure(value)
}
}
// MARK: Higher-order functions
/// Returns `self.value` if this result is a .Success, or the given value otherwise. Equivalent with `??`
public func recover(@autoclosure value: () -> T) -> T {
return self.value ?? value()
}
/// Returns this result if it is a .Success, or the given result otherwise. Equivalent with `??`
public func recoverWith(@autoclosure result: () -> Result<T,Error>) -> Result<T,Error> {
return analysis(
ifSuccess: { _ in self },
ifFailure: { _ in result() })
}
// MARK: Errors
/// The domain for errors constructed by Result.
public static var errorDomain: String { return "com.antitypical.Result" }
/// The userInfo key for source functions in errors constructed by Result.
public static var functionKey: String { return "\(errorDomain).function" }
/// The userInfo key for source file paths in errors constructed by Result.
public static var fileKey: String { return "\(errorDomain).file" }
/// The userInfo key for source file line numbers in errors constructed by Result.
public static var lineKey: String { return "\(errorDomain).line" }
/// Constructs an error.
public static func error(message: String? = nil, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__) -> NSError {
var userInfo: [String: AnyObject] = [
functionKey: function,
fileKey: file,
lineKey: line,
]
if let message = message {
userInfo[NSLocalizedDescriptionKey] = message
}
return NSError(domain: errorDomain, code: 0, userInfo: userInfo)
}
// MARK: CustomStringConvertible
public var description: String {
return analysis(
ifSuccess: { ".Success(\($0))" },
ifFailure: { ".Failure(\($0))" })
}
// MARK: CustomDebugStringConvertible
public var debugDescription: String {
return description
}
}
/// Returns `true` if `left` and `right` are both `Success`es and their values are equal, or if `left` and `right` are both `Failure`s and their errors are equal.
public func == <T: Equatable, Error: Equatable> (left: Result<T, Error>, right: Result<T, Error>) -> Bool {
if let left = left.value, right = right.value {
return left == right
} else if let left = left.error, right = right.error {
return left == right
}
return false
}
/// Returns `true` if `left` and `right` represent different cases, or if they represent the same case but different values.
public func != <T: Equatable, Error: Equatable> (left: Result<T, Error>, right: Result<T, Error>) -> Bool {
return !(left == right)
}
/// Returns the value of `left` if it is a `Success`, or `right` otherwise. Short-circuits.
public func ?? <T, Error> (left: Result<T, Error>, @autoclosure right: () -> T) -> T {
return left.recover(right())
}
/// Returns `left` if it is a `Success`es, or `right` otherwise. Short-circuits.
public func ?? <T, Error> (left: Result<T, Error>, @autoclosure right: () -> Result<T, Error>) -> Result<T, Error> {
return left.recoverWith(right())
}
// MARK: - Derive result from failable closure
public func materialize<T>(f: () throws -> T) -> Result<T, NSError> {
do {
return .Success(try f())
} catch {
return .Failure(error as NSError)
}
}
// MARK: - Cocoa API conveniences
/// Constructs a Result with the result of calling `try` with an error pointer.
///
/// This is convenient for wrapping Cocoa API which returns an object or `nil` + an error, by reference. e.g.:
///
/// Result.try { NSData(contentsOfURL: URL, options: .DataReadingMapped, error: $0) }
public func `try`<T>(function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, `try`: NSErrorPointer -> T?) -> Result<T, NSError> {
var error: NSError?
return `try`(&error).map(Result.Success) ?? .Failure(error ?? Result<T, NSError>.error(function: function, file: file, line: line))
}
/// Constructs a Result with the result of calling `try` with an error pointer.
///
/// This is convenient for wrapping Cocoa API which returns a `Bool` + an error, by reference. e.g.:
///
/// Result.try { NSFileManager.defaultManager().removeItemAtURL(URL, error: $0) }
public func `try`(function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, `try`: NSErrorPointer -> Bool) -> Result<(), NSError> {
var error: NSError?
return `try`(&error) ?
.Success(())
: .Failure(error ?? Result<(), NSError>.error(function: function, file: file, line: line))
}
// MARK: - Operators
infix operator >>- {
// Left-associativity so that chaining works like you’d expect, and for consistency with Haskell, Runes, swiftz, etc.
associativity left
// Higher precedence than function application, but lower than function composition.
precedence 100
}
/// Returns the result of applying `transform` to `Success`es’ values, or re-wrapping `Failure`’s errors.
///
/// This is a synonym for `flatMap`.
public func >>- <T, U, Error> (result: Result<T, Error>, @noescape transform: T -> Result<U, Error>) -> Result<U, Error> {
return result.flatMap(transform)
}
import Foundation
| mit | d61102ef0fce4e28450a65fc32d736fc | 32.115 | 162 | 0.679601 | 3.611232 | false | false | false | false |
picaso/parrot-zik-status | ParrotStatus/zikAPI/ParrotZikEndpoints.swift | 1 | 3531 | struct ParrotZikEndpoints {
static let NoiseCancellationStatus = "/api/audio/noise_cancellation/enabled/get"
static let SetNoiseCancellationStatus = "/api/audio/noise_cancellation/enabled/set"
static let ApplicationVersion = "/api/software/version/get"
static let BatteryInfo = "/api/system/battery/get"
static let FriendlyName = "/api/bluetooth/friendlyname/get"
static let EqualizerStatus = "/api/audio/equalizer/enabled/get"
static let SetEqualizerStatus = "/api/audio/equalizer/enabled/set"
static let NoiseControltatus = "/api/audio/noise_control/enabled/get"
static let SetNoiseControlStatus = "/api/audio/noise_control/enabled/set"
static let NoiseControlLevelStatus = "/api/audio/noise_control/get"
static let SetNoiseControlLevelStatus = "/api/audio/noise_control/set"
static let ConcertHallStatus = "/api/audio/sound_effect/enabled/get"
static let SetConcertHallStatus = "/api/audio/sound_effect/enabled/set"
static let FlightModeStatus = "/api/flight_mode/get"
static let FlightModeEnable = "/api/flight_mode/enable"
static let FlightModeDisable = "/api/flight_mode/disable"
static let HeadDetectionStatus = "/api/system/head_detection/enabled/get"
static let SetHeadModeDetectionStatus = "/api/system/head_detection/enabled/set"
}
//
// '/api/account/username': ['get', 'set'],
// '/api/appli_version': ['set'],
// '/api/audio/counter': ['get'],
// '/api/audio/equalizer/enabled': ['get', 'set'],
// '/api/audio/equalizer/preset_id': ['set'],
// '/api/audio/equalizer/preset_value': ['set'],
// '/api/audio/noise_cancellation/enabled': ['get', 'set'],
// '/api/audio/noise_control/enabled': ['get', 'set'],
// '/api/audio/noise_control': ['get', 'set'],
// '/api/audio/noise_control/phone_mode': ['get', 'set'],
// '/api/audio/noise': ['get'],
// '/api/audio/param_equalizer/value': ['set'],
// '/api/audio/preset/bypass': ['get', 'set'],
// '/api/audio/preset/': ['clear_all'],
// '/api/audio/preset/counter': ['get'],
// '/api/audio/preset/current': ['get'],
// '/api/audio/preset': ['download', 'activate', 'save', 'remove', 'cancel_producer'],
// '/api/audio/preset/synchro': ['start', 'stop'],
// '/api/audio/smart_audio_tune': ['get', 'set'],
// '/api/audio/sound_effect/angle': ['get', 'set'],
// '/api/audio/sound_effect/enabled': ['get', 'set'],
// '/api/audio/sound_effect': ['get'],
// '/api/audio/sound_effect/room_size': ['get', 'set'],
// '/api/audio/source': ['get'],
// '/api/audio/specific_mode/enabled': ['get', 'set'],
// '/api/audio/thumb_equalizer/value': ['get', 'set'],
// '/api/audio/track/metadata': ['get', 'force'],
// '/api/bluetooth/friendlyname': ['get', 'set'],
// '/api/flight_mode': ['get', 'enable', 'disable'],
// '/api/software/download_check_state': ['get'],
// '/api/software/download_size': ['set'],
// '/api/software/tts': ['get', 'enable', 'disable'],
// '/api/software/version_checking': ['get'],
// '/api/software/version': ['get'],
// '/api/system/anc_phone_mode/enabled': ['get', 'set'],
// '/api/system/auto_connection/enabled': ['get', 'set'],
// '/api/system/auto_power_off': ['get', 'set'],
// '/api/system/auto_power_off/presets_list': ['get'],
// '/api/system/battery/forecast': ['get'],
// '/api/system/battery': ['get'],
// '/api/system/bt_address': ['get'],
// '/api/system': ['calibrate'],
// '/api/system/color': ['get'],
// '/api/system/device_type': ['get'],
// '/api/system/': ['factory_reset'],
// '/api/system/head_detection/enabled': ['get', 'set'],
// '/api/system/pi': ['get'],
| mit | c2bb0be255e8a8164538b71cc8f22602 | 47.369863 | 87 | 0.647975 | 3.189702 | false | false | false | false |
28stephlim/HeartbeatAnalysis-master | VoiceMemos/Controller/RecordViewController.swift | 3 | 6992 | //
// RecordViewController.swift
// VoiceMemos
//
// Created by Zhouqi Mo on 2/24/15.
// Copyright (c) 2015 Zhouqi Mo. All rights reserved.
//
import UIKit
import AVFoundation
class RecordViewController: UIViewController {
// MARK: Property
var audioRecorder: AVAudioRecorder?
var meterTimer: NSTimer?
let recordDuration = 120.0
@IBOutlet weak var durationLabel: UILabel!
@IBOutlet weak var voiceRecordHUD: KMVoiceRecordHUD!
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
voiceRecordHUD.update(0.0)
voiceRecordHUD.fillColor = UIColor.greenColor()
durationLabel.text = ""
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: AVAudioSessionInterruptionNotification, object: AVAudioSession.sharedInstance())
}
// MARK: Target Action
@IBAction func finishRecord(sender: AnyObject) {
meterTimer?.invalidate()
meterTimer = nil
voiceRecordHUD.update(0.0)
if audioRecorder?.currentTime > 0 {
audioRecorder?.stop()
performSegueWithIdentifier("Update Recording", sender: self)
} else {
audioRecorder = nil
performSegueWithIdentifier("Cancel Recording", sender: self)
}
AudioSessionHelper.setupSessionActive(false)
}
// MARK: Notification
func handleInterruption(notification: NSNotification) {
if let userInfo = notification.userInfo {
let interruptionType = userInfo[AVAudioSessionInterruptionTypeKey] as! UInt
if interruptionType == AVAudioSessionInterruptionType.Began.rawValue {
if audioRecorder?.recording == true {
audioRecorder?.pause()
}
meterTimer?.invalidate()
meterTimer = nil
voiceRecordHUD.update(0.0)
} else if interruptionType == AVAudioSessionInterruptionType.Ended.rawValue {
let alertController = UIAlertController(title: nil, message: "Do you want to continue the recording?", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { _ in
self.finishRecord(self)
}
alertController.addAction(cancelAction)
let resumeAction = UIAlertAction(title: "Resume", style: .Default) { _ in
self.delay(0.8) {
if let recorder = self.audioRecorder {
recorder.record()
self.updateRecorderCurrentTimeAndMeters()
self.meterTimer = NSTimer.scheduledTimerWithTimeInterval(0.1,
target: self,
selector: "updateRecorderCurrentTimeAndMeters",
userInfo: nil,
repeats: true)
}
}
}
alertController.addAction(resumeAction)
presentViewController(alertController, animated: true, completion: nil)
}
}
}
// MARK: Other
func delay(time: NSTimeInterval, block: () -> Void) {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(time * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue(), block)
}
func updateRecorderCurrentTimeAndMeters() {
if let recorder = audioRecorder {
let currentTime = Int(recorder.currentTime)
let timeLeft = Int(recordDuration) - currentTime
if timeLeft > 10 {
durationLabel.text = "\(currentTime)″"
} else {
voiceRecordHUD.fillColor = UIColor.redColor()
durationLabel.text = "\(timeLeft) seconds left"
if timeLeft == 0 {
durationLabel.text = "Time is up"
finishRecord(self)
}
}
if recorder.recording {
recorder.updateMeters()
let ALPHA = 0.05
let peakPower = pow(10, (ALPHA * Double(recorder.peakPowerForChannel(0))))
var rate: Double = 0.0
if (peakPower <= 0.2) {
rate = 0.2
} else if (peakPower > 0.9) {
rate = 1.0
} else {
rate = peakPower
}
voiceRecordHUD.update(CGFloat(rate))
}
}
}
func configRecorderWithURL(url: NSURL, delegate: AVAudioRecorderDelegate) {
let session:AVAudioSession = AVAudioSession.sharedInstance()
session.requestRecordPermission {granted in
if granted {
debugPrint("Recording permission has been granted")
let recordSettings: [String : AnyObject] = [
AVFormatIDKey : NSNumber(unsignedInt: kAudioFormatLinearPCM),
AVSampleRateKey : 44100.0,
AVNumberOfChannelsKey : 2,
AVLinearPCMBitDepthKey : 16,
AVLinearPCMIsBigEndianKey : false,
AVLinearPCMIsFloatKey : false,
]
self.audioRecorder = try? AVAudioRecorder(URL: url, settings: recordSettings)
guard let recorder = self.audioRecorder else {
return
}
recorder.delegate = delegate
recorder.meteringEnabled = true
AudioSessionHelper.postStartAudioNotificaion(recorder)
self.delay(0.8) {
AudioSessionHelper.setupSessionActive(true, catagory: AVAudioSessionCategoryRecord)
if recorder.prepareToRecord() {
recorder.recordForDuration(self.recordDuration)
debugPrint("Start recording")
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleInterruption:", name: AVAudioSessionInterruptionNotification, object: AVAudioSession.sharedInstance())
self.updateRecorderCurrentTimeAndMeters()
self.meterTimer = NSTimer.scheduledTimerWithTimeInterval(0.1,
target: self,
selector: "updateRecorderCurrentTimeAndMeters",
userInfo: nil,
repeats: true)
}
}
} else {
debugPrint("Recording permission has been denied")
}
}
}
}
| mit | feb79d4677097f4517ac00292dce69f7 | 38.942857 | 198 | 0.540629 | 6.169462 | false | false | false | false |
koehlermichael/focus | Blockzilla/UIColorExtensions.swift | 2 | 1319 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
private struct Color {
var red: CGFloat
var green: CGFloat
var blue: CGFloat
};
extension UIColor {
/**
* Initializes and returns a color object for the given RGB hex integer.
*/
public convenience init(rgb: Int, alpha: Float = 1) {
self.init(
red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
blue: CGFloat((rgb & 0x0000FF) >> 0) / 255.0,
alpha: CGFloat(alpha))
}
func lerp(toColor: UIColor, step: CGFloat) -> UIColor {
var fromR: CGFloat = 0
var fromG: CGFloat = 0
var fromB: CGFloat = 0
getRed(&fromR, green: &fromG, blue: &fromB, alpha: nil)
var toR: CGFloat = 0
var toG: CGFloat = 0
var toB: CGFloat = 0
toColor.getRed(&toR, green: &toG, blue: &toB, alpha: nil)
let r = fromR + (toR - fromR) * step
let g = fromG + (toG - fromG) * step
let b = fromB + (toB - fromB) * step
return UIColor(red: r, green: g, blue: b, alpha: 1)
}
}
| mpl-2.0 | fe00a944655f9ef219cbab2433cb1cd2 | 29.674419 | 76 | 0.571645 | 3.408269 | false | false | false | false |
aleufms/JeraUtils | JeraUtils/Base/JeraPushNotificationHelper.swift | 1 | 3241 | //
// JeraPushNotificationHelper.swift
// Ativoapp
//
// Created by Adriano Wahl on 07/12/15.
// Copyright © 2015 Jera. All rights reserved.
//
import UIKit
import RxSwift
public class JeraPushNotificationHelper {
public static var sharedInstance = JeraPushNotificationHelper()
private let disposeBag = DisposeBag()
public private(set) var deviceToken: NSData?{
didSet{
if let deviceToken = deviceToken{
deviceTokenSubject.onNext(deviceToken)
}
}
}
public let deviceTokenSubject = PublishSubject<NSData>()
public let pushNotificationSubject = PublishSubject<[NSObject : AnyObject]>()
/**
Transform a deviceToken NSData to a String and allocs it to the deviceToken Variable
- parameter deviceTokenData: The NSData for the Device Token to be alloced.
*/
public func registerDeviceToken(deviceTokenData: NSData) {
self.deviceToken = deviceTokenData
print("APNS: \(JeraPushNotificationHelper.deviceTokenDataToString(deviceTokenData))")
}
public func receiveNotification(notification: [NSObject : AnyObject]){
pushNotificationSubject.onNext(notification)
}
private var launchNotification: [NSObject : AnyObject]?
public func registerLaunchNotification(launchOptions: [NSObject: AnyObject]?){
if let launchNotification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [NSObject: AnyObject] {
self.launchNotification = launchNotification
}
}
public func processLaunchNotification() {
if let launchNotification = launchNotification {
pushNotificationSubject.onNext(launchNotification)
self.launchNotification = nil
}
}
/**
Converts a Device Token as NSData to a String
- parameter deviceToken: The NSData to be converted
- returns: The Device Token as a String
*/
public class func deviceTokenDataToString(deviceToken: NSData) -> String {
let deviceTokenStr = deviceToken.description.stringByReplacingOccurrencesOfString("<", withString: "")
.stringByReplacingOccurrencesOfString(">", withString: "")
.stringByReplacingOccurrencesOfString(" ", withString: "")
return deviceTokenStr
}
/**
Ask for permisions and register the user for Remote Notifications with Sound, Alert and Badge.
*/
public class func registerForRemoteNotifications() {
if UIApplication.sharedApplication().respondsToSelector("registerUserNotificationSettings:"){
//iOS > 8
UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil))
}else{
UIApplication.sharedApplication().registerForRemoteNotifications()
}
}
public class func unregisterForRemoteNotifications() {
UIApplication.sharedApplication().unregisterForRemoteNotifications()
}
public class func setNotificationBadge(count: Int) {
UIApplication.sharedApplication().applicationIconBadgeNumber = count
}
}
| mit | 4021f208acadf17b6c78655ed4593282 | 34.604396 | 159 | 0.686111 | 6.03352 | false | false | false | false |
NicolasKim/Roy | Roy/Classes/UIKit/RoyUIExtension.swift | 1 | 3276 | //
// RoyUIExtension.swift
// Pods-Roy_Example
//
// Created by dreamtracer on 2018/3/11.
//
import Foundation
enum RoyUIExtensionError :Error {
case Convert
case Unknown
}
public protocol RoyProtocol {
init?(param : [String:Any]?)
}
public func RoyPrint(_ items: Any..., separator: String = "", terminator: String = "\n"){
#if DEBUG
print("Roy=> ",items, separator: separator, terminator: terminator)
#endif
}
/*
* UIKit extension
*/
public extension RoyR{
public func addRouter(url:String , viewController : RoyProtocol.Type ,paramValidator: RoyValidatorProtocol.Type?) -> Bool{
let c : RoyTaskClosure = { (p : [String:Any]?) -> RoyProtocol? in
if let vc = viewController.init(param: p) {
return vc
}
return nil
}
return self.addRouter(url: url, paramValidator: paramValidator, task: c)
}
public func viewController(url:URL,param:[String:Any]?) -> UIViewController?{
do{
guard let vc = self.route(url: url, param: param) else {
throw RoyUIExtensionError.Convert
}
return vc as? UIViewController
}
catch RoyUIExtensionError.Convert{
return nil
}
catch{
return nil
}
}
}
public extension RoyModuleProtocol{
public func viewController(path:String,param:[String:Any]?) -> UIViewController?{
let urlString = "\(RoyModuleConfig.sharedInstance.scheme)://\(moduleHost)/\(path)"
let url = URL(string: urlString)
return RoyR.global.viewController(url: url!, param: param)
}
public func addRouter(path:String , viewController : RoyProtocol.Type,paramValidator:RoyValidatorProtocol.Type?) -> Bool{
let urlString = "\(RoyModuleConfig.sharedInstance.scheme)://\(moduleHost)/\(path)"
return RoyR.global.addRouter(url: urlString, viewController: viewController, paramValidator: paramValidator)
}
}
public extension UIViewController{
public func present(url : URL, param : [String:Any]?, animated: Bool, completion: (() -> Void)?){
if let vc = RoyR.global.viewController(url: url, param: param){
self.present(vc, animated: animated, completion: completion)
}
}
}
public extension UINavigationController{
public func pushViewController(url: URL , param : [String : Any] , animated: Bool){
if let vc = RoyR.global.viewController(url: url,param:param){
self.pushViewController(vc, animated: animated)
}
}
public func setViewControllers(urls : [URL], animated: Bool){
var vcs : [UIViewController] = []
for url in urls {
if let vc = RoyR.global.viewController(url: url,param:nil){
vcs.append(vc)
}
}
self.setViewControllers(vcs, animated: animated)
}
}
public extension UITabBarController{
func setViewControllers(urls : [URL], animated: Bool){
var vcs : [UIViewController] = []
for url in urls {
if let vc = RoyR.global.viewController(url: url,param:nil){
vcs.append(vc)
}
}
self.setViewControllers(vcs, animated: animated)
}
}
| mit | d5c626934278f0dd2d667f833549813b | 27.99115 | 126 | 0.616911 | 4.344828 | false | false | false | false |
chenyunguiMilook/VisualDebugger | Sources/VisualDebugger/proto/CoordinateSystem.swift | 1 | 6605 | //
// CoordinateSystem.swift
// VisualDebugger
//
// Created by chenyungui on 2018/3/19.
//
import Foundation
#if os(iOS) || os(tvOS)
import UIKit
#else
import Cocoa
#endif
public class CoordinateSystem : CALayer {
public enum Kind {
case yDown, yUp
}
public enum Axis {
case x, y
}
public let minWidth: CGFloat = 250
public var type: Kind
public var area:CGRect
public var segmentLength:CGFloat = 50
public var scale: CGFloat = 1.5
public var numSegments:Int
public var showOrigin:Bool
// for transform values to current coordinate system space
public internal(set) var matrix = CGAffineTransform.identity
internal var colorIndex:Int = 0
internal var minSegmentLength: CGFloat {
return minWidth / CGFloat(numSegments)
}
public init(type: Kind, area:CGRect, scale:CGFloat, numSegments:Int, showOrigin:Bool, precision:Int = 5) {
self.type = type
self.area = area
self.scale = scale
self.numSegments = numSegments
self.showOrigin = showOrigin
super.init()
self.backgroundColor = AppColor.white.cgColor
let rect = showOrigin ? area.rectFromOrigin : area
let maxValue = max(rect.size.width, rect.size.height)
let segmentValue = CGFloat(getDivision(Double(maxValue), segments: numSegments))
let xAxisData = AxisData(min: rect.minX, max: rect.maxX, segmentValue: segmentValue)
let yAxisData = AxisData(min: rect.minY, max: rect.maxY, segmentValue: segmentValue)
let valueRect = CGRect(x: xAxisData.startValue, y: yAxisData.startValue, width: xAxisData.lengthValue, height: yAxisData.lengthValue)
let xAxisY: CGFloat = (valueRect.minY < 0 && valueRect.maxY >= 0) ? 0 : yAxisData.startValue
let yAxisX: CGFloat = (valueRect.minX < 0 && valueRect.maxX >= 0) ? 0 : xAxisData.startValue
// calculate axis segments in value space
let xAxisSegment = AxisSegment(start: CGPoint(x: xAxisData.startValue, y: xAxisY), end: CGPoint(x: xAxisData.endValue, y: xAxisY))
let yAxisSegment = AxisSegment(start: CGPoint(x: yAxisX, y: yAxisData.startValue), end: CGPoint(x: yAxisX, y: yAxisData.endValue))
// get axis labels and transform to render space
let precision = calculatePrecision(Double(segmentValue))
let formater = NumberFormatter(precision: precision)
var xAxisLabels = xAxisSegment.getLabels(axis: .x, segmentValue: segmentValue, numSegments: xAxisData.numSegments, numFormater: formater)
var yAxisLabels = yAxisSegment.getLabels(axis: .y, segmentValue: segmentValue, numSegments: yAxisData.numSegments, numFormater: formater)
// calculate the proper segment length
let xLabelBounds = xAxisLabels.reduce(CGRect.zero) { $0.union($1.label.bounds) }
self.segmentLength = xLabelBounds.width < minSegmentLength ? minSegmentLength : xLabelBounds.width
self.segmentLength = ceil(segmentLength * scale)
// calculate the matrix for transform value from value space to render space
let scale = self.segmentLength / segmentValue
self.matrix = CGAffineTransform(translationX: -valueRect.origin.x, y: -valueRect.origin.y)
self.matrix.scaleBy(x: scale, y: scale)
if self.type == .yUp {
let renderHeight = valueRect.height * scale
self.matrix.scaleBy(x: 1, y: -1)
self.matrix.translateBy(x: 0, y: renderHeight)
}
// until now we got correct transform matrix
// get axis labels and transform to render space
xAxisLabels = xAxisLabels * self.matrix
yAxisLabels = yAxisLabels * self.matrix
// render axis to self
let thickness: CGFloat = 8
renderAxis(axis: .x, coordinate: self.type, labels: xAxisLabels, labelOffset: ceil(xLabelBounds.height), thickness: thickness, to: self)
renderAxis(axis: .y, coordinate: self.type, labels: yAxisLabels, labelOffset: ceil(xLabelBounds.width/2) + thickness, thickness: thickness, to: self)
// setup frame
self.frame = valueRect.applying(self.matrix)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func getNextColor() -> AppColor {
let color = AppColor.get(self.colorIndex % colors.count)
self.colorIndex += 1
return color
}
public func render(object: Debuggable, color: AppColor? = nil) {
object.debug(in: self, color: color)
}
}
func renderAxis(axis: CoordinateSystem.Axis, coordinate: CoordinateSystem.Kind, labels: [AxisLabel], labelOffset: CGFloat, thickness: CGFloat, to layer: CALayer) {
let path = AppBezierPath()
let half = thickness/2
let start = labels[0].position
var vector = (labels[1].position - start)
vector = vector.normalized(to: min(vector.length/2, thickness*3))
let end = labels.last!.position + vector
var labelOffsetX: CGFloat = 0
var labelOffsetY: CGFloat = 0
var lineOffsetX: CGFloat = 0
var lineOffsetY: CGFloat = 0
switch (axis, coordinate) {
case (.x, .yUp): labelOffsetY = labelOffset; lineOffsetY = half
case (.x, .yDown): labelOffsetY = -labelOffset; lineOffsetY = -half
case (.y, .yUp): labelOffsetX = -labelOffset; lineOffsetX = -half
case (.y, .yDown): labelOffsetX = -labelOffset; lineOffsetX = -half
}
// 1. draw main axis
path.move(to: start)
path.addLine(to: end)
// 2. draw short lines
for i in 0 ..< labels.count {
let position = labels[i].position
let lineEnd = CGPoint(x: position.x + lineOffsetX, y: position.y + lineOffsetY)
path.move(to: position)
path.addLine(to: lineEnd)
}
// 3. draw end arrow
path.append(AxisArrow().pathAtEndOfSegment(segStart: start, segEnd: end))
// 4. add bezier path layer
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = 0.5
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = AppColor.lightGray.cgColor
shapeLayer.fillColor = nil
shapeLayer.masksToBounds = false
layer.addSublayer(shapeLayer)
// 5. add labels layer
for label in labels {
let x = label.position.x + labelOffsetX
let y = label.position.y + labelOffsetY
let center = CGPoint(x: x, y: y)
label.label.setCenter(center)
layer.addSublayer(label.label)
}
}
| mit | cd2ca46812954fe3bafe198574248c23 | 37.625731 | 163 | 0.65617 | 4.225848 | false | false | false | false |
ZhaoBingDong/EasySwifty | EasySwifty/Classes/Easy+UIImage.swift | 1 | 1911 | //
// Easy+UIImage.swift
// EaseSwifty
//
// Created by 董招兵 on 2017/8/6.
// Copyright © 2017年 大兵布莱恩特. All rights reserved.
//
import Foundation
import UIKit
// MARK: - UIImage
extension UIImage {
/// 调整图片的方向
func normalizedImage() -> UIImage {
if self.imageOrientation == UIImage.Orientation.up {
return self
}
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
self.draw(in: CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height))
let img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img!
}
// func cirleImage() -> UIImage {
//
// // NO代表透明
// UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)
// // 获得上下文
// let ctx = UIGraphicsGetCurrentContext()
//
// // 添加一个圆
// let rect = CGRect(x: 0, y : 0, width : self.size.width, height: self.size.height);
// ctx!.addEllipse(in: rect);
//
// // 裁剪
// ctx?.clip();
//
// // 将图片画上去
// self.draw(in: rect)
//
// let cirleImage = UIGraphicsGetImageFromCurrentImageContext();
//
// UIGraphicsEndImageContext();
//
// return cirleImage!
//
//
// }
/// 通过一个 UIColor 生成一个 UIImage
@discardableResult
class func imageWithColor(_ color: UIColor) -> UIImage {
let rect:CGRect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context:CGContext = UIGraphicsGetCurrentContext()!
context.setFillColor(color.cgColor)
context.fill(rect)
let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()!;
UIGraphicsEndImageContext()
return image
}
}
| apache-2.0 | 4a9114224264e2e7107be9c7cfc588f1 | 23.876712 | 95 | 0.594714 | 4.09009 | false | false | false | false |
Chaosspeeder/YourGoals | YourGoals WatchKit Extension/WatchConnectivityHandlerForWatch.swift | 1 | 2297 | //
// WatchConnectivityHandlerForWatch.swift
// YourGoals WatchKit Extension
//
// Created by André Claaßen on 24.05.18.
// Copyright © 2018 André Claaßen. All rights reserved.
//
import Foundation
import WatchKit
import WatchConnectivity
protocol WatchContextNotification {
func progressContextReceived(progressContext: [String:Any])
func todayTasksReceived(tasks:[WatchTaskInfo])
}
class WatchConnectivityHandlerForWatch : NSObject, WCSessionDelegate {
let session:WCSession!
var delegates = [WatchContextNotification]()
static let defaultHandler = WatchConnectivityHandlerForWatch(session: WCSession.default)
init (session:WCSession) {
self.session = session
super.init()
session.delegate = self
session.activate()
}
func registerDelegate(delegate: WatchContextNotification) {
self.delegates.append(delegate)
}
func activate() {
}
// MARK: WCSessionDelegate
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
NSLog("activationDidCompleteWith activationState: \(activationState)")
}
/// process the new application context from the host
///
/// - Parameters:
/// - session: the session
/// - applicationContext: the application context
func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
guard let progressContext = applicationContext["progress"] as? [String: Any] else {
NSLog("coulnd't extract progess context from application context: \(applicationContext)" )
return
}
for delegate in delegates {
delegate.progressContextReceived(progressContext: progressContext)
}
guard let todayTasksContext = applicationContext["todayTasks"] as? [[String: Any]] else {
NSLog("couldn't extract today tasks from application context: \(applicationContext)")
return
}
let todayTasks = todayTasksContext.map { WatchTaskInfo(fromDictionary: $0) }
for delegate in delegates {
delegate.todayTasksReceived(tasks: todayTasks)
}
}
}
| lgpl-3.0 | c86f8a0c450853507a8669249b6924df | 29.972973 | 124 | 0.672775 | 5.330233 | false | false | false | false |
SwiftOnEdge/Reactive | Sources/StreamKit/Event.swift | 1 | 3342 | //
// Event.swift
// Edge
//
// Created by Tyler Fleming Cloutier on 5/29/16.
//
//
import Foundation
/// Represents a signal event.
///
/// Signals must conform to the grammar:
/// `next* (failed | completed | interrupted)?`
public enum Event<Value> {
/// A value provided by the signal.
case next(Value)
/// The signal terminated because of an error. No further events will be
/// received.
case failed(Error)
/// The signal successfully terminated. No further events will be received.
case completed
/// Event production on the signal has been interrupted. No further events
/// will be received.
case interrupted
/// Whether this event indicates signal termination (i.e., that no further
/// events will be received).
public var isTerminating: Bool {
switch self {
case .next:
return false
case .failed, .completed, .interrupted:
return true
}
}
/// Lifts the given function over the event's value.
public func map<U>(_ f: (Value) -> U) -> Event<U> {
switch self {
case let .next(value):
return .next(f(value))
case let .failed(error):
return .failed(error)
case .completed:
return .completed
case .interrupted:
return .interrupted
}
}
/// Lifts the given function over the event's value.
public func flatMap<U>(_ f: (Value) -> U?) -> Event<U>? {
switch self {
case let .next(value):
if let nextValue = f(value) {
return .next(nextValue)
}
return nil
case let .failed(error):
return .failed(error)
case .completed:
return .completed
case .interrupted:
return .interrupted
}
}
/// Lifts the given function over the event's error.
public func mapError<F: Error>(_ f: (Error) -> F) -> Event<Value> {
switch self {
case let .next(value):
return .next(value)
case let .failed(error):
return .failed(f(error))
case .completed:
return .completed
case .interrupted:
return .interrupted
}
}
/// Unwraps the contained `Next` value.
public var value: Value? {
if case let .next(value) = self {
return value
} else {
return nil
}
}
/// Unwraps the contained `Error` value.
public var error: Error? {
if case let .failed(error) = self {
return error
} else {
return nil
}
}
}
public func == <Value: Equatable> (lhs: Event<Value>, rhs: Event<Value>) -> Bool {
switch (lhs, rhs) {
case let (.next(left), .next(right)):
return left == right
case let (.failed(left), .failed(right)):
return left.localizedDescription == right.localizedDescription
case (.completed, .completed):
return true
case (.interrupted, .interrupted):
return true
default:
return false
}
}
| mit | 1696d826d3e362bd4fd28fcd080638df | 23.755556 | 82 | 0.520646 | 4.740426 | false | false | false | false |
apple/swift-experimental-string-processing | Sources/_RegexParser/Regex/Printing/DumpAST.swift | 1 | 10823 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-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
//
//===----------------------------------------------------------------------===//
/// AST entities that can be pretty-printed or dumped.
///
/// As an alternative to this protocol,
/// you can also use the `description` to pretty-print an AST,
/// and `debugDescription` for to dump a debugging representation.
public protocol _ASTPrintable:
CustomStringConvertible,
CustomDebugStringConvertible
{
// The "base" dump out for AST nodes, like `alternation`.
// Children printing, parens, etc., handled automatically
var _dumpBase: String { get }
}
extension _ASTPrintable {
public var description: String { _print() }
public var debugDescription: String { _dump() }
var _children: [AST.Node]? {
if let children = (self as? _ASTParent)?.children {
return children
}
if let children = (self as? AST.Node)?.children {
return children
}
return nil
}
func _print() -> String {
// TODO: prettier printing
_dump()
}
func _dump() -> String {
guard let children = _children else {
return _dumpBase
}
let childDump = children.compactMap { child -> String? in
// Exclude trivia for now, as we don't want it to appear when performing
// comparisons of dumped output in tests.
// TODO: We should eventually have some way of filtering out trivia for
// tests, so that it can appear in regular dumps.
if child.isTrivia { return nil }
let dump = child._dump()
return !dump.isEmpty ? dump : nil
}
let base = "\(_dumpBase)"
if childDump.isEmpty {
return base
}
if childDump.count == 1, base.isEmpty {
return "\(childDump[0])"
}
return "\(base)(\(childDump.joined(separator: ",")))"
}
}
extension AST: _ASTPrintable {
public var _dumpBase: String {
var result = ""
if let opts = globalOptions {
result += "\(opts) "
}
result += root._dump()
return result
}
}
extension AST.Node: _ASTPrintable {
public var _dumpBase: String {
_associatedValue._dumpBase
}
}
extension AST.Alternation {
public var _dumpBase: String { "alternation<\(children.count)>" }
}
extension AST.Concatenation {
public var _dumpBase: String { "" }
}
extension AST.Quote {
public var _dumpBase: String { "quote \"\(literal)\"" }
}
extension AST.Trivia {
public var _dumpBase: String {
// TODO: comments, non-semantic whitespace, etc.
""
}
}
extension AST.Interpolation {
public var _dumpBase: String { "interpolation <\(contents)>" }
}
extension AST.Empty {
public var _dumpBase: String { "" }
}
extension AST.Conditional {
public var _dumpBase: String {
"if \(condition) then \(trueBranch) else \(falseBranch)"
}
}
extension AST.Conditional.Condition: _ASTPrintable {
public var _dumpBase: String { return "\(kind)" }
}
extension AST.Conditional.Condition.PCREVersionCheck.Kind: _ASTPrintable {
public var _dumpBase: String {
switch self {
case .equal: return "="
case .greaterThanOrEqual: return ">="
}
}
}
extension AST.Conditional.Condition.PCREVersionNumber: _ASTPrintable {
public var _dumpBase: String { "\(major).\(minor)" }
}
extension AST.Conditional.Condition.PCREVersionCheck: _ASTPrintable {
public var _dumpBase: String { "VERSION\(kind.value)\(num)" }
}
extension AST.Atom {
public var _dumpBase: String {
if let lit = self.literalStringValue {
return lit.halfWidthCornerQuoted
}
switch kind {
case .escaped(let c): return "\\\(c.character)"
case .scalarSequence(let s):
return s.scalars.map(\.value.halfWidthCornerQuoted).joined()
case .namedCharacter(let charName):
return "\\N{\(charName)}"
case .property(let p): return "\(p._dumpBase)"
case .keyboardControl, .keyboardMeta, .keyboardMetaControl:
fatalError("TODO")
case .dot: return "."
case .caretAnchor: return "^"
case .dollarAnchor: return "$"
case .backreference(let r), .subpattern(let r):
return "\(r._dumpBase)"
case .callout(let c): return "\(c)"
case .backtrackingDirective(let d): return "\(d)"
case .changeMatchingOptions(let opts):
return "changeMatchingOptions<\(opts)>"
case .invalid:
return "<invalid>"
case .char, .scalar:
fatalError("Unreachable")
}
}
}
extension AST.Atom.Number: _ASTPrintable {
public var _dumpBase: String {
value.map { "\($0)" } ?? "<invalid>"
}
}
extension AST.Atom.Callout: _ASTPrintable {
public var _dumpBase: String {
switch self {
case .pcre(let p): return "\(p)"
case .onigurumaNamed(let o): return "\(o)"
case .onigurumaOfContents(let o): return "\(o)"
}
}
}
extension AST.Atom.Callout.PCRE: _ASTPrintable {
public var _dumpBase: String {
"PCRE callout \(arg.value)"
}
}
extension AST.Atom.Callout.OnigurumaTag: _ASTPrintable {
public var _dumpBase: String { "[\(name.value)]" }
}
extension AST.Atom.Callout.OnigurumaNamed.ArgList: _ASTPrintable {
public var _dumpBase: String {
"{\(args.map { $0.value }.joined(separator: ","))}"
}
}
extension AST.Atom.Callout.OnigurumaNamed: _ASTPrintable {
public var _dumpBase: String {
var result = "named oniguruma callout \(name.value)"
if let tag = tag {
result += "\(tag)"
}
if let args = args {
result += "\(args)"
}
return result
}
}
extension AST.Atom.Callout.OnigurumaOfContents: _ASTPrintable {
public var _dumpBase: String {
var result = "oniguruma callout of contents {\(contents.value)}"
if let tag = tag {
result += "\(tag)"
}
result += " \(direction.value)"
return result
}
}
extension AST.Reference: _ASTPrintable {
public var _dumpBase: String {
var result = "\(kind)"
if let recursionLevel = recursionLevel {
result += "\(recursionLevel)"
}
return result
}
}
extension AST.Group.Kind: _ASTPrintable {
public var _dumpBase: String {
switch self {
case .capture: return "capture"
case .namedCapture(let s): return "capture<\(s.value)>"
case .balancedCapture(let b): return "balanced capture \(b)"
case .nonCapture: return "nonCapture"
case .nonCaptureReset: return "nonCaptureReset"
case .atomicNonCapturing: return "atomicNonCapturing"
case .lookahead: return "lookahead"
case .negativeLookahead: return "negativeLookahead"
case .nonAtomicLookahead: return "nonAtomicLookahead"
case .lookbehind: return "lookbehind"
case .negativeLookbehind: return "negativeLookbehind"
case .nonAtomicLookbehind: return "nonAtomicLookbehind"
case .scriptRun: return "scriptRun"
case .atomicScriptRun: return "atomicScriptRun"
case .changeMatchingOptions(let seq): return "changeMatchingOptions<\(seq)>"
}
}
}
extension AST.Group: _ASTPrintable {
public var _dumpBase: String {
"group_\(kind.value._dumpBase)"
}
}
extension AST.Quantification.Amount: _ASTPrintable {
public var _printBase: String {
_canonicalBase
}
public var _dumpBase: String {
switch self {
case .zeroOrMore: return "zeroOrMore"
case .oneOrMore: return "oneOrMore"
case .zeroOrOne: return "zeroOrOne"
case let .exactly(n): return "exactly<\(n)>"
case let .nOrMore(n): return "nOrMore<\(n)>"
case let .upToN(n): return "uptoN<\(n)>"
case let .range(lower, upper):
return ".range<\(lower)...\(upper)>"
}
}
}
extension AST.Quantification.Kind: _ASTPrintable {
public var _printBase: String { rawValue }
public var _dumpBase: String {
switch self {
case .eager: return "eager"
case .reluctant: return "reluctant"
case .possessive: return "possessive"
}
}
}
extension AST.Quantification: _ASTPrintable {
public var _printBase: String {
"""
quant_\(amount.value._printBase)\(kind.value._printBase)
"""
}
public var _dumpBase: String {
"""
quant_\(amount.value._dumpBase)_\(kind.value._dumpBase)
"""
}
}
extension AST.CustomCharacterClass: _ASTNode {
public var _dumpBase: String {
// Exclude trivia for now, as we don't want it to appear when performing
// comparisons of dumped output in tests.
// TODO: We should eventually have some way of filtering out trivia for
// tests, so that it can appear in regular dumps.
return "customCharacterClass(inverted: \(isInverted), \(strippingTriviaShallow.members))"
}
}
extension AST.CustomCharacterClass.Member: _ASTPrintable {
public var _dumpBase: String {
switch self {
case .custom(let cc): return "\(cc)"
case .atom(let a): return "\(a)"
case .range(let r): return "\(r)"
case .quote(let q): return "\(q)"
case .trivia(let t): return "\(t)"
case .setOperation(let lhs, let op, let rhs):
// TODO: We should eventually have some way of filtering out trivia for
// tests, so that it can appear in regular dumps.
return "op \(lhs.filter(\.isSemantic)) \(op.value) \(rhs.filter(\.isSemantic))"
}
}
}
extension AST.CustomCharacterClass.Range: _ASTPrintable {
public var _dumpBase: String {
"\(lhs)-\(rhs)"
}
}
extension AST.Atom.BacktrackingDirective: _ASTPrintable {
public var _dumpBase: String {
var result = "\(kind.value)"
if let name = name {
result += ": \(name.value)"
}
return result
}
}
extension AST.Group.BalancedCapture: _ASTPrintable {
public var _dumpBase: String {
"\(name?.value ?? "")-\(priorName.value)"
}
}
extension AST.AbsentFunction.Kind {
public var _dumpBase: String {
switch self {
case .repeater:
return "repeater"
case .expression:
return "expression"
case .stopper:
return "stopper"
case .clearer:
return "clearer"
}
}
}
extension AST.AbsentFunction {
public var _dumpBase: String {
"absent function \(kind._dumpBase)"
}
}
extension AST.GlobalMatchingOption.Kind: _ASTPrintable {
public var _dumpBase: String { _canonicalBase }
}
extension AST.GlobalMatchingOption: _ASTPrintable {
public var _dumpBase: String { "\(kind._dumpBase)" }
}
extension AST.GlobalMatchingOptionSequence: _ASTPrintable {
public var _dumpBase: String {
"GlobalMatchingOptionSequence<\(options)>"
}
}
| apache-2.0 | 74f2f87c35032056c19b51b14d4dc28e | 26.330808 | 93 | 0.630047 | 4.02342 | false | false | false | false |
emadhegab/GenericDataSource | Sources/_DelegatedGeneralCollectionView.swift | 3 | 7604 | //
// _DelegatedGeneralCollectionView.swift
// GenericDataSource
//
// Created by Mohamed Afifi on 3/20/16.
// Copyright © 2016 mohamede1945. All rights reserved.
//
import UIKit
protocol _GeneralCollectionViewMapping {
func globalSectionForLocalSection(_ localSection: Int) -> Int
func localIndexPathForGlobalIndexPath(_ globalIndexPath: IndexPath) -> IndexPath
func globalIndexPathForLocalIndexPath(_ localIndexPath: IndexPath) -> IndexPath
var delegate: GeneralCollectionView? { get }
}
@objc class _DelegatedGeneralCollectionView: NSObject, GeneralCollectionView {
let mapping: _GeneralCollectionViewMapping
var delegate: GeneralCollectionView {
return cast(mapping.delegate, message: "Couldn't call \(#function) of \(self) with a nil delegate. This is usually because you didn't set your UITableView/UICollection to ds_reusableViewDelegate for the GenericDataSource.")
}
init(mapping: _GeneralCollectionViewMapping) {
self.mapping = mapping
}
// MARK: - Scroll View
var ds_scrollView: UIScrollView {
return delegate.ds_scrollView
}
// MARK: - Register, dequeue
func ds_register(_ cellClass: AnyClass?, forCellWithReuseIdentifier identifier: String) {
delegate.ds_register(cellClass, forCellWithReuseIdentifier: identifier)
}
func ds_register(_ nib: UINib?, forCellWithReuseIdentifier identifier: String) {
delegate.ds_register(nib, forCellWithReuseIdentifier: identifier)
}
func ds_dequeueReusableCell(withIdentifier identifier: String, for indexPath: IndexPath) -> ReusableCell {
let globalIndexPath = ds_globalIndexPathForLocalIndexPath(indexPath)
return delegate.ds_dequeueReusableCell(withIdentifier: identifier, for: globalIndexPath)
}
func ds_dequeueReusableSupplementaryView(ofKind kind: String, withIdentifier identifier: String, for indexPath: IndexPath) -> ReusableSupplementaryView {
let globalIndexPath = ds_globalIndexPathForLocalIndexPath(indexPath)
return delegate.ds_dequeueReusableSupplementaryView(ofKind: kind, withIdentifier: identifier, for: globalIndexPath)
}
// MARK: - Numbers
func ds_numberOfSections() -> Int {
return delegate.ds_numberOfSections()
}
func ds_numberOfItems(inSection section: Int) -> Int {
let globalSection = ds_globalSectionForLocalSection(section)
return delegate.ds_numberOfItems(inSection: globalSection)
}
// MARK: - Manpulate items and sections
func ds_reloadData() {
delegate.ds_reloadData()
}
func ds_performBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)?) {
delegate.ds_performBatchUpdates(updates, completion: completion)
}
func ds_insertSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) {
let globalSections = ds_globalSectionSetForLocalSectionSet(sections)
delegate.ds_insertSections(globalSections, with: animation)
}
func ds_deleteSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) {
let globalSections = ds_globalSectionSetForLocalSectionSet(sections)
delegate.ds_deleteSections(globalSections, with: animation)
}
func ds_reloadSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) {
let globalSections = ds_globalSectionSetForLocalSectionSet(sections)
delegate.ds_reloadSections(globalSections, with: animation)
}
func ds_moveSection(_ section: Int, toSection newSection: Int) {
let globalSection = ds_globalSectionForLocalSection(section)
let globalNewSection = ds_globalSectionForLocalSection(newSection)
delegate.ds_moveSection(globalSection, toSection: globalNewSection)
}
func ds_insertItems(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) {
let globalIndexPaths = ds_globalIndexPathsForLocalIndexPaths(indexPaths)
delegate.ds_insertItems(at: globalIndexPaths, with: animation)
}
func ds_deleteItems(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) {
let globalIndexPaths = ds_globalIndexPathsForLocalIndexPaths(indexPaths)
delegate.ds_deleteItems(at: globalIndexPaths, with: animation)
}
func ds_reloadItems(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) {
let globalIndexPaths = ds_globalIndexPathsForLocalIndexPaths(indexPaths)
delegate.ds_reloadItems(at: globalIndexPaths, with: animation)
}
func ds_moveItem(at indexPath: IndexPath, to newIndexPath: IndexPath) {
let globalIndexPath = ds_globalIndexPathForLocalIndexPath(indexPath)
let globalNewIndexPath = ds_globalIndexPathForLocalIndexPath(newIndexPath)
delegate.ds_moveItem(at: globalIndexPath, to: globalNewIndexPath)
}
// MARK: - Scroll
func ds_scrollToItem(at indexPath: IndexPath, at scrollPosition: UICollectionViewScrollPosition, animated: Bool) {
let globalIndexPath = ds_globalIndexPathForLocalIndexPath(indexPath)
delegate.ds_scrollToItem(at: globalIndexPath, at: scrollPosition, animated: animated)
}
// MARK: - Select/Deselect
func ds_selectItem(at indexPath: IndexPath?, animated: Bool, scrollPosition: UICollectionViewScrollPosition) {
let globalIndexPath: IndexPath?
if let indexPath = indexPath {
globalIndexPath = ds_globalIndexPathForLocalIndexPath(indexPath)
} else {
globalIndexPath = nil
}
delegate.ds_selectItem(at: globalIndexPath, animated: animated, scrollPosition: scrollPosition)
}
func ds_deselectItem(at indexPath: IndexPath, animated: Bool) {
let globalIndexPath = ds_globalIndexPathForLocalIndexPath(indexPath)
delegate.ds_deselectItem(at: globalIndexPath, animated: animated)
}
// MARK: - IndexPaths, Cells
func ds_indexPath(for cell: ReusableCell) -> IndexPath? {
if let indexPath = delegate.ds_indexPath(for: cell) {
return ds_localIndexPathForGlobalIndexPath(indexPath)
}
return nil
}
func ds_indexPathForItem(at point: CGPoint) -> IndexPath? {
if let indexPath = delegate.ds_indexPathForItem(at: point) {
return ds_localIndexPathForGlobalIndexPath(indexPath)
}
return nil
}
func ds_indexPathsForVisibleItems() -> [IndexPath] {
let indexPaths = delegate.ds_indexPathsForVisibleItems()
return ds_localIndexPathsForGlobalIndexPaths(indexPaths)
}
func ds_indexPathsForSelectedItems() -> [IndexPath] {
let indexPaths = delegate.ds_indexPathsForSelectedItems()
return ds_localIndexPathsForGlobalIndexPaths(indexPaths)
}
func ds_visibleCells() -> [ReusableCell] {
return delegate.ds_visibleCells()
}
func ds_cellForItem(at indexPath: IndexPath) -> ReusableCell? {
let globalIndexPath = ds_globalIndexPathForLocalIndexPath(indexPath)
return delegate.ds_cellForItem(at: globalIndexPath)
}
// MARK: - Local, Global
func ds_localIndexPathForGlobalIndexPath(_ globalIndexPath: IndexPath) -> IndexPath {
return mapping.localIndexPathForGlobalIndexPath(globalIndexPath)
}
func ds_globalIndexPathForLocalIndexPath(_ localIndexPath: IndexPath) -> IndexPath {
return mapping.globalIndexPathForLocalIndexPath(localIndexPath)
}
func ds_globalSectionForLocalSection(_ localSection: Int) -> Int {
return mapping.globalSectionForLocalSection(localSection)
}
}
| mit | 00ad1769921fa0b884b9dd5bf6f36d8c | 37.593909 | 231 | 0.724188 | 5.399858 | false | false | false | false |
Chaosspeeder/YourGoals | YourGoals/Business/Habits/HabitCheckManager.swift | 1 | 1667 | //
// HabitCheckManager.swift
// YourGoals
//
// Created by André Claaßen on 24.11.17.
// Copyright © 2017 André Claaßen. All rights reserved.
//
import Foundation
/// business functions for checking and unchecking habits
class HabitCheckManager:StorageManagerWorker {
/// delete all check instances for the date. there is usually only one instance
///
/// - Parameters:
/// - habit: the habit
/// - date: the date
func deleteAllChecks(forHabit habit:Habit, atDate date: Date) {
let checks = habit.allHabitChecks().filter{ $0.check == date.day() }
for habitCheck in checks {
habit.removeFromChecks(habitCheck)
manager.context.delete(habitCheck)
}
}
/// check the habit for the given date and save the result in the database
///
/// - Parameters:
/// - habit: the habit
/// - state: .checked or .unchecked state for the date
/// - date: the date to check or uncheck
/// - Throws: core data exception
func checkHabit(forHabit habit:Habit, state: HabitCheckedState, atDate date: Date) throws {
let dayDate = date.day()
deleteAllChecks(forHabit: habit, atDate: dayDate)
if state == .checked {
let habitCheck = manager.habitCheckStore.createPersistentObject()
habitCheck.check = dayDate
habit.addToChecks(habitCheck)
}
try self.manager.context.save()
TaskNotificationObserver.defaultObserver.tasksChanged()
NotificationCenter.default.post(name: StrategyModelNotification.habitCheckStateChanged.name, object: habit)
}
}
| lgpl-3.0 | 483f81124fd7e8c9f5e4b658f135b23d | 33.625 | 115 | 0.645608 | 4.396825 | false | false | false | false |
stack-this/hunter-price | ios/List.swift | 1 | 626 | //
// List.swift
// HunterPrice
//
// Created by Gessy on 9/10/16.
// Copyright © 2016 GetsemaniAvila. All rights reserved.
//
import Foundation
class ListData{
class List{
let name : String
let quantity :String
let unity : String
let unityPrice : String
let totalPrice : String
init(name:String,quantity:String,unity:String,unityPrice:String,totalPrice:String) {
self.name = name
self.quantity = quantity
self.unity = unity
self.unityPrice = unityPrice
self.totalPrice = totalPrice
}
}
}
| apache-2.0 | d5b00ab312f33b1356639b1696b3b26b | 21.321429 | 92 | 0.592 | 4.111842 | false | false | false | false |
22377832/ccyswift | UIScrollVIew/UIScrollVIew/ViewController.swift | 1 | 1296 | //
// ViewController.swift
// UIScrollVIew
//
// Created by sks on 17/1/25.
// Copyright © 2017年 chen. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
var imageView: UIImageView!
var scrollView: UIScrollView!
let image = UIImage(named: "685905.jpg")
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
imageView = UIImageView(image: image)
scrollView = UIScrollView(frame: view.bounds)
scrollView.addSubview(imageView)
view.addSubview(scrollView)
scrollView.delegate = self
scrollView.indicatorStyle = .white
scrollView.contentSize = imageView.bounds.size
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollView.alpha = 0.5
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollView.alpha = 1
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
scrollView.alpha = 1
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 9fff1bbd972ef7c44162c1e2600a459c | 25.387755 | 96 | 0.666667 | 5.070588 | false | false | false | false |
iAugux/iBBS-Swift | iBBS/Additions/UINavigationBar+Extension.swift | 1 | 988 | //
// UINavigationBar+Extension.swift
//
// Created by Augus on 12/7/15.
// Copyright © 2015 iAugus. All rights reserved.
//
import UIKit
extension UINavigationBar {
func hideBottomHairline() {
let navigationBarImageView = hairlineImageViewInNavigationBar(self)
navigationBarImageView?.hidden = true
}
func showBottomHairline() {
let navigationBarImageView = hairlineImageViewInNavigationBar(self)
navigationBarImageView?.hidden = false
}
private func hairlineImageViewInNavigationBar(view: UIView) -> UIImageView? {
if view.isKindOfClass(UIImageView) && view.bounds.height <= 1.0 {
return view as? UIImageView
}
let subviews = view.subviews as [UIView]
for subview: UIView in subviews {
if let imageView = hairlineImageViewInNavigationBar(subview) {
return imageView
}
}
return nil
}
}
| mit | 0302c1a3449dd401c2b8c49550c9d0a3 | 24.973684 | 81 | 0.629179 | 5.140625 | false | false | false | false |
psturm-swift/SwiftySignals | Sources/DistinctModifier.swift | 1 | 2275 | // Copyright (c) 2017 Patrick Sturm <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public final class DistinctModifier<T: Comparable>: ModifierType {
public typealias MessageIn = T
public typealias MessageOut = T
private var _lastMessage: T? = nil
fileprivate init() {
}
public func process(message: MessageIn, notify: @escaping (MessageOut) -> Void) {
let lastMessage = self._lastMessage
if lastMessage == nil || lastMessage! != message {
self._lastMessage = message
notify(message)
}
}
}
public typealias DistinctObservable<O: ObservableType> = ModifierObservable<O, O.MessageOut>
public typealias DistinctEndPoint<O: ObservableType> = EndPoint<DistinctObservable<O>>
extension EndPoint where O.MessageOut: Comparable {
public func distinct() -> DistinctEndPoint<SourceObservable> {
let distinctObservable = DistinctObservable(
source: self.observable,
modifier: DistinctModifier<SourceObservable.MessageOut>())
return DistinctEndPoint<SourceObservable>(
observable: distinctObservable,
dispatchQueue: self.dispatchQueue)
}
}
| mit | 86af82cd763cd7080eb8cc71a0ec81e9 | 41.12963 | 92 | 0.723077 | 4.799578 | false | false | false | false |
AboutCXJ/30DaysOfSwift | Project 13 - AnimateTableViewCell/Project 13 - AnimateTableViewCell/SecondAnimateVC.swift | 1 | 3651 | //
// SecondAnimateVC.swift
// Project 13 - AnimateTableViewCell
//
// Created by sfzx on 2017/11/1.
// Copyright © 2017年 陈鑫杰. All rights reserved.
//
import UIKit
fileprivate let gradientTCellID = "SecondAnimateVCID"
class SecondAnimateVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
}
override func viewWillAppear(_ animated: Bool) {
self.animateTable()
}
func setupUI() {
self.navigationController?.navigationBar.isHidden = true
self.view.addSubview(self.tableView)
}
override var prefersStatusBarHidden: Bool{
get{
return true
}
}
//MARK: - handle
func animateTable() {
self.tableView.reloadData()
let cells = tableView.visibleCells
let tableHeight: CGFloat = tableView.bounds.size.height
for (index, cell) in cells.enumerated() {
cell.transform = CGAffineTransform(translationX: 0, y: tableHeight)
UIView.animate(withDuration: 1.0, delay: 0.05 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: {
cell.transform = CGAffineTransform.identity
}, completion: nil)
}
}
//MARK: - 懒加载
lazy var tableView: UITableView = {
let tableView = UITableView(frame: self.view.bounds)
tableView.separatorStyle = .none
tableView.register(GradientTCell.self, forCellReuseIdentifier: gradientTCellID)
tableView.delegate = self
tableView.dataSource = self
return tableView
}()
lazy var datas: [String] = {
let datas = ["Read 3 article on Medium", "Cleanup bedroom", "Go for a run", "Hit the gym", "Build another swift project", "Movement training", "Fix the layout problem of a client project", "Write the experience of #30daysSwift", "Inbox Zero", "Booking the ticket to Chengdu", "Test the Adobe Project Comet", "Hop on a call to mom"]
return datas
}()
}
//MARK: - UITableViewDelegate
extension SecondAnimateVC: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
}
//MARK: - UITableViewDataSource
extension SecondAnimateVC: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.datas.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: gradientTCellID, for: indexPath) as! GradientTCell
cell.textLabel?.text = self.datas[indexPath.row]
//渐变色
let color = CGFloat(indexPath.row) / CGFloat(self.datas.count) * 0.8
cell.backgroundColor = UIColor.init(red: 1.0, green: color, blue: 0, alpha: 1.0)
return cell
}
// func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// let animation = CAKeyframeAnimation(keyPath: "transform")
// animation.duration = 1.0
// let values = [
// NSValue(caTransform3D: CATransform3DMakeScale(0.5, 0.5, 1.0)),
// NSValue(caTransform3D: CATransform3DMakeScale(1.5, 1.5, 1.0)),
// NSValue(caTransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)),
// ]
// animation.values = values
//
// cell.layer.add(animation, forKey: nil)
// }
}
| mit | 83a56cc64fe006ac4578a5df27621b66 | 31.410714 | 339 | 0.633884 | 4.531835 | false | false | false | false |
duycao2506/SASCoffeeIOS | SAS Coffee/View/CardTableViewCell.swift | 1 | 1269 | //
// CardTableViewCell.swift
// Education Platform
//
// Created by Duy Cao on 12/9/16.
// Copyright © 2016 Duy Cao. All rights reserved.
//
import UIKit
class CardTableViewCell: SuperTableViewCell {
@IBOutlet weak var backgroundCardView : UIView!
override func awakeFromNib() {
super.awakeFromNib()
if backgroundCardView == nil {
self.backgroundCardView = UIView()
self.contentView.addSubview(self.backgroundCardView)
self.contentView.sendSubview(toBack: self.backgroundCardView)
self.backgroundCardView.autoPinEdgesToSuperviewEdges(with: .init(top: 16, left: 16, bottom: 16, right: 16))
}
self.backgroundCardView.backgroundColor = UIColor.white
self.backgroundCardView.layer.cornerRadius = 3.0
self.backgroundCardView.layer.masksToBounds = false
self.backgroundCardView.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor
self.backgroundCardView.layer.shadowOffset = CGSize(width: 0, height: 2.0)
self.backgroundCardView.layer.shadowOpacity = 0.8
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| gpl-3.0 | 8f3545da88608699fc94be711baebe25 | 33.27027 | 119 | 0.681388 | 4.80303 | false | false | false | false |
dnevera/ImageMetalling | ImageMetalling-03/ImageMetalling-03/IMPMetalaGramFilter.swift | 1 | 6619 | //
// IMPMetalaGramFilter.swift
// ImageMetalling-03
//
// Created by denis svinarchuk on 28.11.15.
// Copyright © 2015 IMetalling. All rights reserved.
//
import UIKit
///
/// Металаграмический фильтр. Созадем не с нуля, а используем готовый
/// набор классов еще более больше скрывающий слой работающий с GPU:
/// https://bitbucket.org/degrader/degradr-core-3
///
/// DPCore3 framework - по сути специализированный модульный конструктор
/// для создания собственных прикладных image-фильтров.
///
/// Тут воспользуемся готовыми классами: читалкой файла формата .cube, в котором
/// хранят заранее подготовленные CLUT - Color LookUp Table.
/// .cube - это открытая спецификация Adobe, поддерживается кучей генераторов CLUT
///
///
class IMPMetalaGramFilter: DPFilter {
//
// Кэшируем CLUTs в справочник.
// По ключу можно получить готовую текстуру объекта класса типа DPImageProvider.
//
// Все фильтры наследуемые от DPFilter из DPCore3 framework имеют два свойства:
// - .source - исходное изображение
// - .destination - изображение после преобразования
// Оба свойства являются ссылками на объекты класса DPImageProvider.
//
// Image provider-ы - абстрактное представление произвольного изображения и его сырых данных представленных
// в текстуре записанной в область памяти GPU.
// Фреймворк содержит начальный набор провайдеров к jpeg-файлам, UIImage/CGImage,
// NSData, frame-буферу видео-изображения.
// Нам для работы c lookup таблицами нунеж CLUT-провайдер, который, по сути,
// явлеется таким же изображением (текстурой), и позиция цвета в виде координаты является отображением
// входного цвета в выходной
//
// DPCubeLUTFileProvider - поддерживает обе формы представления CLUT: 1D и 2D
//
// В качестве упражнения можно также написать провайдер CLUT из png-файлов.
//
private var lutTables = [String:DPCubeLUTFileProvider]()
//
// Фильтр мапинга картинки в новое цветовое пространства представленное CLUT-провайдере.
//
private var lutFilter:DPCLUTFilter!
//
// Просто сервисная функция для получения CLUT по имени файла. Файл добавляется в проект приложения.
//
private func getLUT(name:String) -> DPCubeLUTFileProvider? {
do{
if let lut = lutTables[name]{
return lut
}
else {
let lut = try DPCubeLUTFileProvider.newLUTNamed(name, context: context)
lutTables[name] = lut
return lut
}
}
catch let error as NSError{
//
// Перед падением программы напишем что пошло не так,
// скорее всего в проект не добавили файла или формат файла левый
//
NSLog("%@", error)
}
return nil
}
//
// Управление выбором CLUT по имени.
//
var name:String!{
didSet(oldValue){
if oldValue != name {
lutFilter.lutSource=getLUT(name)
//
// Скажем фильтру, что данные протухли.
// Когда пишется свой собственный кастомный фильтр с помощью
// DPCore3 необходимо выставлять флажок протухания (dirty)
// при изменении параметров фильтра.
//
self.dirty = true
}
}
}
//
// Управления степенью воздействия
//
var opacity:Float{
get{
return lutFilter.adjustment.blending.opacity
}
set(value){
lutFilter.adjustment.blending.opacity=value
}
}
init(context aContext: DPContext!, initialLUTName:String) {
super.init(vertex: DP_VERTEX_DEF_FUNCTION, withFragment: DP_FRAGMENT_DEF_FUNCTION, context: aContext)
//
// если CLUT-файл добавлен в проект, формат файла соответствует спекам:
//
name = initialLUTName
if let lut = getLUT(name){
lutFilter = DPCLUTFilter(context: self.context, lut: lut, type: lut.type)
//
// добавляем в цепочку новый фильтр,
// если нам нужна обработка нескольких фильтров можно подцепить несколько
// например анализатор гистограммы:
// DPHistogramAnalizer, к которой в свою очередь DPHistogramZonesSolver для решения
// задачи коррекции экспозиции, к примеру.
//
// Пока просто добавляем фильтра мапинга цветовых пространств через CLUT
//
self.addFilter(lutFilter)
}
}
required init!(context aContext: DPContext!) {
//
// Не даем создать фильтр без инициализации таблицей
//
fatalError("init(context:) does not create initial filter without LUT")
}
}
| mit | bb70f723174e0a4a1a7e702e3a89ab1b | 33.64539 | 111 | 0.621699 | 3.278523 | false | false | false | false |
phr85/Shopy | Pods/Sync/Source/Sync/Sync.swift | 1 | 15098 | import CoreData
import SYNCPropertyMapper
import DATAStack
public protocol SyncDelegate: class {
/// Called before the JSON is used to create a new NSManagedObject.
///
/// - parameter sync: The Sync operation.
/// - parameter json: The JSON used for filling the contents of the NSManagedObject.
/// - parameter entityNamed: The name of the entity to be created.
/// - parameter parent: The new item's parent. Do not mutate the contents of this element.
///
/// - returns: The JSON used to create the new NSManagedObject.
func sync(_ sync: Sync, willInsert json: [String: Any], in entityNamed: String, parent: NSManagedObject?) -> [String: Any]
}
@objc public class Sync: Operation {
public weak var delegate: SyncDelegate?
public struct OperationOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let Insert = OperationOptions(rawValue: 1 << 0)
public static let Update = OperationOptions(rawValue: 1 << 1)
public static let Delete = OperationOptions(rawValue: 1 << 2)
public static let All: OperationOptions = [.Insert, .Update, .Delete]
}
var downloadFinished = false
var downloadExecuting = false
var downloadCancelled = false
public override var isFinished: Bool {
return self.downloadFinished
}
public override var isExecuting: Bool {
return self.downloadExecuting
}
public override var isCancelled: Bool {
return self.downloadCancelled
}
public override var isAsynchronous: Bool {
return !TestCheck.isTesting
}
var changes: [[String: Any]]
var entityName: String
var predicate: NSPredicate?
var filterOperations = Sync.OperationOptions.All
var parent: NSManagedObject?
var parentRelationship: NSRelationshipDescription?
var context: NSManagedObjectContext?
unowned var dataStack: DATAStack
public init(changes: [[String: Any]], inEntityNamed entityName: String, predicate: NSPredicate? = nil, parent: NSManagedObject? = nil, parentRelationship: NSRelationshipDescription? = nil, context: NSManagedObjectContext? = nil, dataStack: DATAStack, operations: Sync.OperationOptions = .All) {
self.changes = changes
self.entityName = entityName
self.predicate = predicate
self.parent = parent
self.parentRelationship = parentRelationship
self.context = context
self.dataStack = dataStack
self.filterOperations = operations
}
func updateExecuting(_ isExecuting: Bool) {
self.willChangeValue(forKey: "isExecuting")
self.downloadExecuting = isExecuting
self.didChangeValue(forKey: "isExecuting")
}
func updateFinished(_ isFinished: Bool) {
self.willChangeValue(forKey: "isFinished")
self.downloadFinished = isFinished
self.didChangeValue(forKey: "isFinished")
}
public override func start() {
if self.isCancelled {
self.updateExecuting(false)
self.updateFinished(true)
} else {
self.updateExecuting(true)
if let context = self.context {
context.perform {
self.perform(using: context)
}
} else {
self.dataStack.performInNewBackgroundContext { backgroundContext in
self.perform(using: backgroundContext)
}
}
}
}
func perform(using context: NSManagedObjectContext) {
do {
try Sync.changes(self.changes, inEntityNamed: self.entityName, predicate: self.predicate, parent: self.parent, parentRelationship: self.parentRelationship, inContext: context, operations: self.filterOperations, shouldContinueBlock: { () -> Bool in
return !self.isCancelled
}, objectJSONBlock: { objectJSON -> [String: Any] in
return self.delegate?.sync(self, willInsert: objectJSON, in: self.entityName, parent: self.parent) ?? objectJSON
})
} catch let error as NSError {
print("Failed syncing changes \(error)")
self.updateExecuting(false)
self.updateFinished(true)
}
}
public override func cancel() {
func updateCancelled(_ isCancelled: Bool) {
self.willChangeValue(forKey: "isCancelled")
self.downloadCancelled = isCancelled
self.didChangeValue(forKey: "isCancelled")
}
updateCancelled(true)
}
public class func changes(_ changes: [[String: Any]], inEntityNamed entityName: String, predicate: NSPredicate?, parent: NSManagedObject?, parentRelationship: NSRelationshipDescription?, inContext context: NSManagedObjectContext, operations: Sync.OperationOptions, completion: ((_ error: NSError?) -> Void)?) {
var error: NSError?
do {
try self.changes(changes, inEntityNamed: entityName, predicate: predicate, parent: parent, parentRelationship: parentRelationship, inContext: context, operations: operations, shouldContinueBlock: nil, objectJSONBlock: nil)
} catch let syncError as NSError {
error = syncError
}
if TestCheck.isTesting {
completion?(error)
} else {
DispatchQueue.main.async {
completion?(error)
}
}
}
class func changes(_ changes: [[String: Any]], inEntityNamed entityName: String, predicate: NSPredicate?, parent: NSManagedObject?, parentRelationship: NSRelationshipDescription?, inContext context: NSManagedObjectContext, operations: Sync.OperationOptions, shouldContinueBlock: (() -> Bool)?, objectJSONBlock: ((_ objectJSON: [String: Any]) -> [String: Any])?) throws {
guard let entity = NSEntityDescription.entity(forEntityName: entityName, in: context) else { fatalError("Entity named \(entityName) not found.") }
let localPrimaryKey = entity.sync_localPrimaryKey()
let remotePrimaryKey = entity.sync_remotePrimaryKey()
let shouldLookForParent = parent == nil && predicate == nil
var finalPredicate = predicate
if let parentEntity = entity.sync_parentEntity(), shouldLookForParent {
finalPredicate = NSPredicate(format: "%K = nil", parentEntity.name)
}
if localPrimaryKey.isEmpty {
fatalError("Local primary key not found for entity: \(entityName), add a primary key named id or mark an existing attribute using hyper.isPrimaryKey")
}
if remotePrimaryKey.isEmpty {
fatalError("Remote primary key not found for entity: \(entityName), we were looking for id, if your remote ID has a different name consider using hyper.remoteKey to map to the right value")
}
let dataFilterOperations = DATAFilter.Operation(rawValue: operations.rawValue)
DATAFilter.changes(changes, inEntityNamed: entityName, predicate: finalPredicate, operations: dataFilterOperations, localPrimaryKey: localPrimaryKey, remotePrimaryKey: remotePrimaryKey, context: context, inserted: { JSON in
let shouldContinue = shouldContinueBlock?() ?? true
guard shouldContinue else { return }
let created = NSEntityDescription.insertNewObject(forEntityName: entityName, into: context)
let interceptedJSON = objectJSONBlock?(JSON) ?? JSON
created.sync_fill(with: interceptedJSON, parent: parent, parentRelationship: parentRelationship, context: context, operations: operations, shouldContinueBlock: shouldContinueBlock, objectJSONBlock: objectJSONBlock)
}) { JSON, updatedObject in
let shouldContinue = shouldContinueBlock?() ?? true
guard shouldContinue else { return }
updatedObject.sync_fill(with: JSON, parent: parent, parentRelationship: parentRelationship, context: context, operations: operations, shouldContinueBlock: shouldContinueBlock, objectJSONBlock: objectJSONBlock)
}
if context.hasChanges {
let shouldContinue = shouldContinueBlock?() ?? true
if shouldContinue {
try context.save()
} else {
context.reset()
}
}
}
/// Fetches a managed object for the provided primary key in an specific entity.
///
/// - Parameters:
/// - id: The primary key.
/// - entityName: The name of the entity.
/// - context: The context to be used, make sure that this method gets called in the same thread as the context using `perform` or `performAndWait`.
/// - Returns: A managed object for a provided primary key in an specific entity.
/// - Throws: Core Data related issues.
@discardableResult
public class func fetch<ResultType: NSManagedObject>(_ id: Any, inEntityNamed entityName: String, using context: NSManagedObjectContext) throws -> ResultType? {
Sync.verifyContextSafety(context: context)
guard let entity = NSEntityDescription.entity(forEntityName: entityName, in: context) else { abort() }
let localPrimaryKey = entity.sync_localPrimaryKey()
let fetchRequest = NSFetchRequest<ResultType>(entityName: entityName)
fetchRequest.predicate = NSPredicate(format: "%K = %@", localPrimaryKey, id as! NSObject)
let objects = try context.fetch(fetchRequest)
return objects.first
}
/// Inserts or updates an object using the given changes dictionary in an specific entity.
///
/// - Parameters:
/// - changes: The dictionary to be used to update or create the object.
/// - entityName: The name of the entity.
/// - context: The context to be used, make sure that this method gets called in the same thread as the context using `perform` or `performAndWait`.
/// - Returns: The inserted or updated object. If you call this method from a background context, make sure to not use this on the main thread.
/// - Throws: Core Data related issues.
@discardableResult
public class func insertOrUpdate<ResultType: NSManagedObject>(_ changes: [String: Any], inEntityNamed entityName: String, using context: NSManagedObjectContext) throws -> ResultType {
Sync.verifyContextSafety(context: context)
guard let entity = NSEntityDescription.entity(forEntityName: entityName, in: context) else { abort() }
let localPrimaryKey = entity.sync_localPrimaryKey()
let remotePrimaryKey = entity.sync_remotePrimaryKey()
guard let id = changes[remotePrimaryKey] as? NSObject else { fatalError("Couldn't find primary key \(remotePrimaryKey) in JSON for object in entity \(entityName)") }
let fetchRequest = NSFetchRequest<ResultType>(entityName: entityName)
fetchRequest.predicate = NSPredicate(format: "%K = %@", localPrimaryKey, id)
let fetchedObjects = try context.fetch(fetchRequest)
let insertedOrUpdatedObjects: [ResultType]
if fetchedObjects.count > 0 {
insertedOrUpdatedObjects = fetchedObjects
} else {
let inserted = NSEntityDescription.insertNewObject(forEntityName: entityName, into: context) as! ResultType
insertedOrUpdatedObjects = [inserted]
}
for object in insertedOrUpdatedObjects {
object.sync_fill(with: changes, parent: nil, parentRelationship: nil, context: context, operations: [.All], shouldContinueBlock: nil, objectJSONBlock: nil)
}
if context.hasChanges {
try context.save()
}
return insertedOrUpdatedObjects.first!
}
/// Updates an object using the given changes dictionary for the provided primary key in an specific entity.
///
/// - Parameters:
/// - id: The primary key.
/// - changes: The dictionary to be used to update the object.
/// - entityName: The name of the entity.
/// - context: The context to be used, make sure that this method gets called in the same thread as the context using `perform` or `performAndWait`.
/// - Returns: The updated object, if not found it returns nil. If you call this method from a background context, make sure to not use this on the main thread.
/// - Throws: Core Data related issues.
@discardableResult
public class func update<ResultType: NSManagedObject>(_ id: Any, with changes: [String: Any], inEntityNamed entityName: String, using context: NSManagedObjectContext) throws -> ResultType? {
Sync.verifyContextSafety(context: context)
guard let entity = NSEntityDescription.entity(forEntityName: entityName, in: context) else { fatalError("Couldn't find an entity named \(entityName)") }
let localPrimaryKey = entity.sync_localPrimaryKey()
let fetchRequest = NSFetchRequest<ResultType>(entityName: entityName)
fetchRequest.predicate = NSPredicate(format: "%K = %@", localPrimaryKey, id as! NSObject)
let objects = try context.fetch(fetchRequest)
for updated in objects {
updated.sync_fill(with: changes, parent: nil, parentRelationship: nil, context: context, operations: [.All], shouldContinueBlock: nil, objectJSONBlock: nil)
}
if context.hasChanges {
try context.save()
}
return objects.first
}
/// Deletes a managed object for the provided primary key in an specific entity.
///
/// - Parameters:
/// - id: The primary key.
/// - entityName: The name of the entity.
/// - context: The context to be used, make sure that this method gets called in the same thread as the context using `perform` or `performAndWait`.
/// - Throws: Core Data related issues.
public class func delete(_ id: Any, inEntityNamed entityName: String, using context: NSManagedObjectContext) throws {
Sync.verifyContextSafety(context: context)
guard let entity = NSEntityDescription.entity(forEntityName: entityName, in: context) else { abort() }
let localPrimaryKey = entity.sync_localPrimaryKey()
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName)
fetchRequest.predicate = NSPredicate(format: "%K = %@", localPrimaryKey, id as! NSObject)
let objects = try context.fetch(fetchRequest)
guard objects.count > 0 else { return }
for deletedObject in objects {
context.delete(deletedObject)
}
if context.hasChanges {
try context.save()
}
}
fileprivate class func verifyContextSafety(context: NSManagedObjectContext) {
if Thread.isMainThread && context.concurrencyType == .privateQueueConcurrencyType {
fatalError("Background context used in the main thread. Use context's `perform` method")
}
if !Thread.isMainThread && context.concurrencyType == .mainQueueConcurrencyType {
fatalError("Main context used in a background thread. Use context's `perform` method.")
}
}
}
| mit | 60a1442475037ac49165e919adc22743 | 46.477987 | 374 | 0.673533 | 5.293829 | false | false | false | false |
Tangdixi/DCExplosion | Source/Explodable.swift | 1 | 7491 | //
// Explodable.swift
// Example (Explodable)
//
// Created by tang dixi on 7/6/2016.
// Copyright © 2016 Tangdixi. All rights reserved.
//
import UIKit
protocol Explodable {}
/**
The explode direction of the animation
- Top: The fragment will explode upward
- Left: The fragment will explode leftward
- Right: The fragment will explode rightward
- Bottom: The fragment will explode downward
- Chaos: The fragment will explode randomly
*/
enum ExplodeDirection {
case top, left, bottom, right, chaos
fileprivate func explodeDirection(_ offset:CGSize) -> CGVector {
switch self {
case .top:
let xOffset = random(from: -16.8, to: 16.8)
let yOffset = random(from: -offset.height*goldenRatio, to: 0)
return CGVector(dx: xOffset, dy: yOffset)
case .left:
let xOffset = random(from: -offset.width*goldenRatio, to: 0)
let yOffset = random(from: -16.8, to: 16.8)
return CGVector(dx: xOffset, dy: yOffset)
case .bottom:
let xOffset = random(from: -16.8, to: 16.8)
let yOffset = random(from: 0, to: offset.height*goldenRatio)
return CGVector(dx: xOffset, dy: yOffset)
case .right:
let xOffset = random(from: 0, to: offset.width*goldenRatio)
let yOffset = random(from: -16.8, to: 16.8)
return CGVector(dx: xOffset, dy: yOffset)
case .chaos:
let xOffset = random(from: -offset.width*goldenRatio, to: offset.width*goldenRatio)
let yOffset = random(from: -offset.height*goldenRatio, to: offset.height*goldenRatio)
return CGVector(dx: xOffset, dy: yOffset)
}
}
}
extension Explodable where Self:UIView {
/**
Explode a view using the specified duration and direction
- Parameter duration: The animation duration
- Parameter direction: The explode direction, default is `ExplodeDirection.Chaos`
*/
func explode(_ direction:ExplodeDirection = .chaos, duration:Double) {
explode(direction, duration: duration) {}
}
/**
Explode a view using the specified duration ,direction and completion handler
- Parameter duration: The total duration of the animation
- Parameter direction: The explode direction, default is `ExplodeDirection.Chaos`
- Parameter completion: A closure to be executed when the animation sequence ends.
*/
func explode(_ direction:ExplodeDirection = .chaos, duration:Double, completion:@escaping (()->Void)) {
guard let containerView = self.superview else { fatalError() }
let fragments = generateFragmentsFrom(self, with: splitRatio, in: containerView)
self.alpha = 0
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIViewAnimationOptions.curveEaseOut,
animations: {
fragments.forEach {
let direction = direction.explodeDirection($0.superview!.frame.size)
let explodeAngle = random(from: -CGFloat(M_PI)*goldenRatio, to: CGFloat(M_PI)*goldenRatio)
let scale = 0.01 + random(from: 0.01, to: goldenRatio)
let translateTransform = CGAffineTransform(translationX: direction.dx, y: direction.dy)
let angleTransform = translateTransform.rotated(by: explodeAngle)
let scaleTransform = angleTransform.scaledBy(x: scale, y: scale)
$0.transform = scaleTransform
$0.alpha = 0
}
},
completion: { _ in
fragments.forEach {
$0.removeFromSuperview()
}
self.removeFromSuperview()
self.alpha = 1
completion()
})
}
}
extension Explodable where Self:UITableView {
/**
Remove a row in tableView with explosion animation
- Parameter indexPath: An indexPath locate a row in _tableView_
- Parameter duration: The total duration of the animation
- Parameter direction: The explode direction, default is _ExplodeDirection.Chaos_
- Parameter completion: A closure to be executed when the animation sqquence ends, also you should update the dataSource here
*/
func explodeRowAtIndexPath(_ indexPath:IndexPath, duration:Double, direction:ExplodeDirection = .chaos, completion:@escaping ()->Void) {
if self.exploding == true {
return
}
guard let cell = self.cellForRow(at: indexPath) else { return }
if cell.backgroundView == nil {
cell.backgroundView = UIView()
}
let fragments = generateFragmentsFrom(cell, with: 10, in: cell)
cell.contentView.alpha = 0
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIViewAnimationOptions.curveLinear,
animations: {
self.exploding = true
fragments.forEach {
let direction = direction.explodeDirection($0.superview!.frame.size)
let explodeAngle = random(from: -CGFloat(M_PI)*goldenRatio, to: CGFloat(M_PI)*goldenRatio)
let scale = 0.01 + random(from: 0.01, to: goldenRatio)
let translateTransform = CGAffineTransform(translationX: direction.dx, y: direction.dy)
let angleTransform = translateTransform.rotated(by: explodeAngle)
let scaleTransform = angleTransform.scaledBy(x: scale, y: scale)
$0.transform = scaleTransform
$0.alpha = 0
}
},
completion: { _ in
fragments.forEach {
$0.removeFromSuperview()
}
completion()
CATransaction.begin()
CATransaction.setCompletionBlock {
cell.contentView.alpha = 1
}
self.deleteRows(at: [indexPath], with: .none)
CATransaction.commit()
self.exploding = false
})
}
}
// MARK: - Private Stuff
/// Add a `explosing` variation to UITableView in runtime
private extension UITableView {
struct AssociatedKeys {
static var associatedName = "exploding"
}
var exploding:Bool {
get {
guard let exploding = objc_getAssociatedObject(self, &AssociatedKeys.associatedName) as? Bool else { return false }
return exploding
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.associatedName, newValue as Bool, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
private let goldenRatio = CGFloat(0.625)
private let splitRatio = CGFloat(10)
private func generateFragmentsFrom(_ originView:UIView, with splitRatio:CGFloat, in containerView:UIView) -> [UIView] {
let size = originView.frame.size
let snapshots = originView.snapshotView(afterScreenUpdates: true)
var fragments = [UIView]()
let shortSide = min(size.width, size.height)
let gap = max(20, shortSide/splitRatio)
for x in stride(from: 0.0, to: Double(size.width), by: Double(gap)) {
for y in stride(from: 0.0, to: Double(size.height), by: Double(gap)) {
let fragmentRect = CGRect(x: CGFloat(x), y: CGFloat(y), width: size.width/splitRatio, height: size.width/splitRatio)
let fragment = snapshots?.resizableSnapshotView(from: fragmentRect, afterScreenUpdates: false, withCapInsets: UIEdgeInsets.zero)
fragment?.frame = originView.convert(fragmentRect, to: containerView)
containerView.addSubview(fragment!)
fragments.append(fragment!)
}
}
return fragments
}
private func random(from lowerBound:CGFloat, to upperBound:CGFloat) -> CGFloat {
return CGFloat(arc4random_uniform(UInt32(upperBound - lowerBound))) + lowerBound
}
| mit | f21dc5d22dda2160f30ff96ce9b04154 | 33.837209 | 151 | 0.670895 | 4.392962 | false | false | false | false |
alexhillc/AXPhotoViewer | Source/Classes/Transition Controller + Animators/AXPhotosDismissalAnimator.swift | 1 | 31419 | //
// AXPhotosDismissalAnimator.swift
// AXPhotoViewer
//
// Created by Alex Hill on 6/5/18.
//
import UIKit
#if os(iOS)
import FLAnimatedImage
#elseif os(tvOS)
import FLAnimatedImage_tvOS
#endif
class AXPhotosDismissalAnimator: AXPhotosTransitionAnimator, UIViewControllerInteractiveTransitioning {
#if os(iOS)
/// The distance threshold at which the interactive controller will dismiss upon end touches.
fileprivate let dismissalPercentThreshold: CGFloat = 0.14
/// The velocity threshold at which the interactive controller will dismiss upon end touches.
fileprivate let dismissalVelocityYThreshold: CGFloat = 400
/// The velocity threshold at which the interactive controller will dismiss in any direction the user is swiping.
fileprivate let dismissalVelocityAnyDirectionThreshold: CGFloat = 1000
// Interactive dismissal transition tracking
fileprivate var dismissalPercent: CGFloat = 0
fileprivate var directionalDismissalPercent: CGFloat = 0
fileprivate var dismissalVelocityY: CGFloat = 1
fileprivate var forceImmediateInteractiveDismissal = false
fileprivate var completeInteractiveDismissal = false
weak fileprivate var dismissalTransitionContext: UIViewControllerContextTransitioning?
fileprivate var imageViewInitialCenter: CGPoint = .zero
fileprivate var imageViewOriginalSuperview: UIView?
weak fileprivate var imageView: UIImageView?
weak fileprivate var overlayView: AXOverlayView?
fileprivate var topStackContainerInitialOriginY: CGFloat = .greatestFiniteMagnitude
fileprivate var bottomStackContainerInitialOriginY: CGFloat = .greatestFiniteMagnitude
fileprivate var overlayViewOriginalSuperview: UIView?
#endif
/// Pending animations that can occur when interactive dismissal has not been triggered by the system,
/// but our pan gesture recognizer is receiving touch events. Processed as soon as the interactive dismissal has been set up.
fileprivate var pendingChanges = [() -> Void]()
// MARK: - UIViewControllerAnimatedTransitioning
override func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let to = transitionContext.viewController(forKey: .to),
let from = transitionContext.viewController(forKey: .from) else {
assertionFailure(
"""
Unable to resolve some necessary properties in order to transition. \
This should never happen. If this does happen, the animator will complete \
the \"transition\" and return immediately.
"""
)
if transitionContext.isInteractive {
transitionContext.finishInteractiveTransition()
}
transitionContext.completeTransition(true)
return
}
var photosViewController: AXPhotosViewController
if let from = from as? AXPhotosViewController {
photosViewController = from
} else {
guard let childViewController = from.children.filter({ $0 is AXPhotosViewController }).first as? AXPhotosViewController else {
assertionFailure(
"""
Could not find AXPhotosViewController in container's children. \
This should never happen. If this does happen, the animator will complete \
the \"transition\" and return immediately.
"""
)
if transitionContext.isInteractive {
transitionContext.finishInteractiveTransition()
}
transitionContext.completeTransition(true)
return
}
photosViewController = childViewController
}
guard let imageView = photosViewController.currentPhotoViewController?.zoomingImageView.imageView as UIImageView? else {
assertionFailure(
"""
Unable to resolve some necessary properties in order to transition. \
This should never happen. If this does happen, the animator will complete \
the \"transition\" and return immediately.
"""
)
if transitionContext.isInteractive {
transitionContext.finishInteractiveTransition()
}
transitionContext.completeTransition(true)
return
}
let presentersViewRemoved = from.presentationController?.shouldRemovePresentersView ?? false
if to.view.superview != transitionContext.containerView && presentersViewRemoved {
to.view.frame = transitionContext.finalFrame(for: to)
transitionContext.containerView.addSubview(to.view)
}
if self.fadeView == nil {
let fadeView = self.transitionInfo.fadingBackdropView()
fadeView.frame = transitionContext.finalFrame(for: from)
transitionContext.containerView.insertSubview(fadeView, aboveSubview: to.view)
self.fadeView = fadeView
}
if from.view.superview != transitionContext.containerView {
from.view.frame = transitionContext.finalFrame(for: from)
transitionContext.containerView.addSubview(from.view)
}
transitionContext.containerView.layoutIfNeeded()
let imageViewFrame = imageView.frame
imageView.transform = .identity
imageView.frame = imageViewFrame
let imageViewCenter = transitionContext.containerView.convert(
imageView.center,
from: imageView.superview
)
let imageViewContainer = AXImageViewTransitionContainer(imageView: imageView)
imageViewContainer.transform = from.view.transform
imageViewContainer.center = imageViewCenter
transitionContext.containerView.addSubview(imageViewContainer)
imageViewContainer.layoutIfNeeded()
if self.canPerformContextualDismissal() {
let endingView = self.transitionInfo.endingView!
endingView.alpha = 0
}
photosViewController.overlayView.isHidden = true
var offscreenImageViewCenter: CGPoint?
let scaleAnimations = { [weak self] () in
guard let `self` = self else { return }
if self.canPerformContextualDismissal() {
let endingView = self.transitionInfo.endingView!
imageViewContainer.contentMode = endingView.contentMode
imageViewContainer.transform = .identity
imageViewContainer.frame = transitionContext.containerView.convert(
endingView.frame,
from: endingView.superview
)
imageViewContainer.layoutIfNeeded()
} else {
if let offscreenImageViewCenter = offscreenImageViewCenter {
imageViewContainer.center = offscreenImageViewCenter
}
}
}
let scaleCompletion = { [weak self] (_ finished: Bool) in
guard let `self` = self else { return }
self.delegate?.transitionAnimator(self, didCompleteDismissalWith: imageViewContainer.imageView)
if self.canPerformContextualDismissal() {
let endingView = self.transitionInfo.endingView!
if let imageView = imageViewContainer.imageView as? FLAnimatedImageView,
let endingView = endingView as? FLAnimatedImageView {
endingView.ax_syncFrames(with: imageView)
}
endingView.alpha = 1
}
imageViewContainer.removeFromSuperview()
if transitionContext.isInteractive {
transitionContext.finishInteractiveTransition()
}
transitionContext.completeTransition(true)
}
let fadeAnimations = { [weak self] in
self?.fadeView?.alpha = 0
from.view.alpha = 0
}
let fadeCompletion = { [weak self] (_ finished: Bool) in
self?.fadeView?.removeFromSuperview()
self?.fadeView = nil
}
var scaleAnimationOptions: UIView.AnimationOptions
var scaleInitialSpringVelocity: CGFloat
if self.canPerformContextualDismissal() {
scaleAnimationOptions = [.curveEaseInOut, .beginFromCurrentState, .allowAnimatedContent]
scaleInitialSpringVelocity = 0
} else {
#if os(iOS)
let extrapolated = self.extrapolateFinalCenter(for: imageViewContainer, in: transitionContext.containerView)
offscreenImageViewCenter = extrapolated.center
if self.forceImmediateInteractiveDismissal {
scaleAnimationOptions = [.curveEaseInOut, .beginFromCurrentState, .allowAnimatedContent]
scaleInitialSpringVelocity = 0
} else {
var divisor: CGFloat = 1
let changed = extrapolated.changed
if .ulpOfOne >= abs(changed - extrapolated.center.x) {
divisor = abs(changed - imageView.frame.origin.x)
} else {
divisor = abs(changed - imageView.frame.origin.y)
}
scaleAnimationOptions = [.curveLinear, .beginFromCurrentState, .allowAnimatedContent]
scaleInitialSpringVelocity = abs(self.dismissalVelocityY / divisor)
}
#else
scaleAnimationOptions = [.curveEaseInOut, .beginFromCurrentState, .allowAnimatedContent]
scaleInitialSpringVelocity = 0
#endif
}
UIView.animate(
withDuration: self.transitionDuration(using: transitionContext),
delay: 0,
usingSpringWithDamping: self.transitionInfo.dismissalSpringDampingRatio,
initialSpringVelocity: scaleInitialSpringVelocity,
options: scaleAnimationOptions,
animations: scaleAnimations,
completion: scaleCompletion
)
UIView.animate(
withDuration: self.transitionDuration(using: transitionContext) * self.fadeInOutTransitionRatio,
delay: 0,
options: [.curveEaseInOut],
animations: fadeAnimations,
completion: fadeCompletion
)
if self.canPerformContextualDismissal() {
let endingView = self.transitionInfo.endingView!
UIView.animateCornerRadii(
withDuration: self.transitionDuration(using: transitionContext) * self.fadeInOutTransitionRatio,
to: endingView.layer.cornerRadius,
views: [imageViewContainer]
)
}
}
// MARK: - UIViewControllerInteractiveTransitioning
func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) {
#if os(iOS)
self.dismissalTransitionContext = transitionContext
guard let to = transitionContext.viewController(forKey: .to),
let from = transitionContext.viewController(forKey: .from) else {
assertionFailure(
"""
Unable to resolve some necessary properties in order to transition. \
This should never happen. If this does happen, the animator will complete \
the \"transition\" and return immediately.
"""
)
if transitionContext.isInteractive {
transitionContext.finishInteractiveTransition()
}
transitionContext.completeTransition(true)
return
}
var photosViewController: AXPhotosViewController
if let from = from as? AXPhotosViewController {
photosViewController = from
} else {
guard let childViewController = from.children.filter({ $0 is AXPhotosViewController }).first as? AXPhotosViewController else {
assertionFailure(
"""
Could not find AXPhotosViewController in container's children. \
This should never happen. If this does happen, the animator will complete \
the \"transition\" and return immediately.
"""
)
if transitionContext.isInteractive {
transitionContext.finishInteractiveTransition()
}
transitionContext.completeTransition(true)
return
}
photosViewController = childViewController
}
guard let imageView = photosViewController.currentPhotoViewController?.zoomingImageView.imageView as UIImageView? else {
assertionFailure(
"""
Unable to resolve some necessary properties in order to transition. \
This should never happen. If this does happen, the animator will complete \
the \"transition\" and return immediately.
"""
)
if transitionContext.isInteractive {
transitionContext.finishInteractiveTransition()
}
transitionContext.completeTransition(true)
return
}
self.imageView = imageView
self.overlayView = photosViewController.overlayView
// if we're going to force an immediate dismissal, we can just return here
// this setup will be done in `animateDismissal(_:)`
if self.forceImmediateInteractiveDismissal {
self.processPendingChanges()
return
}
let presentersViewRemoved = from.presentationController?.shouldRemovePresentersView ?? false
if presentersViewRemoved {
to.view.frame = transitionContext.finalFrame(for: to)
transitionContext.containerView.addSubview(to.view)
}
let fadeView = self.transitionInfo.fadingBackdropView()
fadeView.frame = transitionContext.finalFrame(for: from)
transitionContext.containerView.insertSubview(fadeView, aboveSubview: to.view)
self.fadeView = fadeView
from.view.frame = transitionContext.finalFrame(for: from)
transitionContext.containerView.addSubview(from.view)
transitionContext.containerView.layoutIfNeeded()
self.imageViewOriginalSuperview = imageView.superview
imageView.center = transitionContext.containerView.convert(imageView.center, from: imageView.superview)
transitionContext.containerView.addSubview(imageView)
self.imageViewInitialCenter = imageView.center
let overlayView = photosViewController.overlayView
self.overlayViewOriginalSuperview = overlayView.superview
overlayView.frame = transitionContext.containerView.convert(overlayView.frame, from: overlayView.superview)
transitionContext.containerView.addSubview(overlayView)
self.topStackContainerInitialOriginY = overlayView.topStackContainer.frame.origin.y
self.bottomStackContainerInitialOriginY = overlayView.bottomStackContainer.frame.origin.y
from.view.alpha = 0
if self.canPerformContextualDismissal() {
guard let referenceView = self.transitionInfo.endingView else {
assertionFailure("No. ಠ_ಠ")
return
}
referenceView.alpha = 0
}
self.processPendingChanges()
#else
fatalError("Interactive animations are not supported on tvOS.")
#endif
}
#if os(iOS)
// MARK: - Cancel interactive transition
fileprivate func cancelTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let from = transitionContext.viewController(forKey: .from) else {
assertionFailure("No. ಠ_ಠ")
return
}
var photosViewController: AXPhotosViewController
if let from = from as? AXPhotosViewController {
photosViewController = from
} else {
guard let childViewController = from.children.filter({ $0 is AXPhotosViewController }).first as? AXPhotosViewController else {
assertionFailure("Could not find AXPhotosViewController in container's children.")
return
}
photosViewController = childViewController
}
guard let imageView = photosViewController.currentPhotoViewController?.zoomingImageView.imageView as UIImageView? else {
assertionFailure("No. ಠ_ಠ")
return
}
let overlayView = photosViewController.overlayView
let animations = { [weak self] () in
guard let `self` = self else { return }
imageView.center.y = self.imageViewInitialCenter.y
overlayView.topStackContainer.frame.origin.y = self.topStackContainerInitialOriginY
overlayView.bottomStackContainer.frame.origin.y = self.bottomStackContainerInitialOriginY
self.fadeView?.alpha = 1
}
let completion = { [weak self] (_ finished: Bool) in
guard let `self` = self else { return }
if self.canPerformContextualDismissal() {
guard let referenceView = self.transitionInfo.endingView else {
assertionFailure("No. ಠ_ಠ")
return
}
referenceView.alpha = 1
}
self.fadeView?.removeFromSuperview()
from.view.alpha = 1
imageView.frame = transitionContext.containerView.convert(imageView.frame, to: self.imageViewOriginalSuperview)
self.imageViewOriginalSuperview?.addSubview(imageView)
overlayView.frame = transitionContext.containerView.convert(overlayView.frame, to: self.overlayViewOriginalSuperview)
self.overlayViewOriginalSuperview?.addSubview(overlayView)
self.imageViewInitialCenter = .zero
self.imageViewOriginalSuperview = nil
self.topStackContainerInitialOriginY = .greatestFiniteMagnitude
self.bottomStackContainerInitialOriginY = .greatestFiniteMagnitude
self.overlayViewOriginalSuperview = nil
self.dismissalPercent = 0
self.directionalDismissalPercent = 0
self.dismissalVelocityY = 1
self.delegate?.transitionAnimatorDidCancelDismissal(self)
if transitionContext.isInteractive {
transitionContext.cancelInteractiveTransition()
}
transitionContext.completeTransition(false)
self.dismissalTransitionContext = nil
}
UIView.animate(
withDuration: self.transitionDuration(using: transitionContext),
delay: 0,
usingSpringWithDamping: self.transitionInfo.dismissalSpringDampingRatio,
initialSpringVelocity: 0,
options: [.curveEaseInOut, .beginFromCurrentState, .allowAnimatedContent],
animations: animations,
completion: completion
)
}
// MARK: - Interaction handling
public func didPanWithGestureRecognizer(_ sender: UIPanGestureRecognizer, in viewController: UIViewController) {
self.dismissalVelocityY = sender.velocity(in: sender.view).y
let translation = sender.translation(in: sender.view?.superview)
switch sender.state {
case .began:
self.overlayView = nil
let endingOrientation = UIApplication.shared.statusBarOrientation
let startingOrientation = endingOrientation.by(transforming: viewController.view.transform)
let shouldForceImmediateInteractiveDismissal = (startingOrientation != endingOrientation)
if shouldForceImmediateInteractiveDismissal {
// arbitrary dismissal percentages
self.directionalDismissalPercent = self.dismissalVelocityY > 0 ? 1 : -1
self.dismissalPercent = 1
self.forceImmediateInteractiveDismissal = true
self.completeInteractiveDismissal = true
// immediately trigger `cancelled` for dismissal
sender.isEnabled = false
}
case .changed:
let animation = { [weak self] in
guard let `self` = self,
let topStackContainer = self.overlayView?.topStackContainer,
let bottomStackContainer = self.overlayView?.bottomStackContainer else {
assertionFailure("No. ಠ_ಠ")
return
}
let height = UIScreen.main.bounds.size.height
self.directionalDismissalPercent = (translation.y > 0)
? min(1, translation.y / height)
: max(-1, translation.y / height)
self.dismissalPercent = min(1, abs(translation.y / height))
self.completeInteractiveDismissal = (self.dismissalPercent >= self.dismissalPercentThreshold)
|| (abs(self.dismissalVelocityY) >= self.dismissalVelocityYThreshold)
// this feels right-ish
let dismissalRatio = (1.2 * self.dismissalPercent / self.dismissalPercentThreshold)
let topStackContainerOriginY = max(
self.topStackContainerInitialOriginY - topStackContainer.frame.size.height,
self.topStackContainerInitialOriginY - (topStackContainer.frame.size.height * dismissalRatio)
)
let bottomStackContainerOriginY = min(
self.bottomStackContainerInitialOriginY + bottomStackContainer.frame.size.height,
self.bottomStackContainerInitialOriginY + (bottomStackContainer.frame.size.height * dismissalRatio)
)
let imageViewCenterY = self.imageViewInitialCenter.y + translation.y
UIView.performWithoutAnimation {
topStackContainer.frame.origin.y = topStackContainerOriginY
bottomStackContainer.frame.origin.y = bottomStackContainerOriginY
self.imageView?.center.y = imageViewCenterY
}
self.fadeView?.alpha = 1 - (1 * min(1, dismissalRatio))
}
if self.imageView == nil || self.overlayView == nil {
self.pendingChanges.append(animation)
return
}
animation()
case .ended:
fallthrough
case .cancelled:
let animation = { [weak self] in
guard let `self` = self,
let transitionContext = self.dismissalTransitionContext,
let _ = self.overlayView?.topStackContainer,
let _ = self.overlayView?.bottomStackContainer else {
return
}
if self.completeInteractiveDismissal {
self.animateTransition(using: transitionContext)
} else {
self.cancelTransition(using: transitionContext)
}
}
// `imageView`, `overlayView` set in `startInteractiveTransition(_:)`
if self.imageView == nil || self.overlayView == nil {
self.pendingChanges.append(animation)
return
}
animation()
default:
break
}
}
/// Extrapolate the "final" offscreen center value for an image view in a view given the starting and ending orientations.
///
/// - Parameters:
/// - imageView: The image view to retrieve the final offscreen center value for.
/// - view: The view that is containing the imageView. Most likely the superview.
/// - Returns: A tuple containing the final center of the imageView, as well as the value that was adjusted from the original `center` value.
fileprivate func extrapolateFinalCenter(for view: UIView,
in containingView: UIView) -> (center: CGPoint, changed: CGFloat) {
let endingOrientation = UIApplication.shared.statusBarOrientation
let startingOrientation = endingOrientation.by(transforming: view.transform)
let dismissFromBottom = (abs(self.dismissalVelocityY) > self.dismissalVelocityAnyDirectionThreshold)
? self.dismissalVelocityY >= 0
: self.directionalDismissalPercent >= 0
let viewRect = view.convert(view.bounds, to: containingView)
var viewCenter = view.center
switch startingOrientation {
case .landscapeLeft:
switch endingOrientation {
case .landscapeLeft:
if dismissFromBottom {
viewCenter.y = containingView.frame.size.height + (viewRect.size.height / 2)
} else {
viewCenter.y = -(viewRect.size.height / 2)
}
case .landscapeRight:
if dismissFromBottom {
viewCenter.y = -(viewRect.size.height / 2)
} else {
viewCenter.y = containingView.frame.size.height + (viewRect.size.height / 2)
}
case .portraitUpsideDown:
if dismissFromBottom {
viewCenter.x = -(viewRect.size.width / 2)
} else {
viewCenter.x = containingView.frame.size.width + (viewRect.size.width / 2)
}
default:
if dismissFromBottom {
viewCenter.x = containingView.frame.size.width + (viewRect.size.width / 2)
} else {
viewCenter.x = -(viewRect.size.width / 2)
}
}
case .landscapeRight:
switch endingOrientation {
case .landscapeLeft:
if dismissFromBottom {
viewCenter.y = -(viewRect.size.height / 2)
} else {
viewCenter.y = containingView.frame.size.height + (viewRect.size.height / 2)
}
case .landscapeRight:
if dismissFromBottom {
viewCenter.y = containingView.frame.size.height + (viewRect.size.height / 2)
} else {
viewCenter.y = -(viewRect.size.height / 2)
}
case .portraitUpsideDown:
if dismissFromBottom {
viewCenter.x = containingView.frame.size.width + (viewRect.size.width / 2)
} else {
viewCenter.x = -(viewRect.size.width / 2)
}
default:
if dismissFromBottom {
viewCenter.x = -(viewRect.size.width / 2)
} else {
viewCenter.x = containingView.frame.size.width + (viewRect.size.width / 2)
}
}
case .portraitUpsideDown:
switch endingOrientation {
case .landscapeLeft:
if dismissFromBottom {
viewCenter.x = containingView.frame.size.width + (viewRect.size.width / 2)
} else {
viewCenter.x = -(viewRect.size.width / 2)
}
case .landscapeRight:
if dismissFromBottom {
viewCenter.x = -(viewRect.size.width / 2)
} else {
viewCenter.x = containingView.frame.size.width + (viewRect.size.width / 2)
}
case .portraitUpsideDown:
if dismissFromBottom {
viewCenter.y = containingView.frame.size.height + (viewRect.size.height / 2)
} else {
viewCenter.y = -(viewRect.size.height / 2)
}
default:
if dismissFromBottom {
viewCenter.y = -(viewRect.size.height / 2)
} else {
viewCenter.y = containingView.frame.size.height + (viewRect.size.height / 2)
}
}
default:
switch endingOrientation {
case .landscapeLeft:
if dismissFromBottom {
viewCenter.x = -(viewRect.size.width / 2)
} else {
viewCenter.x = containingView.frame.size.width + (viewRect.size.width / 2)
}
case .landscapeRight:
if dismissFromBottom {
viewCenter.x = containingView.frame.size.width + (viewRect.size.width / 2)
} else {
viewCenter.x = -(viewRect.size.width / 2)
}
case .portraitUpsideDown:
if dismissFromBottom {
viewCenter.y = -(viewRect.size.height / 2)
} else {
viewCenter.y = containingView.frame.size.height + (viewRect.size.height / 2)
}
default:
if dismissFromBottom {
viewCenter.y = containingView.frame.size.height + (viewRect.size.height / 2)
} else {
viewCenter.y = -(viewRect.size.height / 2)
}
}
}
if abs(view.center.x - viewCenter.x) >= .ulpOfOne {
return (viewCenter, viewCenter.x)
} else {
return (viewCenter, viewCenter.y)
}
}
#endif
// MARK: - Helpers
fileprivate func canPerformContextualDismissal() -> Bool {
guard let endingView = self.transitionInfo.endingView, let endingViewSuperview = endingView.superview else {
return false
}
return UIScreen.main.bounds.intersects(endingViewSuperview.convert(endingView.frame, to: nil))
}
fileprivate func processPendingChanges() {
for animation in self.pendingChanges {
animation()
}
self.pendingChanges.removeAll()
}
}
| mit | eb579ee525667a1bccb06cbe1f78f41a | 42.071331 | 145 | 0.584031 | 6.502174 | false | false | false | false |
frankeh/swift-corelibs-libdispatch | src/swift/Private.swift | 1 | 15483 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Redeclarations of all SwiftPrivate functions with appropriate markup.
import CDispatch
@available(*, unavailable, renamed:"DispatchQueue.init(label:attributes:target:)")
public func dispatch_queue_create(_ label: UnsafePointer<Int8>?, _ attr: dispatch_queue_attr_t?) -> DispatchQueue
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.init(label:attributes:target:)")
public func dispatch_queue_create_with_target(_ label: UnsafePointer<Int8>?, _ attr: dispatch_queue_attr_t?, _ queue: DispatchQueue?) -> DispatchQueue
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchIO.init(type:fileDescriptor:queue:cleanupHandler:)")
public func dispatch_io_create(_ type: UInt, _ fd: Int32, _ queue: DispatchQueue, _ cleanup_handler: @escaping (Int32) -> Void) -> DispatchIO
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchIO.init(type:path:oflag:mode:queue:cleanupHandler:)")
public func dispatch_io_create_with_path(_ type: UInt, _ path: UnsafePointer<Int8>, _ oflag: Int32, _ mode: mode_t, _ queue: DispatchQueue, _ cleanup_handler: @escaping (Int32) -> Void) -> DispatchIO
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchIO.init(type:io:queue:cleanupHandler:)")
public func dispatch_io_create_with_io(_ type: UInt, _ io: DispatchIO, _ queue: DispatchQueue, _ cleanup_handler: @escaping (Int32) -> Void) -> DispatchIO
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchIO.read(fileDescriptor:length:queue:handler:)")
public func dispatch_read(_ fd: Int32, _ length: Int, _ queue: DispatchQueue, _ handler: @escaping (dispatch_data_t, Int32) -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchIO.read(self:offset:length:queue:ioHandler:)")
func dispatch_io_read(_ channel: DispatchIO, _ offset: off_t, _ length: Int, _ queue: DispatchQueue, _ io_handler: @escaping (Bool, dispatch_data_t?, Int32) -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchIO.write(self:offset:data:queue:ioHandler:)")
func dispatch_io_write(_ channel: DispatchIO, _ offset: off_t, _ data: dispatch_data_t, _ queue: DispatchQueue, _ io_handler: @escaping (Bool, dispatch_data_t?, Int32) -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchIO.write(fileDescriptor:data:queue:handler:)")
func dispatch_write(_ fd: Int32, _ data: dispatch_data_t, _ queue: DispatchQueue, _ handler: @escaping (dispatch_data_t?, Int32) -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchData.init(bytes:)")
public func dispatch_data_create(_ buffer: UnsafeRawPointer, _ size: Int, _ queue: DispatchQueue?, _ destructor: (() -> Void)?) -> dispatch_data_t
{
fatalError()
}
@available(*, unavailable, renamed:"getter:DispatchData.count(self:)")
public func dispatch_data_get_size(_ data: dispatch_data_t) -> Int
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchData.withUnsafeBytes(self:body:)")
public func dispatch_data_create_map(_ data: dispatch_data_t, _ buffer_ptr: UnsafeMutablePointer<UnsafeRawPointer?>?, _ size_ptr: UnsafeMutablePointer<Int>?) -> dispatch_data_t
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchData.append(self:_:)")
public func dispatch_data_create_concat(_ data1: dispatch_data_t, _ data2: dispatch_data_t) -> dispatch_data_t
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchData.subdata(self:in:)")
public func dispatch_data_create_subrange(_ data: dispatch_data_t, _ offset: Int, _ length: Int) -> dispatch_data_t
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchData.enumerateBytes(self:block:)")
public func dispatch_data_apply(_ data: dispatch_data_t, _ applier: @escaping (dispatch_data_t, Int, UnsafeRawPointer, Int) -> Bool) -> Bool
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchData.region(self:location:)")
public func dispatch_data_copy_region(_ data: dispatch_data_t, _ location: Int, _ offset_ptr: UnsafeMutablePointer<Int>) -> dispatch_data_t
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.asynchronously(self:group:qos:flags:execute:)")
public func dispatch_group_async(_ group: DispatchGroup, _ queue: DispatchQueue, _ block: @escaping () -> Void)
{
fatalError()
}
@available(*, unavailable, renamed: "DispatchGroup.notify(self:qos:flags:queue:execute:)")
public func dispatch_group_notify(_ group: DispatchGroup, _ queue: DispatchQueue, _ block: @escaping () -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchGroup.wait(self:timeout:)")
public func dispatch_group_wait(_ group: DispatchGroup, _ timeout: dispatch_time_t) -> Int
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchIO.close(self:flags:)")
public func dispatch_io_close(_ channel: DispatchIO, _ flags: UInt)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchIO.setInterval(self:interval:flags:)")
public func dispatch_io_set_interval(_ channel: DispatchIO, _ interval: UInt64, _ flags: UInt)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.apply(attributes:iterations:execute:)")
public func dispatch_apply(_ iterations: Int, _ queue: DispatchQueue, _ block: (Int) -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.asynchronously(self:execute:)")
public func dispatch_async(_ queue: DispatchQueue, _ block: @escaping () -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.global(attributes:)")
public func dispatch_get_global_queue(_ identifier: Int, _ flags: UInt) -> DispatchQueue
{
fatalError()
}
@available(*, unavailable, renamed: "DispatchQueue.main")
public func dispatch_get_main_queue() -> DispatchQueue
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueueAttributes.initiallyInactive")
public func dispatch_queue_attr_make_initially_inactive(_ attr: dispatch_queue_attr_t?) -> dispatch_queue_attr_t
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueueAttributes.autoreleaseWorkItem")
public func dispatch_queue_attr_make_with_autorelease_frequency(_ attr: dispatch_queue_attr_t?, _ frequency: dispatch_autorelease_frequency_t) -> dispatch_queue_attr_t
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueueAttributes.qosUserInitiated")
public func dispatch_queue_attr_make_with_qos_class(_ attr: dispatch_queue_attr_t?, _ qos_class: dispatch_qos_class_t, _ relative_priority: Int32) -> dispatch_queue_attr_t
{
fatalError()
}
@available(*, unavailable, renamed:"getter:DispatchQueue.label(self:)")
public func dispatch_queue_get_label(_ queue: DispatchQueue?) -> UnsafePointer<Int8>
{
fatalError()
}
@available(*, unavailable, renamed:"getter:DispatchQueue.qos(self:)")
public func dispatch_queue_get_qos_class(_ queue: DispatchQueue, _ relative_priority_ptr: UnsafeMutablePointer<Int32>?) -> dispatch_qos_class_t
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.after(self:when:execute:)")
public func dispatch_after(_ when: dispatch_time_t, _ queue: DispatchQueue, _ block: @escaping () -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.asynchronously(self:group:qos:flags:execute:)")
public func dispatch_barrier_async(_ queue: DispatchQueue, _ block: @escaping () -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.synchronously(self:flags:execute:)")
public func dispatch_barrier_sync(_ queue: DispatchQueue, _ block: () -> Void)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.setSpecific(self:key:value:)")
public func dispatch_queue_set_specific(_ queue: DispatchQueue, _ key: UnsafeRawPointer, _ context: UnsafeMutableRawPointer?, _ destructor: (@convention(c) (UnsafeMutableRawPointer?) -> Void)?)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.getSpecific(self:key:)")
public func dispatch_queue_get_specific(_ queue: DispatchQueue, _ key: UnsafeRawPointer) -> UnsafeMutableRawPointer?
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchQueue.getSpecific(key:)")
public func dispatch_get_specific(_ key: UnsafeRawPointer) -> UnsafeMutableRawPointer?
{
fatalError()
}
@available(*, unavailable, renamed:"dispatchPrecondition(_:)")
public func dispatch_assert_queue(_ queue: DispatchQueue)
{
fatalError()
}
@available(*, unavailable, renamed:"dispatchPrecondition(_:)")
public func dispatch_assert_queue_barrier(_ queue: DispatchQueue)
{
fatalError()
}
@available(*, unavailable, renamed:"dispatchPrecondition(_:)")
public func dispatch_assert_queue_not(_ queue: DispatchQueue)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchSemaphore.wait(self:timeout:)")
public func dispatch_semaphore_wait(_ dsema: DispatchSemaphore, _ timeout: dispatch_time_t) -> Int
{
fatalError()
}
@available(*, unavailable, renamed: "DispatchSemaphore.signal(self:)")
public func dispatch_semaphore_signal(_ dsema: DispatchSemaphore) -> Int
{
fatalError()
}
@available(*, unavailable, message:"Use DispatchSource class methods")
public func dispatch_source_create(_ type: dispatch_source_type_t, _ handle: UInt, _ mask: UInt, _ queue: DispatchQueue?) -> DispatchSource
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchSource.setEventHandler(self:handler:)")
public func dispatch_source_set_event_handler(_ source: DispatchSource, _ handler: (() -> Void)?)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchSource.setCancelHandler(self:handler:)")
public func dispatch_source_set_cancel_handler(_ source: DispatchSource, _ handler: (() -> Void)?)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchSource.cancel(self:)")
public func dispatch_source_cancel(_ source: DispatchSource)
{
fatalError()
}
@available(*, unavailable, renamed:"getter:DispatchSource.isCancelled(self:)")
public func dispatch_source_testcancel(_ source: DispatchSource) -> Int
{
fatalError()
}
@available(*, unavailable, renamed:"getter:DispatchSource.handle(self:)")
public func dispatch_source_get_handle(_ source: DispatchSource) -> UInt
{
fatalError()
}
@available(*, unavailable, renamed:"getter:DispatchSource.mask(self:)")
public func dispatch_source_get_mask(_ source: DispatchSource) -> UInt
{
fatalError()
}
@available(*, unavailable, renamed:"getter:DispatchSource.data(self:)")
public func dispatch_source_get_data(_ source: DispatchSource) -> UInt
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchUserDataAdd.mergeData(self:value:)")
public func dispatch_source_merge_data(_ source: DispatchSource, _ value: UInt)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchTimerSource.setTimer(self:start:interval:leeway:)")
public func dispatch_source_set_timer(_ source: DispatchSource, _ start: dispatch_time_t, _ interval: UInt64, _ leeway: UInt64)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchSource.setRegistrationHandler(self:handler:)")
public func dispatch_source_set_registration_handler(_ source: DispatchSource, _ handler: (() -> Void)?)
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchTime.now()")
public func dispatch_time(_ when: dispatch_time_t, _ delta: Int64) -> dispatch_time_t
{
fatalError()
}
@available(*, unavailable, renamed:"DispatchWalltime.init(time:)")
public func dispatch_walltime(_ when: UnsafePointer<timespec>?, _ delta: Int64) -> dispatch_time_t
{
fatalError()
}
@available(*, unavailable, renamed: "DispatchQueue.GlobalAttributes.qosUserInitiated")
public var DISPATCH_QUEUE_PRIORITY_HIGH: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchQueue.GlobalAttributes.qosDefault")
public var DISPATCH_QUEUE_PRIORITY_DEFAULT: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchQueue.GlobalAttributes.qosUtility")
public var DISPATCH_QUEUE_PRIORITY_LOW: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchQueue.GlobalAttributes.qosBackground")
public var DISPATCH_QUEUE_PRIORITY_BACKGROUND: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchIO.StreamType.stream")
public var DISPATCH_IO_STREAM: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchIO.StreamType.random")
public var DISPATCH_IO_RANDOM: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchIO.CloseFlags.stop")
public var DISPATCH_IO_STOP: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchIO.IntervalFlags.strictInterval")
public var DISPATCH_IO_STRICT_INTERVAL: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.MachSendEvent.dead")
public var DISPATCH_MACH_SEND_DEAD: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.MemoryPressureEvent.normal")
public var DISPATCH_MEMORYPRESSURE_NORMAL: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.MemoryPressureEvent.warning")
public var DISPATCH_MEMORYPRESSURE_WARN: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.MemoryPressureEvent.critical")
public var DISPATCH_MEMORYPRESSURE_CRITICAL: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.ProcessEvent.exit")
public var DISPATCH_PROC_EXIT: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.ProcessEvent.fork")
public var DISPATCH_PROC_FORK: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.ProcessEvent.exec")
public var DISPATCH_PROC_EXEC: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.ProcessEvent.signal")
public var DISPATCH_PROC_SIGNAL: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.TimerFlags.strict")
public var DISPATCH_TIMER_STRICT: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.delete")
public var DISPATCH_VNODE_DELETE: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.write")
public var DISPATCH_VNODE_WRITE: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.extend")
public var DISPATCH_VNODE_EXTEND: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.attrib")
public var DISPATCH_VNODE_ATTRIB: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.link")
public var DISPATCH_VNODE_LINK: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.rename")
public var DISPATCH_VNODE_RENAME: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.revoke")
public var DISPATCH_VNODE_REVOKE: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.funlock")
public var DISPATCH_VNODE_FUNLOCK: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchTime.now()")
public var DISPATCH_TIME_NOW: Int {
fatalError()
}
@available(*, unavailable, renamed: "DispatchTime.distantFuture")
public var DISPATCH_TIME_FOREVER: Int {
fatalError()
}
| apache-2.0 | 4cc174c85cfb00810649a5159112cf71 | 31.664557 | 199 | 0.736033 | 3.910836 | false | false | false | false |
TotalDigital/People-iOS | Pods/p2.OAuth2/Sources/Base/OAuth2AuthRequest.swift | 2 | 9057 | //
// OAuth2AuthRequest.swift
// OAuth2
//
// Created by Pascal Pfiffner on 18/03/16.
// Copyright © 2016 Pascal Pfiffner. 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 Foundation
/**
HTTP methods for auth requests.
*/
public enum OAuth2HTTPMethod: String {
/// "GET" is the HTTP method of choice.
case GET = "GET"
/// This is a "POST" method.
case POST = "POST"
}
/**
Content types that will be specified in the request header under "Content-type".
*/
public enum OAuth2HTTPContentType: String {
/// JSON content: `application/json`
case json = "application/json"
/// Form encoded content, using UTF-8: `application/x-www-form-urlencoded; charset=utf-8`
case wwwForm = "application/x-www-form-urlencoded; charset=utf-8"
}
/**
The auth method supported by the endpoint.
*/
public enum OAuth2EndpointAuthMethod: String {
/// No auth method is to be used. Good luck with that.
case none = "none"
/// The `client_secret_post` method should be used.
case clientSecretPost = "client_secret_post"
/// The `client_secret_basic` method should be used.
case clientSecretBasic = "client_secret_basic"
}
/**
Class representing an OAuth2 authorization request that can be used to create NSURLRequest instances.
*/
open class OAuth2AuthRequest {
/// The url of the receiver. Queries may by added by parameters specified on `params`.
open let url: URL
/// The HTTP method.
open let method: OAuth2HTTPMethod
/// The content type that will be specified. Defaults to `wwwForm`.
open var contentType = OAuth2HTTPContentType.wwwForm
/// Custom headers can be set here, they will take precedence over any built-in headers.
open private(set) var headers: [String: String]?
/// Query parameters to use with the request.
open var params = OAuth2RequestParams()
/**
Designated initializer. Neither URL nor method can later be changed.
*/
public init(url: URL, method: OAuth2HTTPMethod = .POST) {
self.url = url
self.method = method
}
// MARK: - Headers
/**
Set the given custom header.
- parameter header: The header's name
- parameter value: The value to use
*/
public func set(header: String, to value: String) {
if nil == headers {
headers = [header: value]
}
else {
headers![header] = value
}
}
/**
Unset the given header so that the default can be applied again.
- parameter header: The header's name
*/
public func unset(header: String) {
_ = headers?.removeValue(forKey: header)
}
// MARK: - Parameter
/**
Add the given parameter to the receiver's parameter list, overwriting existing parameters. This method can take nil for convenience.
- parameter params: The parameters to add to the receiver
*/
open func add(params inParams: OAuth2StringDict?) {
if let prms = inParams {
for (key, val) in prms {
params[key] = val
}
}
}
// MARK: - Request Creation
/**
Returns URL components created from the receiver. Only if its method is GET will it add the parameters as percent encoded query.
- returns: NSURLComponents representing the receiver
*/
func asURLComponents() throws -> URLComponents {
let comp = URLComponents(url: url, resolvingAgainstBaseURL: false)
guard var components = comp, "https" == components.scheme else {
throw OAuth2Error.notUsingTLS
}
if .GET == method && params.count > 0 {
components.percentEncodedQuery = params.percentEncodedQueryString()
}
return components
}
/**
Creates an NSURL from the receiver's components; calls `asURLComponents()`, so its caveats apply.
- returns: An NSURL representing the receiver
*/
open func asURL() throws -> URL {
let comp = try asURLComponents()
if let finalURL = comp.url {
return finalURL
}
throw OAuth2Error.invalidURLComponents(comp)
}
/**
Creates a mutable URL request from the receiver, taking into account settings from the provided OAuth2 instance.
- parameter oauth2: The OAuth2 instance from which to take client and auth settings
- returns: A mutable NSURLRequest
*/
open func asURLRequest(for oauth2: OAuth2Base) throws -> URLRequest {
var finalParams = params
// base request
let finalURL = try asURL()
var req = URLRequest(url: finalURL)
req.httpMethod = method.rawValue
req.setValue(contentType.rawValue, forHTTPHeaderField: "Content-Type")
req.setValue("application/json", forHTTPHeaderField: "Accept")
// handle client secret if there is one
if let clientId = oauth2.clientConfig.clientId, !clientId.isEmpty, let secret = oauth2.clientConfig.clientSecret {
// add to request body
if oauth2.clientConfig.secretInBody {
oauth2.logger?.debug("OAuth2", msg: "Adding “client_id” and “client_secret” to request body")
finalParams["client_id"] = clientId
finalParams["client_secret"] = secret
}
// add Authorization header (if not in body)
else {
oauth2.logger?.debug("OAuth2", msg: "Adding “Authorization” header as “Basic client-key:client-secret”")
let pw = "\(clientId.wwwFormURLEncodedString):\(secret.wwwFormURLEncodedString)"
if let utf8 = pw.data(using: oauth2.clientConfig.authStringEncoding) {
req.setValue("Basic \(utf8.base64EncodedString())", forHTTPHeaderField: "Authorization")
}
else {
throw OAuth2Error.utf8EncodeError
}
finalParams.removeValue(forKey: "client_id")
finalParams.removeValue(forKey: "client_secret")
}
}
// add custom headers, first from our OAuth2 instance, then our custom ones
if let headers = oauth2.authHeaders {
for (key, val) in headers {
oauth2.logger?.trace("OAuth2", msg: "Overriding “\(key)” header")
req.setValue(val, forHTTPHeaderField: key)
}
}
if let headers = headers {
for (key, val) in headers {
oauth2.logger?.trace("OAuth2", msg: "Adding custom “\(key)” header")
req.setValue(val, forHTTPHeaderField: key)
}
}
if let customParameters = oauth2.clientConfig.customParameters {
for (k, v) in customParameters {
finalParams[k] = v
}
}
// add a body to POST requests
if .POST == method && finalParams.count > 0 {
req.httpBody = try finalParams.utf8EncodedData()
}
return req
}
}
/**
Struct to hold on to request parameters.
Provides utility functions so the parameters can be correctly encoded for use in URLs and request bodies.
*/
public struct OAuth2RequestParams {
/// The parameters to be used.
public private(set) var params: OAuth2StringDict? = nil
/** Designated initalizer. */
public init() { }
public subscript(key: String) -> String? {
get {
return params?[key]
}
set(newValue) {
params = params ?? OAuth2StringDict()
params![key] = newValue
}
}
/**
Removes the given value from the receiver, if it is defined.
- parameter forKey: The key for the value to be removed
- returns: The value that was removed, if any
*/
@discardableResult
public mutating func removeValue(forKey key: String) -> String? {
return params?.removeValue(forKey: key)
}
/// The number of items in the receiver.
public var count: Int {
return params?.count ?? 0
}
// MARK: - Conversion
/**
Creates a form encoded query string, then encodes it using UTF-8 to NSData.
- returns: NSData representing the receiver form-encoded
*/
public func utf8EncodedData() throws -> Data? {
guard nil != params else {
return nil
}
let body = percentEncodedQueryString()
if let encoded = body.data(using: String.Encoding.utf8, allowLossyConversion: true) {
return encoded
}
else {
throw OAuth2Error.utf8EncodeError
}
}
/**
Creates a parameter string in the form of `key1=value1&key2=value2`, using form URL encoding.
- returns: A form encoded string
*/
public func percentEncodedQueryString() -> String {
guard let params = params else {
return ""
}
return type(of: self).formEncodedQueryStringFor(params)
}
/**
Create a query string from a dictionary of string: string pairs.
This method does **form encode** the value part. If you're using NSURLComponents you want to assign the return value to
`percentEncodedQuery`, NOT `query` as this would double-encode the value.
- parameter params: The parameters you want to have encoded
- returns: An URL-ready query string
*/
public static func formEncodedQueryStringFor(_ params: OAuth2StringDict) -> String {
var arr: [String] = []
for (key, val) in params {
arr.append("\(key)=\(val.wwwFormURLEncodedString)")
}
return arr.joined(separator: "&")
}
}
| apache-2.0 | 75bcf5049bb2250b1169ede9317ac5f8 | 26.620795 | 133 | 0.703942 | 3.704676 | false | false | false | false |
onmyway133/Scale | Sources/Energy.swift | 1 | 2106 | //
// Energy.swift
// Scale
//
// Created by Khoa Pham
// Copyright © 2016 Fantageek. All rights reserved.
//
import Foundation
public enum EnergyUnit: Double {
case joule = 1
case kilojoule = 1_000
case gramcalorie = 4.184
case kilocalorie = 4_184
case watthour = 3_600
static var defaultScale: Double {
return EnergyUnit.joule.rawValue
}
}
public struct Energy {
public let value: Double
public let unit: EnergyUnit
public init(value: Double, unit: EnergyUnit) {
self.value = value
self.unit = unit
}
public func to(unit: EnergyUnit) -> Energy {
return Energy(value: self.value * self.unit.rawValue * EnergyUnit.joule.rawValue / unit.rawValue, unit: unit)
}
}
public extension Double {
public var joule: Energy {
return Energy(value: self, unit: .joule)
}
public var kilojoule: Energy {
return Energy(value: self, unit: .kilojoule)
}
public var gramcalorie: Energy {
return Energy(value: self, unit: .gramcalorie)
}
public var kilocalorie: Energy {
return Energy(value: self, unit: .kilocalorie)
}
public var watthour: Energy {
return Energy(value: self, unit: .watthour)
}
}
public func compute(_ left: Energy, right: Energy, operation: (Double, Double) -> Double) -> Energy {
let (min, max) = left.unit.rawValue < right.unit.rawValue ? (left, right) : (right, left)
let result = operation(min.value, max.to(unit: min.unit).value)
return Energy(value: result, unit: min.unit)
}
public func +(left: Energy, right: Energy) -> Energy {
return compute(left, right: right, operation: +)
}
public func -(left: Energy, right: Energy) -> Energy {
return compute(left, right: right, operation: -)
}
public func *(left: Energy, right: Energy) -> Energy {
return compute(left, right: right, operation: *)
}
public func /(left: Energy, right: Energy) throws -> Energy {
guard right.value != 0 else {
throw ScaleError.dividedByZero
}
return compute(left, right: right, operation: /)
}
| mit | 6d9eb49d7a4734113a353535ca07b8f0 | 24.059524 | 117 | 0.644656 | 3.641869 | false | false | false | false |
apple/swift-corelibs-foundation | Sources/FoundationNetworking/URLSession/Message.swift | 1 | 4598 | // Foundation/URLSession/Message.swift - Message parsing for native protocols
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
///
/// These are libcurl helpers for the URLSession API code.
/// - SeeAlso: https://curl.haxx.se/libcurl/c/
/// - SeeAlso: URLSession.swift
///
// -----------------------------------------------------------------------------
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import SwiftFoundation
#else
import Foundation
#endif
extension _NativeProtocol {
/// A native protocol like FTP or HTTP header being parsed.
///
/// It can either be complete (i.e. the final CR LF CR LF has been
/// received), or partial.
internal enum _ParsedResponseHeader {
case partial(_ResponseHeaderLines)
case complete(_ResponseHeaderLines)
init() {
self = .partial(_ResponseHeaderLines())
}
}
/// A type safe wrapper around multiple lines of headers.
///
/// This can be converted into an `HTTPURLResponse`.
internal struct _ResponseHeaderLines {
let lines: [String]
init() {
self.lines = []
}
init(headerLines: [String]) {
self.lines = headerLines
}
}
}
extension _NativeProtocol._ParsedResponseHeader {
/// Parse a header line passed by libcurl.
///
/// These contain the <CRLF> ending and the final line contains nothing but
/// that ending.
/// - Returns: Returning nil indicates failure. Otherwise returns a new
/// `ParsedResponseHeader` with the given line added.
func byAppending(headerLine data: Data, onHeaderCompleted: (String) -> Bool) -> _NativeProtocol._ParsedResponseHeader? {
// The buffer must end in CRLF
guard 2 <= data.count &&
data[data.endIndex - 2] == _Delimiters.CR &&
data[data.endIndex - 1] == _Delimiters.LF
else { return nil }
let lineBuffer = data.subdata(in: data.startIndex..<data.endIndex-2)
guard let line = String(data: lineBuffer, encoding: .utf8) else { return nil}
return _byAppending(headerLine: line, onHeaderCompleted: onHeaderCompleted)
}
/// Append a status line.
///
/// If the line is empty, it marks the end of the header, and the result
/// is a complete header. Otherwise it's a partial header.
/// - Note: Appending a line to a complete header results in a partial
/// header with just that line.
private func _byAppending(headerLine line: String, onHeaderCompleted: (String) -> Bool) -> _NativeProtocol._ParsedResponseHeader {
if onHeaderCompleted(line) {
switch self {
case .partial(let header): return .complete(header)
case .complete: return .partial(_NativeProtocol._ResponseHeaderLines())
}
} else {
let header = partialResponseHeader
return .partial(header.byAppending(headerLine: line))
}
}
private var partialResponseHeader: _NativeProtocol._ResponseHeaderLines {
switch self {
case .partial(let header): return header
case .complete: return _NativeProtocol._ResponseHeaderLines()
}
}
}
private extension _NativeProtocol._ResponseHeaderLines {
/// Returns a copy of the lines with the new line appended to it.
func byAppending(headerLine line: String) -> _NativeProtocol._ResponseHeaderLines {
var l = self.lines
l.append(line)
return _NativeProtocol._ResponseHeaderLines(headerLines: l)
}
}
// Characters that we need for Header parsing:
struct _Delimiters {
/// *Carriage Return* symbol
static let CR: UInt8 = 0x0d
/// *Line Feed* symbol
static let LF: UInt8 = 0x0a
/// *Space* symbol
static let Space = UnicodeScalar(0x20)
static let HorizontalTab = UnicodeScalar(0x09)
static let Colon = UnicodeScalar(0x3a)
static let Backslash = UnicodeScalar(0x5c)!
static let Comma = UnicodeScalar(0x2c)!
static let DoubleQuote = UnicodeScalar(0x22)!
static let Equals = UnicodeScalar(0x3d)!
/// *Separators* according to RFC 2616
static let Separators = NSCharacterSet(charactersIn: "()<>@,;:\\\"/[]?={} \t")
}
| apache-2.0 | 12646c9951b44d491cbbd41c39285ce9 | 37.316667 | 134 | 0.630492 | 4.588822 | false | false | false | false |
apple/swift-driver | Tests/SwiftDriverTests/Helpers/AssertDiagnostics.swift | 1 | 8247 | //===-------- AssertDiagnostics.swift - Diagnostic Test Assertions --------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import XCTest
import SwiftDriver
import TSCBasic
import TestUtilities
@discardableResult
func assertDriverDiagnostics<Result> (
args: [String],
env: [String: String] = ProcessEnv.vars,
file: StaticString = #file, line: UInt = #line,
do body: (inout Driver, DiagnosticVerifier) throws -> Result
) throws -> Result {
let matcher = DiagnosticVerifier()
defer { matcher.verify(file: file, line: line) }
var driver = try Driver(args: args, env: env, diagnosticsEngine: DiagnosticsEngine(handlers: [matcher.emit(_:)]))
return try body(&driver, matcher)
}
/// Asserts that the `Driver` it instantiates will only emit warnings and errors
/// marked as expected by calls to `DiagnosticVerifier.expect(_:)`,
/// and will emit all diagnostics so marked by the end of the block.
func assertDriverDiagnostics(
args: String...,
env: [String: String] = ProcessEnv.vars,
file: StaticString = #file, line: UInt = #line,
do body: (inout Driver, DiagnosticVerifier) throws -> Void
) throws {
// Ensure there are no color codes in order to make matching work
let argsInBlackAndWhite = [args[0], "-no-color-diagnostics"] + args.dropFirst()
try assertDriverDiagnostics(
args: argsInBlackAndWhite, env: env, file: file, line: line, do: body
)
}
/// Asserts that the `Driver` it instantiates will not emit any warnings or errors.
func assertNoDriverDiagnostics(
args: String...,
env: [String: String] = ProcessEnv.vars,
file: StaticString = #file, line: UInt = #line,
do body: (inout Driver) throws -> Void = { _ in }
) throws {
try assertDriverDiagnostics(args: args, env: env, file: file, line: line) {
driver, _ in try body(&driver)
}
}
/// Asserts that the `DiagnosticsEngine` it instantiates will only emit warnings
/// and errors marked as expected by calls to `DiagnosticVerifier.expect(_:)`,
/// and will emit all diagnostics so marked by the end of the block.
func assertDiagnostics(
file: StaticString = #file, line: UInt = #line,
do body: (DiagnosticsEngine, DiagnosticVerifier) throws -> Void
) rethrows {
let matcher = DiagnosticVerifier()
defer { matcher.verify(file: file, line: line) }
let diags = DiagnosticsEngine(handlers: [matcher.emit(_:)])
try body(diags, matcher)
}
/// Asserts that the `DiagnosticsEngine` it instantiates will not emit any warnings
/// or errors.
func assertNoDiagnostics(
file: StaticString = #file, line: UInt = #line,
do body: (DiagnosticsEngine) throws -> Void
) rethrows {
try assertDiagnostics(file: file, line: line) { diags, _ in try body(diags) }
}
/// Checks that the diagnostics actually emitted by a `DiagnosticsEngine`
/// or `Driver` match the ones expected to be emitted.
///
/// A `DiagnosticVerifier` receives both actual diagnostics and expected diagnostic
/// messages and compares them against each other. If the behavior of the diagnostic and
/// message are the same, and the message's text is a substring of the diagnostic's text,
/// the diagnostics are considered to match. At the end of the assertion that created the
/// verifier, the verifier evaluates all unmatched diagnostics and expectations to
/// determine if any XCTest assertions failed.
///
/// Expected diagnostics are added to the verifier by calling
/// `DiagnosticVerifier.expect(_:repetitions:)`. Any unmet
/// expectation is always a failure. Expectations can be registered before
/// or after the matching diagnostic is emitted, but
///
/// Actual diagnostics are added via a private method. By default, only
/// unexpected warnings and errors—not notes or remarks—cause a
/// failure. You can manipulate this rule by calling
/// `DiagnosticVerifier.permitUnexpected(_:)` or
/// `DiagnosticVerifier.forbidUnexpected(_:)`.
final class DiagnosticVerifier {
fileprivate struct Expectation {
let message: Diagnostic.Message
let file: StaticString
let line: UInt
}
// When we're finished, we will nil the dispatch queue so that any diagnostics
// emitted after verification will cause a crash.
fileprivate var queue: DispatchQueue? =
DispatchQueue(label: "DiagnosticVerifier")
// Access to `actual` and `expected` must be synchronized on `queue`. (Even
// reads should be, although we only enforce writes.)
fileprivate var actual: [Diagnostic] = [] {
didSet {
if #available(macOS 10.12, *) {
dispatchPrecondition(condition: .onQueue(queue!))
}
}
}
fileprivate var expected: [Expectation] = [] {
didSet {
if #available(macOS 10.12, *) {
dispatchPrecondition(condition: .onQueue(queue!))
}
}
}
// Access to `permitted` is not synchronized because it is only used from the
// test.
fileprivate var permitted: Set<Diagnostic.Behavior> = [.note, .remark, .ignored]
/// Callback for the diagnostic engine or driver to use.
func emit(_ diag: Diagnostic) {
guard let queue = queue else {
fatalError("Diagnostic emitted after the test was complete! \(diag)")
}
queue.async {
for (i, expectation) in self.expected.zippedIndices {
if diag.matches(expectation.message) {
self.expected.remove(at: i)
return
}
}
self.actual.append(diag)
}
}
/// Adds an expectation that, by the end of the assertion that created this
/// verifier, the indicated diagnostic will have been emitted. If no diagnostic
/// with the same behavior and a message containing this message's text
/// is emitted by then, a test assertion will fail.
func expect(
_ message: Diagnostic.Message,
repetitions: Int = 1,
file: StaticString = #file, line: UInt = #line
) {
queue!.async {
var remaining = repetitions
for (i, diag) in self.actual.zippedIndices where diag.matches(message) {
self.actual.remove(at: i)
remaining -= 1
if remaining < 1 { return }
}
let expectation = Expectation(message: message, file: file, line: line)
self.expected.append(contentsOf: repeatElement(expectation, count: remaining))
}
}
/// Tells the verifier to permit unexpected diagnostics with
/// the indicated behaviors without causing a test failure.
func permitUnexpected(_ behaviors: Diagnostic.Behavior...) {
permitted.formUnion(behaviors)
}
/// Tells the verifier to forbid unexpected diagnostics with
/// the indicated behaviors; any such diagnostics will cause
/// a test failure.
func forbidUnexpected(_ behaviors: Diagnostic.Behavior...) {
permitted.subtract(behaviors)
}
/// Performs the final verification that the actual diagnostics
/// matched the expectations.
func verify(file: StaticString, line: UInt) {
// All along, we have removed expectations and diagnostics as they've been
// matched, so if there's anything left, it didn't get matched.
var failures: [(String, StaticString, UInt)] = []
queue!.sync {
for diag in self.actual where !self.permitted.contains(diag.behavior) {
failures.append((
"Driver emitted unexpected diagnostic \(diag.behavior): \(diag)",
file, line
))
}
for expectation in self.expected {
failures.append((
"Driver did not emit expected diagnostic: \(expectation.message)",
expectation.file, expectation.line
))
}
self.queue = nil
}
for failure in failures {
XCTFail(failure.0, file: failure.1, line: failure.2)
}
}
}
extension Diagnostic {
func matches(_ expectation: Diagnostic.Message) -> Bool {
behavior == expectation.behavior && message.text.contains(expectation.text)
}
}
fileprivate extension Collection {
var zippedIndices: Zip2Sequence<Indices, Self> {
zip(indices, self)
}
}
| apache-2.0 | b2a07f4e3a8fad2f1d3eadac6488cf1e | 34.683983 | 115 | 0.688948 | 4.417471 | false | false | false | false |
iitjee/SteppinsSwift | 05 Classes.swift | 1 | 8357 | /*
Classes are "class types"(aka "reference types") whereas struct and enums are "value types"
Value types (structures and enumerations) do not support inheritance,
Terminology:
field/member = Stored Property (in Apple) -> can be provided by classes, structures, and enumerations.
property(get/set) = Computed Property (in Apple) -> provided only by classes and structures
= Type Property (in Apple) ->
-> Stored properties store const and var values as part of an instance, whereas computed properties calculate (rather than store) a value.
-> Stored and computed properties are usually associated with instances of a particular type.
However, properties can also be associated with the type itself. Such properties are known as TYPE PROPERTIES.
-> In addition, you can define PROPERTY OBSERVERS to monitor changes in a property’s value, which you can respond to with custom actions.
Property observers can be added to stored properties you define yourself, and also to properties that a subclass inherits from its superclass.
*/
/* Class Initialization */
class VideoMode {
var resolution = Resolution()
var interlaced = false //default value of false
var frameRate = 0.0 //default value of 0.0
var name: String? //default value of nil
var company: String //default value given in initializer ("Canon")
let constProperty: Int //no value initialized in definition, so user must ensure to provide a value to it when instantiating
var firstProperty = "first", secondProperty = "hello"
/* Initialization */
init() {
company = "Canon"
}
init(comp: String) {
company = comp
}
/* Deinitalization */
deinit {
}
/* Normal Function */
func normalFunction() {
}
/* Final Function */
final func printName(name: String) { //final => Subclass can't override it
print("Video company name is \(name)")
}
/* Static Variables */
static var numberOfVideos = 0; //same variable reference for all the class objects. (changing this in one object will reflect in all other objects as well.)
/* Static Functions */
/*Lazy Variable */
lazy var companyInfo = Company() //Here company is some class. The Company instance for the companyInfo property is only created when the companyInfo property is first accessed.
}
/* Instantiation: Classes and Structs MUST set all of their stored properties to an appropriate initial value by the time an instance of that class or Struct is created. */
let someVideoMode = VideoMode()
//interlaced, frameRate, name has default values whereas company is given value with "initializer"
/* Classes are reference types */
let tenEighty = VideoMode()
tenEighty.resolution = hd
tenEighty.interlaced = true
tenEighty.name = "1080i"
tenEighty.frameRate = 25.0
//This example declares a new constant called tenEighty and sets it to refer to a new instance of the VideoMode class.
let alsoTenEighty = tenEighty
alsoTenEighty.frameRate = 30.0
//Because classes are reference types, tenEighty and alsoTenEighty actually both refer to the same VideoMode instance. so tenEightly.frameRate is also 30.0 now.
//V.IMP NOTE: Note that tenEighty and alsoTenEighty are declared as constants, rather than variables.
//However, you can still change tenEighty.frameRate and alsoTenEighty.frameRate because the values of the tenEighty
// and alsoTenEighty constants themselves do not actually change.
// tenEighty and alsoTenEighty themselves do not “store” the VideoMode instance—instead, they both refer to a VideoMode instance behind the scenes.
// It is the frameRate property of the underlying VideoMode that is changed, not the values of the constant references to that VideoMode.
//(However, this is not true in structs for they being value types. When an instance of a value type is marked as a constant, so are all of its properties.)
/* Identity Operators(=== and !==) */
//Because classes are reference types, it is possible for multiple constants and variables to refer to the same single instance of a class behind the scenes. (The same is not true for structures and enumerations, because they are always copied when they are assigned to a constant or variable, or passed to a function.)
if tenEighty === alsoTenEighty {
print("tenEighty and alsoTenEighty refer to the same VideoMode instance.")
}
//Note that “identical to” (represented by three equals signs, or ===) does not mean the same thing as “equal to” (represented by two equals signs, or ==):
//“Identical to” means that two constants or variables of class type refer to exactly the same class instance.
//“Equal to” means that two instances are considered “equal” or “equivalent” in value, for some appropriate meaning of “equal”, as defined by the type’s designer.(one can define one's own implementations of the “equal to” and “not equal to” operators using Equivalence Operators.
/* Swift Collections */
//In Swift, many basic data types such as String, Array, and Dictionary are implemented as structures. This means that data such as strings, arrays, and dictionaries are copied when they are assigned to a new constant or variable, or when they are passed to a function or method.
//This behavior is different from Foundation: NSString, NSArray, and NSDictionary are implemented as classes, not structures. Strings, arrays, and dictionaries in Foundation are always assigned and passed around as a reference to an existing instance, rather than as a copy.
// The behavior you see in your code will always be as if a copy took place. However, Swift only performs an actual copy behind the scenes when it is absolutely necessary to do so. Swift manages all value copying to ensure optimal performance, and you should not avoid assignment to try to preempt this optimization.
/* Stored Properties and iVars */
//ObjC provides two ways to store values and references as part of a class instance.
//In addition to properties, you can use instance variables as a backing store for the values stored in a property.
//Swift unifies these concepts into a single property declaration.
//A Swift property does not have a corresponding instance variable, and the backing store for a property is not accessed directly.
//This approach avoids confusion about how the value is accessed in different contexts and simplifies the property’s declaration into a single, definitive statement.
//All information about the property—including its name, type, and memory management characteristics—is defined in a single location as part of the type’s definition.
/* Lazy Variable */
//A lazy stored property is a property whose initial value is not calculated until the first time it is used.
//You must always declare a lazy property as a variable (with the var keyword), because its initial value might not be retrieved until after instance initialization completes.
//Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy.
//Two Uses:
// -> when the initial value for a property is dependent on outside factors whose values are not known until after an instance’s initialization is complete.
// -> when the initial value for a property requires complex or computationally expensive setup that should not be performed unless or until it is needed.
//If a property marked with the lazy modifier is accessed by multiple threads simultaneously and the property has not yet been initialized, there is no guarantee that the property will be initialized only once.
//IMPORTANT: Global constants and variables are always computed lazily, in a similar manner to Lazy Stored Properties. Unlike lazy stored properties, global constants and variables do not need to be marked with the lazy modifier.
/* Static Methods */
//Static methods cannot be overridden by subclasses. => acting like 'final'
//Static methods are lazy by default.
/* Deinitializtion */
//Unlike in langs like Java or C# where unused variables are cleared at some "random point of time" (Called Garbage Collection) in Swift, you exactly know when the variable is being cleared. (Called Reference Counting)
| apache-2.0 | e1873d01037444ea3ffc12f399a191b7 | 54.711409 | 319 | 0.754487 | 4.801041 | false | false | false | false |
fatalhck/findr | Findr/Classes/FindrConfiguration.swift | 1 | 4064 | import CoreLocation
import UIKit
let LAT_LON_FACTOR: CGFloat = 1.33975031663 // Used in azimuzh calculation, don't change
let VERTICAL_SENS: CGFloat = 960
let H_PIXELS_PER_DEGREE: CGFloat = 15 // How many pixels per degree
let OVERLAY_VIEW_WIDTH: CGFloat = 360 * H_PIXELS_PER_DEGREE // 360 degrees x sensitivity
let MAX_VISIBLE_ANNOTATIONS: Int = 500 // Do not change, can affect performance
let MAX_VERTICAL_LEVELS: Int = 5 // Do not change, can affect performance
internal func radiansToDegrees(_ radians: Double) -> Double
{
return (radians) * (180.0 / M_PI)
}
internal func degreesToRadians(_ degrees: Double) -> Double
{
return (degrees) * (M_PI / 180.0)
}
/// Normalizes degree to 360
internal func normalizeDegree(_ degree: Double) -> Double
{
var degreeNormalized = fmod(degree, 360)
if degreeNormalized < 0
{
degreeNormalized = 360 + degreeNormalized
}
return degreeNormalized
}
/// Finds shortes angle distance between two angles. Angles must be normalized(0-360)
internal func deltaAngle(_ angle1: Double, angle2: Double) -> Double
{
var deltaAngle = angle1 - angle2
if deltaAngle > 180
{
deltaAngle -= 360
}
else if deltaAngle < -180
{
deltaAngle += 360
}
return deltaAngle
}
/// DataSource provides the FindrViewController with the information needed to display annotations.
@objc public protocol ARDataSource : NSObjectProtocol
{
/// Asks the data source to provide annotation view for annotation. Annotation view must be subclass of ARAnnotationView.
func ar(_ findrViewController: FindrViewController, viewForAnnotation: FindrAnnotation) -> FindrAnnotationView
/**
* READ BEFORE IMPLEMENTING
* FindrViewController tracks user movement and shows/hides annotations accordingly. But if there is huge amount
* of annotations or for some other reason annotations cannot be set all at once, this method can be used to
* set annotations part by part.
*
* Use FindrViewController.trackingManager.reloadDistanceFilter to change how often this is called.
*
* - parameter findrViewController: FindrViewController instance
* - parameter location: Current location of the user
* - returns: Annotations to load, previous annotations are removed
*/
@objc optional func ar(_ findrViewController: FindrViewController, shouldReloadWithLocation location: CLLocation) -> [FindrAnnotation]
}
//MARK: FindrViewController Delegate
protocol FindrViewControllerDelegate {
func findrViewController(findrViewController: FindrViewController, failToOpenWithError error: Error)
func findrViewControllerUpdateAngleForAnnotation(findrViewController: FindrViewController,annotation: FindrAnnotation , angle: CGFloat)
func findrViewControllerFixedVerticalPositionForAnnotation(findrViewController: FindrViewController)-> CGFloat?
func findrViewControllerWillShowAnnotationView(findrViewController: FindrViewController, annotationView: FindrAnnotationView)
func findrViewControllerWillReloadAnnotations(findrViewController: FindrViewController, annotations: [FindrAnnotation])
func findrViewControllerUserDidGetLost(findrViewController: FindrViewController) -> Void
func findrViewControllerViewForLeftIndicator(findrViewController: FindrViewController)-> UIView
func findrViewControllerViewForRightIndicator(findrViewController: FindrViewController) -> UIView
func findrViewControllerFrameForRightIndicator(findrViewController: FindrViewController) -> CGRect
func findrViewControllerFrameForLeftIndicator(findrViewController: FindrViewController) -> CGRect
func findrViewControllerUpdateLeftIndicatorView(findrViewController: FindrViewController, view: UIView)
func findrViewControllerUpdateRightIndicatorView(findrViewController: FindrViewController, view: UIView)
}
| mit | 39d52781ec9c577da645058ebb1b6f3d | 44.155556 | 139 | 0.738927 | 5.514247 | false | false | false | false |
huonw/swift | stdlib/public/core/LazyCollection.swift | 1 | 8687 | //===--- LazyCollection.swift ---------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A collection on which normally-eager operations such as `map` and
/// `filter` are implemented lazily.
///
/// Please see `LazySequenceProtocol` for background; `LazyCollectionProtocol`
/// is an analogous component, but for collections.
///
/// To add new lazy collection operations, extend this protocol with
/// methods that return lazy wrappers that are themselves
/// `LazyCollectionProtocol`s.
public protocol LazyCollectionProtocol: Collection, LazySequenceProtocol {
/// A `Collection` that can contain the same elements as this one,
/// possibly with a simpler type.
///
/// - See also: `elements`
associatedtype Elements : Collection = Self
}
extension LazyCollectionProtocol {
// Lazy things are already lazy
@inlinable // FIXME(sil-serialize-all)
public var lazy: LazyCollection<Elements> {
return elements.lazy
}
}
extension LazyCollectionProtocol where Elements: LazyCollectionProtocol {
// Lazy things are already lazy
@inlinable // FIXME(sil-serialize-all)
public var lazy: Elements {
return elements
}
}
/// A collection containing the same elements as a `Base` collection,
/// but on which some operations such as `map` and `filter` are
/// implemented lazily.
///
/// - See also: `LazySequenceProtocol`, `LazyCollection`
@_fixed_layout
public struct LazyCollection<Base : Collection> {
/// Creates an instance with `base` as its underlying Collection
/// instance.
@inlinable
internal init(_base: Base) {
self._base = _base
}
@usableFromInline
internal var _base: Base
}
extension LazyCollection: LazyCollectionProtocol {
/// The type of the underlying collection.
public typealias Elements = Base
/// The underlying collection.
@inlinable
public var elements: Elements { return _base }
}
/// Forward implementations to the base collection, to pick up any
/// optimizations it might implement.
extension LazyCollection : Sequence {
public typealias Iterator = Base.Iterator
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
@inlinable
public func makeIterator() -> Iterator {
return _base.makeIterator()
}
/// A value less than or equal to the number of elements in the sequence,
/// calculated nondestructively.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
@inlinable
public var underestimatedCount: Int { return _base.underestimatedCount }
@inlinable
public func _copyToContiguousArray()
-> ContiguousArray<Base.Iterator.Element> {
return _base._copyToContiguousArray()
}
@inlinable
public func _copyContents(
initializing buf: UnsafeMutableBufferPointer<Iterator.Element>
) -> (Iterator,UnsafeMutableBufferPointer<Iterator.Element>.Index) {
return _base._copyContents(initializing: buf)
}
@inlinable
public func _customContainsEquatableElement(
_ element: Base.Iterator.Element
) -> Bool? {
return _base._customContainsEquatableElement(element)
}
}
extension LazyCollection : Collection {
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Element = Base.Element
public typealias Index = Base.Index
public typealias Indices = Base.Indices
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
@inlinable
public var startIndex: Index { return _base.startIndex }
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// `endIndex` is always reachable from `startIndex` by zero or more
/// applications of `index(after:)`.
@inlinable
public var endIndex: Index { return _base.endIndex }
@inlinable
public var indices: Indices { return _base.indices }
// TODO: swift-3-indexing-model - add docs
@inlinable
public func index(after i: Index) -> Index {
return _base.index(after: i)
}
/// Accesses the element at `position`.
///
/// - Precondition: `position` is a valid position in `self` and
/// `position != endIndex`.
@inlinable
public subscript(position: Index) -> Element {
return _base[position]
}
/// A Boolean value indicating whether the collection is empty.
@inlinable
public var isEmpty: Bool {
return _base.isEmpty
}
/// Returns the number of elements.
///
/// To check whether a collection is empty, use its `isEmpty` property
/// instead of comparing `count` to zero. Unless the collection guarantees
/// random-access performance, calculating `count` can be an O(*n*)
/// operation.
///
/// - Complexity: O(1) if `Self` conforms to `RandomAccessCollection`;
/// O(*n*) otherwise.
@inlinable
public var count: Int {
return _base.count
}
// The following requirement enables dispatching for firstIndex(of:) and
// lastIndex(of:) when the element type is Equatable.
/// Returns `Optional(Optional(index))` if an element was found;
/// `Optional(nil)` if the element doesn't exist in the collection;
/// `nil` if a search was not performed.
///
/// - Complexity: Better than O(*n*)
@inlinable
public func _customIndexOfEquatableElement(
_ element: Element
) -> Index?? {
return _base._customIndexOfEquatableElement(element)
}
/// Returns `Optional(Optional(index))` if an element was found;
/// `Optional(nil)` if the element doesn't exist in the collection;
/// `nil` if a search was not performed.
///
/// - Complexity: Better than O(*n*)
@inlinable
public func _customLastIndexOfEquatableElement(
_ element: Element
) -> Index?? {
return _base._customLastIndexOfEquatableElement(element)
}
/// Returns the first element of `self`, or `nil` if `self` is empty.
@inlinable
public var first: Element? {
return _base.first
}
// TODO: swift-3-indexing-model - add docs
@inlinable
public func index(_ i: Index, offsetBy n: Int) -> Index {
return _base.index(i, offsetBy: n)
}
// TODO: swift-3-indexing-model - add docs
@inlinable
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
return _base.index(i, offsetBy: n, limitedBy: limit)
}
// TODO: swift-3-indexing-model - add docs
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
return _base.distance(from:start, to: end)
}
}
extension LazyCollection : BidirectionalCollection
where Base : BidirectionalCollection {
@inlinable
public func index(before i: Index) -> Index {
return _base.index(before: i)
}
@inlinable
public var last: Element? {
return _base.last
}
}
extension LazyCollection : RandomAccessCollection
where Base : RandomAccessCollection {}
/// Augment `self` with lazy methods such as `map`, `filter`, etc.
extension Collection {
/// A view onto this collection that provides lazy implementations of
/// normally eager operations, such as `map` and `filter`.
///
/// Use the `lazy` property when chaining operations to prevent
/// intermediate operations from allocating storage, or when you only
/// need a part of the final collection to avoid unnecessary computation.
@inlinable
public var lazy: LazyCollection<Self> {
return LazyCollection(_base: self)
}
}
extension Slice: LazySequenceProtocol where Base: LazySequenceProtocol { }
extension Slice: LazyCollectionProtocol where Base: LazyCollectionProtocol { }
extension ReversedCollection: LazySequenceProtocol where Base: LazySequenceProtocol { }
extension ReversedCollection: LazyCollectionProtocol where Base: LazyCollectionProtocol { }
@available(*, deprecated, renamed: "LazyCollection")
public typealias LazyBidirectionalCollection<T> = LazyCollection<T> where T : BidirectionalCollection
@available(*, deprecated, renamed: "LazyCollection")
public typealias LazyRandomAccessCollection<T> = LazyCollection<T> where T : RandomAccessCollection
| apache-2.0 | 89b5dba54379f81a6f42a69f83ae9861 | 31.174074 | 101 | 0.700357 | 4.54341 | false | false | false | false |
ludoded/ReceiptBot | Pods/Material/Sources/iOS/Bar.swift | 2 | 8517 | /*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
@objc(ContentViewAlignment)
public enum ContentViewAlignment: Int {
case full
case center
}
open class Bar: View {
/// Will layout the view.
open var willLayout: Bool {
return 0 < width && 0 < height && nil != superview
}
open override var intrinsicContentSize: CGSize {
return CGSize(width: width, height: height)
}
/// Should center the contentView.
open var contentViewAlignment = ContentViewAlignment.full {
didSet {
layoutSubviews()
}
}
/// A preset wrapper around contentEdgeInsets.
open var contentEdgeInsetsPreset: EdgeInsetsPreset {
get {
return grid.contentEdgeInsetsPreset
}
set(value) {
grid.contentEdgeInsetsPreset = value
}
}
/// A reference to EdgeInsets.
@IBInspectable
open var contentEdgeInsets: EdgeInsets {
get {
return grid.contentEdgeInsets
}
set(value) {
grid.contentEdgeInsets = value
}
}
/// A preset wrapper around interimSpace.
open var interimSpacePreset: InterimSpacePreset {
get {
return grid.interimSpacePreset
}
set(value) {
grid.interimSpacePreset = value
}
}
/// A wrapper around grid.interimSpace.
@IBInspectable
open var interimSpace: InterimSpace {
get {
return grid.interimSpace
}
set(value) {
grid.interimSpace = value
}
}
/// Grid cell factor.
@IBInspectable
open var gridFactor: CGFloat = 12 {
didSet {
assert(0 < gridFactor, "[Material Error: gridFactor must be greater than 0.]")
layoutSubviews()
}
}
/// ContentView that holds the any desired subviews.
open let contentView = UIView()
/// Left side UIViews.
open var leftViews: [UIView] {
didSet {
for v in oldValue {
v.removeFromSuperview()
}
layoutSubviews()
}
}
/// Right side UIViews.
open var rightViews: [UIView] {
didSet {
for v in oldValue {
v.removeFromSuperview()
}
layoutSubviews()
}
}
/// Center UIViews.
open var centerViews: [UIView] {
get {
return contentView.grid.views
}
set(value) {
contentView.grid.views = value
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
leftViews = []
rightViews = []
super.init(coder: aDecoder)
}
/**
An initializer that initializes the object with a CGRect object.
If AutoLayout is used, it is better to initilize the instance
using the init() initializer.
- Parameter frame: A CGRect instance.
*/
public override init(frame: CGRect) {
leftViews = []
rightViews = []
super.init(frame: frame)
}
/// Convenience initializer.
public convenience init() {
self.init(frame: .zero)
}
/**
A convenience initializer with parameter settings.
- Parameter leftViews: An Array of UIViews that go on the left side.
- Parameter rightViews: An Array of UIViews that go on the right side.
- Parameter centerViews: An Array of UIViews that go in the center.
*/
public convenience init(leftViews: [UIView]? = nil, rightViews: [UIView]? = nil, centerViews: [UIView]? = nil) {
self.init()
self.leftViews = leftViews ?? []
self.rightViews = rightViews ?? []
self.centerViews = centerViews ?? []
}
open override func layoutSubviews() {
super.layoutSubviews()
guard willLayout else {
return
}
guard !grid.deferred else {
return
}
reload()
}
/// Reloads the view.
open func reload() {
var lc = 0
var rc = 0
grid.begin()
grid.views.removeAll()
for v in leftViews {
if let b = v as? UIButton {
b.contentEdgeInsets = .zero
b.titleEdgeInsets = .zero
}
v.width = v.intrinsicContentSize.width
v.sizeToFit()
v.grid.columns = Int(ceil(v.width / gridFactor)) + 2
lc += v.grid.columns
grid.views.append(v)
}
grid.views.append(contentView)
for v in rightViews {
if let b = v as? UIButton {
b.contentEdgeInsets = .zero
b.titleEdgeInsets = .zero
}
v.width = v.intrinsicContentSize.width
v.sizeToFit()
v.grid.columns = Int(ceil(v.width / gridFactor)) + 2
rc += v.grid.columns
grid.views.append(v)
}
contentView.grid.begin()
contentView.grid.offset.columns = 0
var l: CGFloat = 0
var r: CGFloat = 0
if .center == contentViewAlignment {
if leftViews.count < rightViews.count {
r = CGFloat(rightViews.count) * interimSpace
l = r
} else {
l = CGFloat(leftViews.count) * interimSpace
r = l
}
}
let p = width - l - r - contentEdgeInsets.left - contentEdgeInsets.right
let columns = Int(ceil(p / gridFactor))
if .center == contentViewAlignment {
if lc < rc {
contentView.grid.columns = columns - 2 * rc
contentView.grid.offset.columns = rc - lc
} else {
contentView.grid.columns = columns - 2 * lc
rightViews.first?.grid.offset.columns = lc - rc
}
} else {
contentView.grid.columns = columns - lc - rc
}
grid.axis.columns = columns
grid.commit()
contentView.grid.commit()
divider.reload()
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open override func prepare() {
super.prepare()
heightPreset = .normal
autoresizingMask = .flexibleWidth
interimSpacePreset = .interimSpace3
contentEdgeInsetsPreset = .square1
}
}
| lgpl-3.0 | 27e3a1ce241ec1d41fd2c825f0c55449 | 28.884211 | 116 | 0.577081 | 5.096948 | false | false | false | false |
3DprintFIT/octoprint-ios-client | OctoPhone/Utils/Formatters/OPTimeFormatter.swift | 1 | 1134 | //
// OPTimeFormatter.swift
// OctoPhone
//
// Created by Josef Dolezal on 02/05/2017.
// Copyright © 2017 Josef Dolezal. All rights reserved.
//
import Foundation
import ReactiveSwift
/// Provides standardized date formats
struct OPTimeFormatter {
/// Creates formatted duration string from seconds. The returned format
/// is always HH:MM:SS.
///
/// - Parameter value: Amount of seconds
/// - Returns: Formatted duration value
static func durationFormSeconds(_ value: Int) -> String {
let hours = value / 3600
let minutes = (value / 60) % 60
let seconds = value % 60
return String(format: "%02i:%02i:%02i", hours, minutes, seconds)
}
}
// MARK: - Formatter reactive extension for time format.
extension SignalProducer where Value == Int {
/// Operator for seconds (number) formatting. Maps given values of `self`
/// to string represantation of duration.
///
/// - Returns: Producer with formatted value of `self`
func formatDuration() -> SignalProducer<String, Error> {
return map { OPTimeFormatter.durationFormSeconds($0) }
}
}
| mit | 1ff2fdb717492f1ad32935afad4b88f5 | 29.621622 | 77 | 0.664607 | 4.340996 | false | false | false | false |
biohazardlover/ROer | Roer/Skill+DatabaseRecord.swift | 1 | 16087 |
import CoreData
import CoreSpotlight
import MobileCoreServices
extension Skill {
var displayType: String? {
guard let inf = inf else { return nil }
switch inf {
case 0:
return "Skill.Type.Passive".localized
default:
return nil
}
}
var displayAttackType: String? {
guard let element = element else { return nil }
switch element {
case -3:
return "Skill.AttackType.UseRandomProperty".localized
case -2:
return "Skill.AttackType.UseEndowedProperty".localized
case -1:
return "Skill.AttackType.UseWeaponProperty".localized
case 1:
return "Skill.AttackType.WaterProperty".localized
case 2:
return "Skill.AttackType.EarthProperty".localized
case 3:
return "Skill.AttackType.FireProperty".localized
case 4:
return "Skill.AttackType.WindProperty".localized
case 5:
return "Skill.AttackType.PoisonProperty".localized
case 6:
return "Skill.AttackType.HolyProperty".localized
case 7:
return "Skill.AttackType.ShadowProperty".localized
case 8:
return "Skill.AttackType.GhostProperty".localized
case 9:
return "Skill.AttackType.UndeadProperty".localized
default:
return nil
}
}
var displayTarget: String? {
guard let inf = inf else { return nil }
switch inf {
case 1:
return "Skill.Target.Enemy".localized
case 2:
return "Skill.Target.Ground".localized
case 4:
return "Skill.Target.Self".localized
case 16:
return "Skill.Target.Player".localized
case 32:
return "Skill.Target.Trap".localized
default:
return nil
}
}
var displayRange: String? {
guard let range = range else { return nil }
if range.intValue < 0 {
return "Skill.Range.Melee".localized
} else if range.intValue > 0 {
return range.stringValue + " " + "Cells".localized
} else {
return nil
}
}
var displayArea: String? {
return nil
}
var displayKnockback: String? {
guard let blow_count = blow_count else { return nil }
if blow_count.intValue > 0 {
return blow_count.stringValue + " " + "Cells".localized
} else {
return nil
}
}
var displayCost: NSAttributedString? {
let attributedString = NSMutableAttributedString()
if let displayHPCost = displayHPCost {
attributedString.appendLineOfName("Skill.HPCost".localized, andValue: displayHPCost)
}
if let displaySPCost = displaySPCost {
attributedString.appendLineOfName("Skill.SPCost".localized, andValue: displaySPCost)
}
if let displayZenyCost = displayZenyCost {
attributedString.appendLineOfName("Skill.ZenyCost".localized, andValue: displayZenyCost)
}
if let displaySpiritSphereCost = displaySpiritSphereCost {
attributedString.appendLineOfName("Skill.SpiritSphereCost".localized, andValue: displaySpiritSphereCost)
}
return attributedString
}
var displayHPCost: String? {
guard let hpCost = requirement?.hpCost, hpCost != "0" else { return nil }
return hpCost.components(separatedBy: ":").joined(separator: " / ")
}
var displaySPCost: String? {
guard let spCost = requirement?.spCost, spCost != "0" else { return nil }
return spCost.components(separatedBy: ":").joined(separator: " / ")
}
var displayZenyCost: String? {
guard let zenyCost = requirement?.zenyCost, zenyCost != "0" else { return nil }
return zenyCost.components(separatedBy: ":").joined(separator: " / ")
}
var displaySpiritSphereCost: String? {
guard let spiritSphereCost = requirement?.spiritSphereCost, spiritSphereCost != "0" else { return nil }
return spiritSphereCost.components(separatedBy: ":").joined(separator: " / ")
}
var displayCast: NSAttributedString? {
let attributedString = NSMutableAttributedString()
if let displayCastTime = displayCastTime {
attributedString.appendLineOfName("Skill.CastTime".localized, andValue: displayCastTime)
}
if let displayStayDuration = displayStayDuration {
attributedString.appendLineOfName("Skill.StayDuration".localized, andValue: displayStayDuration)
}
if let displayEffectDuration = displayEffectDuration {
attributedString.appendLineOfName("Skill.EffectDuration".localized, andValue: displayEffectDuration)
}
if let displayCoolDown = displayCoolDown {
attributedString.appendLineOfName("Skill.CoolDown".localized, andValue: displayCoolDown)
}
return attributedString
}
var displayCastTime: String? {
guard let castingTime = cast?.castingTime, let fixedCastingTime = cast?.fixedCastingTime else { return nil }
if castingTime == "0" && fixedCastingTime == "0" { return nil }
let castingTimes = castingTime.components(separatedBy: ":")
let fixedCastingTimes = fixedCastingTime.components(separatedBy: ":")
let count = castingTimes.count > fixedCastingTimes.count ? castingTimes.count : fixedCastingTimes.count
var times = [String]()
for i in 0..<count {
let castTime = i < castingTimes.count ? castingTimes[i] : castingTimes.first
let fixedCastTime = i < fixedCastingTimes.count ? fixedCastingTimes[i] : fixedCastingTimes.first
guard let castTime1 = castTime, let fixedCastTime1 = fixedCastTime else {
times.append("")
continue
}
if let msec1 = Float(castTime1), let msec2 = Float(fixedCastTime1) {
times.append(NSNumber(value: msec1 / 1000 + msec2 / 1000 as Float).stringValue)
} else {
times.append("")
}
}
return times.joined(separator: " / ") + " " + "Time.Second".localized
}
var displayStayDuration: String? {
guard let duration1 = cast?.duration1, duration1 != "0" else { return nil }
let durations = duration1.components(separatedBy: ":").map { (duration) -> String in
if let msec = Float(duration) {
let sec = msec / 1000
return NSNumber(value: sec as Float).stringValue
} else {
return ""
}
}
return durations.joined(separator: " / ") + " " + "Time.Second".localized
}
var displayEffectDuration: String? {
guard let duration2 = cast?.duration2, duration2 != "0" else { return nil }
let durations = duration2.components(separatedBy: ":").map { (duration) -> String in
if let msec = Float(duration) {
let sec = msec / 1000
return NSNumber(value: sec as Float).stringValue
} else {
return ""
}
}
return durations.joined(separator: " / ") + " " + "Time.Second".localized
}
var displayCoolDown: String? {
guard let coolDown = cast?.coolDown, coolDown != "0" else { return nil }
let durations = coolDown.components(separatedBy: ":").map { (duration) -> String in
if let msec = Float(duration) {
let sec = msec / 1000
return NSNumber(value: sec as Float).stringValue
} else {
return ""
}
}
return durations.joined(separator: " / ") + " " + "Time.Second".localized
}
var displayRequiredWeaponClass: NSAttributedString? {
guard let requiredWeapons = requirement?.requiredWeapons, requiredWeapons != "0" else { return nil }
let weapons = requiredWeapons.components(separatedBy: ":").map { (weapon) -> String in
switch weapon {
case "0":
return "Bare Fist"
case "1":
return "Item.Class.Dagger".localized
case "2":
return "Item.Class.OnehandedSword".localized
case "3":
return "Item.Class.TwohandedSword".localized
case "4":
return "Item.Class.OnehandedSpear".localized
case "5":
return "Item.Class.TwohandedSpear".localized
case "6":
return "Item.Class.OnehandedAxe".localized
case "7":
return "Item.Class.TwohandedAxe".localized
case "8":
return "Item.Class.Mace".localized
case "10":
return "Item.Class.OnehandedStaff".localized
case "11":
return "Item.Class.Bow".localized
case "12":
return "Item.Class.Knuckle".localized
case "13":
return "Item.Class.MusicalInstrument".localized
case "14":
return "Item.Class.Whip".localized
case "15":
return "Item.Class.Book".localized
case "16":
return "Item.Class.Katar".localized
case "17":
return "Item.Class.Revolver".localized
case "18":
return "Item.Class.Rifle".localized
case "19":
return "Item.Class.GatlingGun".localized
case "20":
return "Item.Class.Shotgun".localized
case "21":
return "Item.Class.GrenadeLauncher".localized
case "22":
return "Item.Class.FuumaShuriken".localized
case "23":
return "Item.Class.TwohandedStaff".localized
case "24":
return "Max Type"
case "25":
return "Dual-wield Daggers"
case "26":
return "Dual-wield Swords"
case "27":
return "Dual-wield Axes"
case "28":
return "Dagger + Sword"
case "29":
return "Dagger + Axe"
case "30":
return "Sword + Axe"
default:
return ""
}
}
return NSAttributedString(string: weapons.joined(separator: ", "), attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17)])
}
}
extension Skill {
var requiredItems: [DatabaseRecordCellInfo] {
var requiredItems = [DatabaseRecordCellInfo]()
let items: [(id: NSNumber?, amount: NSNumber?)] = [
(requirement?.requiredItemID1, requirement?.requiredItemAmount1),
(requirement?.requiredItemID2, requirement?.requiredItemAmount2),
(requirement?.requiredItemID3, requirement?.requiredItemAmount3),
(requirement?.requiredItemID4, requirement?.requiredItemAmount4),
(requirement?.requiredItemID5, requirement?.requiredItemAmount5),
(requirement?.requiredItemID6, requirement?.requiredItemAmount6),
(requirement?.requiredItemID7, requirement?.requiredItemAmount7),
(requirement?.requiredItemID8, requirement?.requiredItemAmount8),
(requirement?.requiredItemID9, requirement?.requiredItemAmount9),
(requirement?.requiredItemID10, requirement?.requiredItemAmount10)
]
for item in items {
if let itemID = item.id, itemID != 0, let itemAmount = item.amount {
let fetchRequest = NSFetchRequest<Item>(entityName: "Item")
fetchRequest.predicate = NSPredicate(format: "id == %@", itemID)
if let item = (try? managedObjectContext?.fetch(fetchRequest))??.first {
requiredItems.append((item, "×" + itemAmount.stringValue))
}
}
}
return requiredItems
}
}
extension Skill {
var localizedName: String? {
guard let id = id else { return nil }
let result = Localization.preferred.skillInfo["\(id)"]["SkillName"].string
return result?.isEmpty == false ? result : name
}
var localizedDescription: NSAttributedString? {
guard let id = id else { return nil }
guard let resultArray = Localization.preferred.skillInfo["\(id)"]["SkillDescription"].array else { return nil }
let stringArray = resultArray.map { (json) -> String in
return json.stringValue
}
let result = stringArray.joined(separator: "\n")
return NSAttributedString(descriptiveString: result)
}
}
extension Skill: DatabaseRecord {
var smallImageURL: URL? {
if let name = name {
return URL(string: "http://ratemyserver.net/skill_icons/\(name.lowercased()).gif")
} else {
return nil
}
}
var largeImageURL: URL? {
return nil
}
var displayName: String? {
return localizedName
}
var recordDetails: DatabaseRecordDetails {
var attributeGroups = [DatabaseRecordAttributeGroup]()
attributeGroups.appendAttribute(("Skill.Type".localized, displayType?.utf8))
attributeGroups.appendAttribute(("Skill.MaxLevel".localized, max))
attributeGroups.appendAttribute(("Skill.AttackType".localized, displayAttackType?.utf8))
attributeGroups.appendAttribute(("Skill.Target".localized, displayTarget?.utf8))
attributeGroups.appendAttribute(("Skill.Range".localized, displayRange?.utf8))
attributeGroups.appendAttribute(("Skill.Area".localized, displayArea?.utf8))
attributeGroups.appendAttribute(("Skill.Knockback".localized, displayKnockback?.utf8))
var recordDetails = DatabaseRecordDetails()
recordDetails.appendTitle(displayName != nil && id != nil ? "\(displayName!) #\(id!)" : "", section: .attributeGroups(attributeGroups))
recordDetails.appendTitle("Skill.Cost".localized, section: .description(displayCost))
recordDetails.appendTitle("Skill.Cast".localized, section: .description(displayCast))
recordDetails.appendTitle("Skill.RequiredItems".localized, section: .databaseRecords(requiredItems))
recordDetails.appendTitle("Skill.RequiredWeaponClass".localized, section: .description(displayRequiredWeaponClass))
recordDetails.appendTitle("Skill.Description".localized, section: .description(localizedDescription))
return recordDetails
}
func correspondingDatabaseRecord(in managedObjectContext: NSManagedObjectContext) -> DatabaseRecord? {
guard let id = id else { return nil }
let request = NSFetchRequest<Skill>(entityName: "Skill")
request.predicate = NSPredicate(format: "%K == %@", "id", id)
let results = try? managedObjectContext.fetch(request)
return results?.first
}
}
extension Skill: Searchable {
var searchableItem: CSSearchableItem {
let searchableItemAttributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeData as String)
searchableItemAttributeSet.title = localizedName
searchableItemAttributeSet.contentDescription = nil
searchableItemAttributeSet.thumbnailData = nil
return CSSearchableItem(uniqueIdentifier: "Skill/" + (id?.stringValue ?? ""), domainIdentifier: nil, attributeSet: searchableItemAttributeSet)
}
}
| mit | b8522356d70381c482f97bc211b01d9a | 36.409302 | 150 | 0.587778 | 5.217645 | false | false | false | false |
wikimedia/apps-ios-wikipedia | Wikipedia/Code/ArticleCollectionViewCell.swift | 3 | 14884 | import UIKit
open class ArticleCollectionViewCell: CollectionViewCell, SwipeableCell, BatchEditableCell {
public let titleLabel = UILabel()
public let descriptionLabel = UILabel()
public let imageView = UIImageView()
public var extractLabel: UILabel?
public let actionsView = ActionsView()
public var alertIcon = UIImageView()
public var alertLabel = UILabel()
open var alertType: ReadingListAlertType?
public var statusView = UIImageView() // the circle that appears next to the article name to indicate the article's status
private var _titleHTML: String? = nil
private var _titleBoldedString: String? = nil
private func updateTitleLabel() {
if let titleHTML = _titleHTML {
titleLabel.attributedText = titleHTML.byAttributingHTML(with: titleTextStyle, matching: traitCollection, withBoldedString: _titleBoldedString)
} else {
let titleFont = UIFont.wmf_font(titleTextStyle, compatibleWithTraitCollection: traitCollection)
titleLabel.font = titleFont
}
}
public var titleHTML: String? {
set {
_titleHTML = newValue
updateTitleLabel()
}
get {
return _titleHTML
}
}
public func setTitleHTML(_ titleHTML: String?, boldedString: String?) {
_titleHTML = titleHTML
_titleBoldedString = boldedString
updateTitleLabel()
}
public var actions: [Action] {
set {
actionsView.actions = newValue
updateAccessibilityElements()
}
get {
return actionsView.actions
}
}
open override func setup() {
titleTextStyle = .georgiaTitle3
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
statusView.clipsToBounds = true
imageView.accessibilityIgnoresInvertColors = true
titleLabel.isOpaque = true
descriptionLabel.isOpaque = true
imageView.isOpaque = true
contentView.addSubview(alertIcon)
contentView.addSubview(alertLabel)
contentView.addSubview(statusView)
contentView.addSubview(imageView)
contentView.addSubview(titleLabel)
contentView.addSubview(descriptionLabel)
super.setup()
}
// This method is called to reset the cell to the default configuration. It is called on initial setup and prepareForReuse. Subclassers should call super.
override open func reset() {
super.reset()
_titleHTML = nil
_titleBoldedString = nil
titleTextStyle = .georgiaTitle3
descriptionTextStyle = .subheadline
extractTextStyle = .subheadline
saveButtonTextStyle = .mediumFootnote
spacing = 3
imageViewDimension = 70
statusViewDimension = 6
alertIconDimension = 12
imageView.wmf_reset()
resetSwipeable()
isBatchEditing = false
isBatchEditable = false
actions = []
isAlertLabelHidden = true
isAlertIconHidden = true
isStatusViewHidden = true
updateFonts(with: traitCollection)
}
override open func updateBackgroundColorOfLabels() {
super.updateBackgroundColorOfLabels()
titleLabel.backgroundColor = labelBackgroundColor
descriptionLabel.backgroundColor = labelBackgroundColor
extractLabel?.backgroundColor = labelBackgroundColor
alertIcon.backgroundColor = labelBackgroundColor
alertLabel.backgroundColor = labelBackgroundColor
}
open override func safeAreaInsetsDidChange() {
super.safeAreaInsetsDidChange()
if swipeState == .open {
swipeTranslation = swipeTranslationWhenOpen
}
setNeedsLayout()
}
var actionsViewInsets: UIEdgeInsets {
return safeAreaInsets
}
public final var statusViewDimension: CGFloat = 0 {
didSet {
setNeedsLayout()
}
}
public final var alertIconDimension: CGFloat = 0 {
didSet {
setNeedsLayout()
}
}
public var isStatusViewHidden: Bool = true {
didSet {
statusView.isHidden = isStatusViewHidden
setNeedsLayout()
}
}
public var isAlertLabelHidden: Bool = true {
didSet {
alertLabel.isHidden = isAlertLabelHidden
setNeedsLayout()
}
}
public var isAlertIconHidden: Bool = true {
didSet {
alertIcon.isHidden = isAlertIconHidden
setNeedsLayout()
}
}
public var isDeviceRTL: Bool {
return effectiveUserInterfaceLayoutDirection == .rightToLeft
}
public var isArticleRTL: Bool {
return articleSemanticContentAttribute == .forceRightToLeft
}
open override func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize {
let size = super.sizeThatFits(size, apply: apply)
if apply {
let layoutMargins = calculatedLayoutMargins
let isBatchEditOnRight = isDeviceRTL
var batchEditSelectViewWidth: CGFloat = 0
var batchEditX: CGFloat = 0
if isBatchEditingPaneOpen {
if isArticleRTL {
batchEditSelectViewWidth = isBatchEditOnRight ? layoutMargins.left : layoutMargins.right // left and and right here are really leading and trailing, should change to UIDirectionalEdgeInsets when available
} else {
batchEditSelectViewWidth = isBatchEditOnRight ? layoutMargins.right : layoutMargins.left
}
if isBatchEditOnRight {
batchEditX = size.width - batchEditSelectViewWidth
} else {
batchEditX = 0
}
} else {
if isBatchEditOnRight {
batchEditX = size.width
} else {
batchEditX = 0 - batchEditSelectViewWidth
}
}
let safeX = isBatchEditOnRight ? safeAreaInsets.right : safeAreaInsets.left
batchEditSelectViewWidth -= safeX
if !isBatchEditOnRight && isBatchEditingPaneOpen {
batchEditX += safeX
}
if isBatchEditOnRight && !isBatchEditingPaneOpen {
batchEditX -= batchEditSelectViewWidth
}
batchEditSelectView?.frame = CGRect(x: batchEditX, y: 0, width: batchEditSelectViewWidth, height: size.height)
batchEditSelectView?.layoutIfNeeded()
let actionsViewWidth = isDeviceRTL ? max(0, swipeTranslation) : -1 * min(0, swipeTranslation)
let x = isDeviceRTL ? 0 : size.width - actionsViewWidth
actionsView.frame = CGRect(x: x, y: 0, width: actionsViewWidth, height: size.height)
actionsView.layoutIfNeeded()
}
return size
}
// MARK - View configuration
// These properties can mutate with each use of the cell. They should be reset by the `reset` function. Call setsNeedLayout after adjusting any of these properties
public var titleTextStyle: DynamicTextStyle!
public var descriptionTextStyle: DynamicTextStyle!
public var extractTextStyle: DynamicTextStyle!
public var saveButtonTextStyle: DynamicTextStyle!
public var imageViewDimension: CGFloat! //used as height on full width cell, width & height on right aligned
public var spacing: CGFloat!
public var isImageViewHidden = false {
didSet {
imageView.isHidden = isImageViewHidden
setNeedsLayout()
}
}
open override func updateFonts(with traitCollection: UITraitCollection) {
super.updateFonts(with: traitCollection)
updateTitleLabel()
descriptionLabel.font = UIFont.wmf_font(descriptionTextStyle, compatibleWithTraitCollection: traitCollection)
extractLabel?.font = UIFont.wmf_font(extractTextStyle, compatibleWithTraitCollection: traitCollection)
alertLabel.font = UIFont.wmf_font(.semiboldCaption2, compatibleWithTraitCollection: traitCollection)
}
// MARK - Semantic content
fileprivate var _articleSemanticContentAttribute: UISemanticContentAttribute = .unspecified
fileprivate var _effectiveArticleSemanticContentAttribute: UISemanticContentAttribute = .unspecified
open var articleSemanticContentAttribute: UISemanticContentAttribute {
set {
_articleSemanticContentAttribute = newValue
updateEffectiveArticleSemanticContentAttribute()
setNeedsLayout()
}
get {
return _effectiveArticleSemanticContentAttribute
}
}
// for items like the Save Button that are localized and should match the UI direction
public var userInterfaceSemanticContentAttribute: UISemanticContentAttribute {
return traitCollection.layoutDirection == .rightToLeft ? .forceRightToLeft : .forceLeftToRight
}
fileprivate func updateEffectiveArticleSemanticContentAttribute() {
if _articleSemanticContentAttribute == .unspecified {
let isRTL = effectiveUserInterfaceLayoutDirection == .rightToLeft
_effectiveArticleSemanticContentAttribute = isRTL ? .forceRightToLeft : .forceLeftToRight
} else {
_effectiveArticleSemanticContentAttribute = _articleSemanticContentAttribute
}
let alignment = _effectiveArticleSemanticContentAttribute == .forceRightToLeft ? NSTextAlignment.right : NSTextAlignment.left
titleLabel.textAlignment = alignment
titleLabel.semanticContentAttribute = _effectiveArticleSemanticContentAttribute
descriptionLabel.semanticContentAttribute = _effectiveArticleSemanticContentAttribute
descriptionLabel.textAlignment = alignment
extractLabel?.semanticContentAttribute = _effectiveArticleSemanticContentAttribute
extractLabel?.textAlignment = alignment
}
open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
updateEffectiveArticleSemanticContentAttribute()
super.traitCollectionDidChange(previousTraitCollection)
}
// MARK - Accessibility
open override func updateAccessibilityElements() {
var updatedAccessibilityElements: [Any] = []
var groupedLabels = [titleLabel, descriptionLabel]
if let extract = extractLabel {
groupedLabels.append(extract)
}
updatedAccessibilityElements.append(LabelGroupAccessibilityElement(view: self, labels: groupedLabels, actions: actions))
accessibilityElements = updatedAccessibilityElements
}
// MARK: - Swipeable
var swipeState: SwipeState = .closed {
didSet {
if swipeState != .closed && actionsView.superview == nil {
contentView.addSubview(actionsView)
contentView.backgroundColor = backgroundView?.backgroundColor
clipsToBounds = true
} else if swipeState == .closed && actionsView.superview != nil {
actionsView.removeFromSuperview()
contentView.backgroundColor = .clear
clipsToBounds = false
}
}
}
public var swipeTranslation: CGFloat = 0 {
didSet {
assert(!swipeTranslation.isNaN && swipeTranslation.isFinite)
let isArticleRTL = articleSemanticContentAttribute == .forceRightToLeft
if isArticleRTL {
layoutMarginsInteractiveAdditions.left = 0 - swipeTranslation
layoutMarginsInteractiveAdditions.right = swipeTranslation
} else {
layoutMarginsInteractiveAdditions.right = 0 - swipeTranslation
layoutMarginsInteractiveAdditions.left = swipeTranslation
}
setNeedsLayout()
}
}
private var isBatchEditingPaneOpen: Bool {
return batchEditingTranslation > 0
}
private var batchEditingTranslation: CGFloat = 0 {
didSet {
let marginAddition = batchEditingTranslation / 1.5
if isArticleRTL {
if isDeviceRTL {
layoutMarginsInteractiveAdditions.left = marginAddition
} else {
layoutMarginsInteractiveAdditions.right = marginAddition
}
} else {
if isDeviceRTL {
layoutMarginsInteractiveAdditions.right = marginAddition
} else {
layoutMarginsInteractiveAdditions.left = marginAddition
}
}
if isBatchEditingPaneOpen, let batchEditSelectView = batchEditSelectView {
contentView.addSubview(batchEditSelectView)
batchEditSelectView.clipsToBounds = true
}
setNeedsLayout()
}
}
public override func layoutWidth(for size: CGSize) -> CGFloat {
let layoutWidth = super.layoutWidth(for: size) - layoutMarginsInteractiveAdditions.left - layoutMarginsInteractiveAdditions.right
return layoutWidth
}
public var swipeTranslationWhenOpen: CGFloat {
let maxWidth = actionsView.maximumWidth
let isRTL = effectiveUserInterfaceLayoutDirection == .rightToLeft
return isRTL ? actionsViewInsets.left + maxWidth : 0 - maxWidth - actionsViewInsets.right
}
// MARK: Prepare for reuse
func resetSwipeable() {
swipeTranslation = 0
swipeState = .closed
}
// MARK: - BatchEditableCell
public var batchEditSelectView: BatchEditSelectView?
public var isBatchEditable: Bool = false {
didSet {
if isBatchEditable && batchEditSelectView == nil {
batchEditSelectView = BatchEditSelectView()
batchEditSelectView?.isSelected = isSelected
} else if !isBatchEditable && batchEditSelectView != nil {
batchEditSelectView?.removeFromSuperview()
batchEditSelectView = nil
}
}
}
public var isBatchEditing: Bool = false {
didSet {
if isBatchEditing {
isBatchEditable = true
batchEditingTranslation = BatchEditSelectView.fixedWidth
batchEditSelectView?.isSelected = isSelected
} else {
batchEditingTranslation = 0
}
}
}
override open var isSelected: Bool {
didSet {
batchEditSelectView?.isSelected = isSelected
}
}
}
| mit | 07537c72fb49395a7b78a60191834e2e | 35.750617 | 224 | 0.636993 | 6.71055 | false | false | false | false |
SwiftAndroid/swift | test/IDE/import_as_member_cf.swift | 1 | 1269 | // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t -I %S/Inputs/custom-modules) -print-module -source-filename %s -module-to-print=ImportAsMember.C -always-argument-labels > %t.printed.C.txt
// REQUIRES: objc_interop
// RUN: FileCheck %s -check-prefix=PRINTC -strict-whitespace < %t.printed.C.txt
// PRINTC: extension CCPowerSupply {
// PRINTC-NEXT: /*not inherited*/ init(watts watts: Double)
// PRINTC-NEXT: class let semiModular: CCPowerSupply!
// PRINTC-NEXT: class let defaultPower: Double
// PRINTC-NEXT: class let AC: CCPowerSupply
// PRINTC-NEXT: class let DC: CCPowerSupply?
// PRINTC-NEXT: }
// PRINTC: extension CCRefrigerator {
// PRINTC-NEXT: /*not inherited*/ init(powerSupply power: CCPowerSupply)
// PRINTC-NEXT: func open()
// PRINTC-NEXT: var powerSupply: CCPowerSupply
// PRINTC-NEXT: }
// PRINTC: extension CCMutableRefrigerator {
// PRINTC-NEXT: /*not inherited*/ init(powerSupply power: CCPowerSupply)
// PRINTC-NEXT: }
// RUN: %target-parse-verify-swift -I %S/Inputs/custom-modules
import ImportAsMember.C
let powerSupply = CCPowerSupply(watts: 500.0)
let refrigerator = CCRefrigerator(powerSupply: powerSupply)
refrigerator.open();
refrigerator.powerSupply = powerSupply
| apache-2.0 | 3b941c07b91df89741769bee28772f79 | 38.65625 | 223 | 0.723404 | 3.515235 | false | false | false | false |
mfreiwald/RealDebridKit | RealDebridKit/Classes/Models/User.swift | 1 | 1543 | //
// User.swift
// Pods
//
// Created by Michael Freiwald on 21.11.16.
//
//
import Foundation
import Gloss
public struct User : Decodable {
public let id:Int
public let username:String
public let email:String
public let points:Int
public let locale:String
public let avatar:String
public let type:String
public let premium:Int
public let expiration:String
public init?(json: JSON) {
guard let id: Int = "id" <~~ json else {
return nil
}
guard let username: String = "username" <~~ json else {
return nil
}
guard let email: String = "email" <~~ json else {
return nil
}
guard let points: Int = "points" <~~ json else {
return nil
}
guard let locale: String = "locale" <~~ json else {
return nil
}
guard let avatar: String = "avatar" <~~ json else {
return nil
}
guard let type: String = "type" <~~ json else {
return nil
}
guard let premium: Int = "premium" <~~ json else {
return nil
}
guard let expiration: String = "expiration" <~~ json else {
return nil
}
self.id = id
self.username = username
self.email = email
self.points = points
self.locale = locale
self.avatar = avatar
self.type = type
self.premium = premium
self.expiration = expiration
}
}
| mit | 2a223c7199f378ddc4c0a7c6e24be739 | 23.109375 | 67 | 0.529488 | 4.498542 | false | false | false | false |
eliasbagley/Pesticide | debugdrawer/SampleViewController.swift | 1 | 5793 | //
// SampleViewController.swift
// debugdrawer
//
// Created by Daniel Gubler on 11/21/14.
// Copyright (c) 2014 Rocketmade. All rights reserved.
//
class SampleViewController : UIViewController, UITextFieldDelegate {
let textField: UITextField = UITextField()
let enterButton: UIButton = UIButton()
let label: UILabel = UILabel()
let coolLabel: UILabel = UILabel()
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override init() {
super.init()
self.setupView()
self.enterButton.addTarget(self, action: Selector("enterButtonTouch:"), forControlEvents: .TouchUpInside)
#if DEBUG
Pesticide.addCommand("log", block: { (components: Array<String>) in
if components.count < 1 {
Pesticide.log("Hurray a log")
return
}
if let times = components[0].toInt() {
for count in 0..<times {
Pesticide.log("did it \(count)")
}
}
})
Pesticide.addCommand("stab", block: { (components: Array<String>) in
if components.count < 1 {
Pesticide.log("Ouch")
return
}
if let times = components[0].toInt() {
for count in 0..<times {
Pesticide.log("die, die, die")
}
}
})
Pesticide.addButton("Panic Button", { () in
assert(false, "SOME CRASH AHHHH!!!!")
})
Pesticide.addSlider(Float(self.view.alpha),name:"Alpha", block: { (value :Float) in
let currentColor = self.view.backgroundColor
self.view.alpha = CGFloat(value)
})
Pesticide.addTextInput("Auto Layout", block: { (text: String) in
self.label.text = text
})
Pesticide.addDropdown("Blue",name: "Color", options: ["Black":UIColor.blackColor(),"Blue":UIColor.blueColor(),"Red":UIColor.redColor(),"Green":UIColor.greenColor()], block:{(option:AnyObject) in
let newColor = option as UIColor
self.view.backgroundColor = newColor
})
Pesticide.addButton("Network Request", { () in
(UIApplication.sharedApplication().delegate as AppDelegate).makeNetworkRequest()
})
#endif
print("sample inited")
}
func enterButtonTouch(sender: UIButton!) {
self.label.text = "Hello, " + self.textField.text
#if DEBUG
Pesticide.log("INPUT: \(self.textField.text)")
#endif
}
func setupView() {
self.view.backgroundColor = UIColor(red: 0.16, green: 0.16, blue: 0.18, alpha: 1)
self.enterButton.setTitle("Say Hello", forState: .Normal)
self.enterButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
self.textField.placeholder = "Your Name"
self.coolLabel.text = " This label is in the way"
self.coolLabel.backgroundColor = .yellowColor()
self.coolLabel.textColor = .blackColor()
self.textField.setTranslatesAutoresizingMaskIntoConstraints(false)
self.enterButton.setTranslatesAutoresizingMaskIntoConstraints(false)
self.label.setTranslatesAutoresizingMaskIntoConstraints(false)
self.coolLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
self.textField.delegate = self
self.textField.backgroundColor = .whiteColor()
self.enterButton.backgroundColor = .whiteColor()
self.label.backgroundColor = .whiteColor()
self.view.addSubview(self.textField)
self.view.addSubview(self.enterButton)
self.view.addSubview(self.label)
self.view.addSubview(self.coolLabel)
self.applyConstraints()
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func applyConstraints() {
let bindings = ["textField": self.textField,
"button": self.enterButton,
"label": self.label,
"coolLabel": self.coolLabel]
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-(40)-[textField(40)]-[button(40)]-[label(40)]", options: NSLayoutFormatOptions(0), metrics: nil, views: bindings))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-(40)-[coolLabel(40)]", options: NSLayoutFormatOptions(0), metrics: nil, views: bindings))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"|-[textField]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: bindings))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"|-[button]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: bindings))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"|-[label]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: bindings))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-[coolLabel]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: bindings))
}
} | mit | 6386c1e3e04f92ba245ef3f80056e20b | 38.684932 | 206 | 0.586052 | 5.329347 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceApplication/Tests/EurofurenceApplicationTests/Application/Components/News/Widgets/Announcements/Model/NewsAnnouncementsDataSourceRepositoryAdapterTests.swift | 1 | 1087 | import Combine
import EurofurenceApplication
import EurofurenceModel
import XCTest
import XCTEurofurenceModel
class NewsAnnouncementsDataSourceRepositoryAdapterTests: XCTestCase {
func testPropogatesAnnouncements() {
let announcements = [FakeAnnouncement.random, FakeAnnouncement.random, FakeAnnouncement.random]
let service = FakeAnnouncementsRepository(announcements: announcements)
let dataSource = NewsAnnouncementsDataSourceRepositoryAdapter(repository: service)
var observedAnnouncements: [FakeAnnouncement] = []
let subscription = dataSource
.announcements
.sink { (upstreamAnnouncements) in
observedAnnouncements = (upstreamAnnouncements as? [FakeAnnouncement]) ?? []
}
defer {
subscription.cancel()
}
let announcementsEqual = announcements.elementsEqual(observedAnnouncements, by: { $0 === $1 })
XCTAssertTrue(announcementsEqual, "Expected to receive announcements from repository")
}
}
| mit | 95f22455efb8bbbde10e0057da0a8d7e | 35.233333 | 103 | 0.689052 | 6.283237 | false | true | false | false |
enmiller/PeekABoo | PeekABoo/AppDelegate.swift | 1 | 2139 | //
// AppDelegate.swift
// PeekABoo
//
// Created by Eric Miller on 10/25/15.
// Copyright © 2015 Eric Miller. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var shortcutItem: UIApplicationShortcutItem?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
var performShortcutDelegate = true
if let shortcut = launchOptions?[UIApplicationLaunchOptionsShortcutItemKey] as? UIApplicationShortcutItem {
shortcutItem = shortcut
performShortcutDelegate = false
}
return performShortcutDelegate
}
func applicationDidBecomeActive(application: UIApplication) {
guard let shortcut = shortcutItem else { return }
handleShortcut(shortcut)
self.shortcutItem = nil
}
func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {
completionHandler(handleShortcut(shortcutItem))
}
func handleShortcut(shortcut: UIApplicationShortcutItem) -> Bool {
var succeeded = false
switch (shortcut.type) {
case "com.tinyzepplin.PeekABoo.blueScreen":
succeeded = true
if let vc = window?.rootViewController as? ViewController {
vc.view.backgroundColor = .blueColor()
}
case "com.tinyzepplin.PeekABoo.redScreen":
succeeded = true
if let vc = window?.rootViewController as? ViewController {
vc.view.backgroundColor = .redColor()
}
case "com.tinyzepplin.PeekABoo.greenScreen":
succeeded = true
if let vc = window?.rootViewController as? ViewController {
vc.view.backgroundColor = .greenColor()
}
default: break
}
return succeeded
}
}
| mit | 84eee536c4268cdb24bd34dd7db036fd | 29.542857 | 155 | 0.620674 | 5.762803 | false | false | false | false |
artsy/Emergence | Emergence/Contexts/App Setup/Auth and Slideshow/AuthViewController.swift | 1 | 3925 | import UIKit
import Moya
import Artsy_Authentication
import ARAnalytics
/// Shows a slideshow of Artsy logos
/// until we've got all the networking for the next VC cached
class AuthViewController: UIViewController {
var featuredShows:[Show] = []
var completedAuthentication = false
@IBOutlet weak var errorMessageLabel: UILabel!
@IBOutlet weak var slideshowView: SlideshowView!
@IBOutlet weak var artsyLogoImageView: UIImageView!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
errorMessageLabel.hidden = true
startSlideshow()
if isFirstRun == false {
artsyLogoImageView.image = UIImage(named: "artsy-logo-black")
errorMessageLabel.textColor = .blackColor()
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
login()
}
func login() {
guard let appVC = self.appViewController else {
return print("you need an app VC")
}
appVC.auth { success in
// If you're offline, let people know there is a problem and try
// again in 0.3 seconds, you've only got 1-2 seconds in here
// so sooner is better.
if success == false {
self.errorMessageLabel.hidden = false
self.errorMessageLabel.backgroundColor = .clearColor()
return delay(0.3) { self.login() }
}
self.completedAuthentication = true
let network = appVC.context.network
network.request(.FeaturedShows).mapSuccessfulHTTPToObjectArray(Show).subscribe(onNext: { shows in
self.featuredShows = shows
}, onError: { error in
print("ERROROR \(error)")
}, onCompleted: nil, onDisposed: nil)
}
}
lazy var isFirstRun:Bool = {
let key = "have_ran"
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.boolForKey(key) { return false }
ARAnalytics.event("first user install")
defaults.setBool(true, forKey: key)
defaults.synchronize()
return true
}()
var initialDelay: Double {
return 0.7
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let locationsVC = segue.destinationViewController as? ShowsOverviewViewController {
locationsVC.cachedShows = self.featuredShows
}
}
// TODO: If authenticated, support skipping on tap?
}
extension AuthViewController {
// TODO: Move to delegate / functions on the slideshow?
func startSlideshow() {
let images:[String]
if isFirstRun {
images = ["slide-bg-1.jpg", "slide-bg-2.jpg", "slide-bg-3.jpg"]
} else {
images = ["white.png", "white.png", "white.png"]
}
slideshowView.imagePaths = images
slideshowView.next()
print("waiting \(initialDelay)")
performSelector("nextSlide", withObject: nil, afterDelay: initialDelay)
}
func endSlideshow() {
self.performSegueWithIdentifier("menu", sender: self)
}
func shouldFinishSlideshow() -> Bool {
let completedCache = featuredShows.isNotEmpty
let skipBecauseCached = completedCache && isFirstRun == false
let outOfSlides = slideshowView.hasMoreSlides() == false
return outOfSlides || skipBecauseCached
}
func nextSlide() {
if shouldFinishSlideshow() {
return endSlideshow()
}
slideshowView.next()
var delay = initialDelay - 0.3 + (0.1 * Double(slideshowView.slidesLeft()) );
delay = max(delay, 0.1)
print("waiting \(delay)")
performSelector("nextSlide", withObject: nil, afterDelay: delay)
}
}
| mit | c342de1edf38dd6426ee7796ea115a14 | 28.961832 | 109 | 0.608408 | 4.943325 | false | false | false | false |
mike4aday/SwiftlySalesforce | Sources/SwiftlySalesforce/Credential.swift | 1 | 2438 | import Foundation
public struct Credential: Codable, Equatable {
public let accessToken: String
public let instanceURL: URL
public let identityURL: URL
public let timestamp: Date
public let refreshToken: String?
public let siteURL: URL?
public let siteID: String?
internal init(
accessToken: String,
instanceURL: URL,
identityURL: URL,
timestamp: Date,
refreshToken: String? = nil,
siteURL: URL? = nil,
siteID: String? = nil
) {
self.accessToken = accessToken
self.instanceURL = instanceURL
self.identityURL = identityURL
self.timestamp = timestamp
self.refreshToken = refreshToken
self.siteURL = siteURL
self.siteID = siteID
}
/// The ID of the Salesforce User record associated with this credential.
var userID: String {
return identityURL.lastPathComponent
}
/// The ID of the Salesforce Organization record associated with this credential.
var orgID: String {
return identityURL.deletingLastPathComponent().lastPathComponent
}
}
internal extension Credential {
init?(fromPercentEncoded: String, andRefreshToken: String? = nil) {
var comps = URLComponents()
comps.percentEncodedQuery = fromPercentEncoded
// Non-nillable properties
guard let queryItems: [URLQueryItem] = comps.queryItems,
let accessToken: String = queryItems["access_token"],
let instanceURL: URL = queryItems["instance_url"].flatMap({ URL(string: $0) }),
let identityURL: URL = queryItems["id"].flatMap({ URL(string: $0) }),
let timestamp: Date = queryItems["issued_at"].flatMap({ Double($0) }).map({ Date(timeIntervalSince1970: $0/1000) }) else {
return nil
}
// Nillable properties
let refreshToken: String? = queryItems["refresh_token"] ?? andRefreshToken
let siteURL: URL? = queryItems["sfdc_site_url"].flatMap({ URL(string: $0) })
let siteID: String? = queryItems["sfdc_site_id"]
self.init(
accessToken: accessToken,
instanceURL: instanceURL,
identityURL: identityURL,
timestamp: timestamp,
refreshToken: refreshToken,
siteURL: siteURL,
siteID: siteID
)
}
}
| mit | eec806d14693499951292cfb154e402d | 31.945946 | 136 | 0.611157 | 5.198294 | false | false | false | false |
ayong6/iOSNote | swift语言/swift语言/6. 函数.playground/Contents.swift | 1 | 4133 | //: Playground - noun: a place where people can play
import UIKit
// 函数
/*
函数的格式
func 函数名(参数) -> 返回值 { 代码块 }
1. 如果没有参数,写成()
2. 如果没有返回值,写成 () / Void 或者 不写
*/
// 常见的函数类型
// 1> 没有参数,没有返回值的函数
func sayHelloWorld() {
print("hello world")
}
// 2> 有参数,没有返回值的函数
func sayHelloWorld(name: String) {
print("\(name):hello world")
}
sayHelloWorld("xiaoming")
// 3> 没有参数,有返回值的函数
func sayHello() -> String {
return "hello world"
}
sayHello()
// 4> 有参数,有返回值的函数
func sayHello(personName: String, alreadyGreeted: Bool) -> String {
if alreadyGreeted {
return "\(personName) true"
} else {
return "\(personName) flase"
}
}
print(sayHello("Tim", alreadyGreeted: true))
// 5> 多重返回值函数
func minMax(array: [Int]) -> (min: Int, max: Int) {
return (array.first!, array.last!)
}
// 函数参数名称
// 函数参数都有一个外部参数名称和一个局部参数名称:
// 外部参数名用于在函数调用时标注传递给函数的参数
// 局部参数名在函数的实现内部调用。
// 所有参数必须有独一无二的局部参数名。
// 1> 默认情况下,第一个参数省略外部参数名, 从第二个参数开始,其局部参数名也是外部参数名。
func test1(name: String, age: Int, height: Double) {
}
test1("xiaohei", age: 18, height: 171.0)
// 2> 我们可以指定外部参数名: 如果你指定了外部参数名,函数被调用时,必须使用外部参数名。
func test2(name: String, andAge age: Int, andHeight height: Double) {
}
test2("xiaohei", andAge: 18, andHeight: 171.0)
// 3> 如果你不想为第二个及后续的参数设置外部参数名,用一个下划线 _代替一个明确的参数名。
func test3(name: String, _ age: Int, _ height: Double) {
}
test3("xiaohei", 17, 171.0)
// 3. 默认参数值
// 3.1 你可以在函数体中为每个参数定义默认值。当默认值被定义后,调用这个函数时可以忽略这个参数
// 3.2 将带有默认值的参数放在函数参数列表的最后,这样可以保证在函数调用时,非默认参数的顺序是一致的,同时使得相同函数在不同情况下调用时显的更为清晰
// 4. 可变参数
// 一个可变参数可以接受零个或者多个值。函数调用时,你可以用可变参数来制定函数参数可以被传入不确定数量的输入值。
// 4.1 通过变量类型名后面加入...的方式来定义可变参数
// 4.2 可变参数传入的值在函数体中变为此类型的一个数组。
// 4.3 一个函数最多只能有一个可变参数
// 4.4 如果函数有一个或者多个带默认值的参数,而且还有一个可变参数,那么把可变参数放在参数列表的最后
func arithmeticMean(numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
// 5. 常量参数和变量参数
// 5.1 函数参数默认是常量
// 5.2 通过再参数前面加关键字 var 来定义变量参数
// 5.3 好处:通过指定一个或者多个参数为变量参数,从而避免自己再函数中定义新的变量,你可以在函数中把它当做新的可修改的副本来使用。
// 6. 输入输出函数
// 6.1 变量参数,仅仅只能再函数体内被更改。如果你想要一个函数可以修改参数的值,并且想要在这些修改的在函数调用结束后仍然存在,那么就应该把这个参数定义为输入输出参数
// 6.2 定义输入输出参数,在参数名前加 inout 关键字
func swapTwoInts(inout a: Int, inout _ b: Int) {
let temporaryA = a
a = b
b = temporaryA
}
func printMathResult(mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
print("Result: \(mathFunction(a, b))")
}
// 6. 函数类型
// 6.1 函数类型作为参数
// 6.2 函数类型作为返回类型
| apache-2.0 | d42923a07a19d4618c8af9ab2b7b0853 | 19.669421 | 85 | 0.676529 | 2.486083 | false | false | false | false |
kreeger/pinwheel | Classes/DataSources/PinsDataSource.swift | 1 | 3140 | //
// Pinwheel // PinsDataSource.swift
// Copyright (c) 2014 Ben Kreeger. All rights reserved.
//
import UIKit
class PinsDataSource: NSObject {
let coordinator: PinboardCoordinator
var delegate: PinsDataSourceDelegate?
var pins: [Pin]
init(coordinator: PinboardCoordinator) {
self.coordinator = coordinator
self.pins = [Pin]()
super.init()
}
func fetchPins(completion: ((Void) -> Void)?) {
coordinator.syncPins(tags: nil) { pins, error in
if let value = pins { self.pins = value }
self.delegate?.dataSource?(self, didRefreshWithPins: pins)
completion?()
}
}
func registerCells(collectionView: UICollectionView!) {
collectionView.registerClass(PinCollectionViewCell.self, forCellWithReuseIdentifier: PinCollectionViewCellID)
}
func pinForIndexPath(indexPath: NSIndexPath) -> Pin {
return self.pins[indexPath.item]
}
func sizeForItemAtIndexPath(indexPath: NSIndexPath, constrainedToWidth width: CGFloat) -> CGSize {
let pin = pinForIndexPath(indexPath)
let title = pin.title as NSString
let maxSize = CGSize(width: width - 32, height: CGFloat.max)
let style = NSMutableParagraphStyle()
style.lineBreakMode = NSLineBreakMode.ByWordWrapping
let attributes: [NSObject:AnyObject] = [NSParagraphStyleAttributeName: style,
NSFontAttributeName: PinCollectionViewCell.labelFont()]
let boundingRect = title.boundingRectWithSize(maxSize,
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: attributes,
context: NSStringDrawingContext())
return CGSize(width: width, height: CGRectIntegral(boundingRect).size.height + 32)
}
}
extension PinsDataSource: UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return pins.count
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PinCollectionViewCellID, forIndexPath: indexPath) as PinCollectionViewCell
let pin = pinForIndexPath(indexPath)
cell.label.text = pin.title
return cell
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView!) -> Int {
return 1
}
// The view that is returned must be retrieved from a call to -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:
func collectionView(collectionView: UICollectionView!, viewForSupplementaryElementOfKind kind: String!, atIndexPath indexPath: NSIndexPath!) -> UICollectionReusableView! {
return nil
}
}
| mit | 373b8d326b8d246074534c60ce4a49ac | 42.611111 | 175 | 0.670701 | 6.003824 | false | false | false | false |
apple-programmer/general_mac_anonymizer | MKO project/Brew functions.swift | 1 | 1054 | //
// Brew functions.swift
// MKO project
//
// Created by Roman Nikitin on 08.02.16.
// Copyright © 2016 NikRom. All rights reserved.
//
import Foundation
import Cocoa
func isBrewInstalled() -> Bool {
let arr = runCommand(command: "command -v /usr/local/bin/brew")
return !arr.isEmpty
}
func installBrew() {
runCommand(command: "/usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"")
}
func initBrew() {
if !isBrewInstalled() {
let alert = NSAlert()
alert.messageText = "You have not installed HomeBrew!"
alert.informativeText = "Home brew is needed to install tor and privoxy"
alert.addButtonWithTitle("OK, install")
alert.addButtonWithTitle("Cancel")
let response = alert.runModal()
if response == NSAlertFirstButtonReturn {
print("User agreed")
installBrew()
}
else {
print("User refused to install HomeBrew")
exit(0);
}
}
}
| artistic-2.0 | d5d799eb99f8930caa736cf0d606ab78 | 24.071429 | 127 | 0.611586 | 4.113281 | false | false | false | false |
nicolastinkl/swift | ListerAProductivityAppBuiltinSwift/Lister/CheckBoxLayer.swift | 1 | 3489 | /*
Copyright (C) 2014 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A CALayer subclass that draws a check box within its layer. This is shared between ListerKit and ListerKitOSX to draw their respective CheckBox controls.
*/
import QuartzCore
class CheckBoxLayer: CALayer {
// MARK: Types
struct SharedColors {
static let defaultTintColor = CGColorCreate(CGColorSpaceCreateDeviceRGB(), [0.5, 0.5, 0.5])
}
// MARK: Properties
var tintColor: CGColor = SharedColors.defaultTintColor {
didSet {
setNeedsDisplay()
}
}
var isChecked: Bool = false {
didSet {
setNeedsDisplay()
}
}
var strokeFactor: CGFloat = 0.07 {
didSet {
setNeedsDisplay()
}
}
var insetFactor: CGFloat = 0.17 {
didSet {
setNeedsDisplay()
}
}
var markInsetFactor: CGFloat = 0.34 {
didSet {
setNeedsDisplay()
}
}
// MARK: Overrides
override class func needsDisplayForKey(key: String) -> Bool {
// Check to see if the key is contained in the array.
// The array contains a ist of keys that this layer subclass supports.
if ["tintColor", "isChecked", "strokeFactor", "insetFactor", "markInsetFactor"] ~= key {
return true
}
return super.needsDisplayForKey(key)
}
// The method that does the heavy lifting of check box drawing code.
override func drawInContext(context: CGContext) {
super.drawInContext(context)
let size = min(bounds.size.width, bounds.size.height)
var transform = affineTransform()
var xTranslate: CGFloat = 0
var yTranslate: CGFloat = 0
if bounds.size.width < bounds.size.height {
yTranslate = (bounds.size.height - size) / 2.0
}
else {
xTranslate = (bounds.size.width - size) / 2.0
}
transform = CGAffineTransformTranslate(transform, xTranslate, yTranslate)
let strokeWidth: CGFloat = strokeFactor * size
let checkBoxInset: CGFloat = insetFactor * size
// Create the outer border for the check box.
let outerDimension: CGFloat = size - 2.0 * checkBoxInset
var checkBoxRect = CGRect(x: checkBoxInset, y: checkBoxInset, width: outerDimension, height: outerDimension)
checkBoxRect = CGRectApplyAffineTransform(checkBoxRect, transform)
// Make the desired width of the outer box.
CGContextSetLineWidth(context, strokeWidth)
// Set the tint color of the outer box.
CGContextSetStrokeColorWithColor(context, tintColor)
// Draw the outer box.
CGContextStrokeRect(context, checkBoxRect)
// Draw the inner box if it's checked.
if isChecked {
let markInset: CGFloat = markInsetFactor * size
let markDimension: CGFloat = size - 2.0 * markInset
var markRect = CGRect(x: markInset, y: markInset, width: markDimension, height: markDimension)
markRect = CGRectApplyAffineTransform(markRect, transform)
CGContextSetFillColorWithColor(context, tintColor)
CGContextFillRect(context, markRect)
}
}
}
| mit | 6311924445490a128bdd8d4efabf1634 | 30.133929 | 169 | 0.599943 | 5.173591 | false | false | false | false |
laszlokorte/reform-swift | ReformCore/ReformCore/FormIdentifier.swift | 1 | 703 | //
// FormIdentifier.swift
// ReformCore
//
// Created by Laszlo Korte on 13.08.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
public struct FormIdentifier : Hashable {
public let value : Int
public init(_ value : Int) {
self.value = value
}
public var hashValue : Int { return Int(value) }
}
public func ==(lhs: FormIdentifier, rhs: FormIdentifier) -> Bool {
return lhs.value == rhs.value
}
extension FormIdentifier : CustomDebugStringConvertible {
public var debugDescription : String {
return "FormId(\(value))"
}
}
extension FormIdentifier : SequenceGeneratable {
public init(id : Int) {
self.init(id)
}
} | mit | 85731eb10e7c4fd709781d2f1eda1602 | 20.30303 | 66 | 0.643875 | 4.129412 | false | false | false | false |
leizh007/HiPDA | HiPDA/HiPDA/Sections/Home/NewThread/EmoticonParser.swift | 1 | 1197 | //
// EmoticonParser.swift
// HiPDA
//
// Created by leizh007 on 2017/6/20.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import Foundation
import YYText
class EmoticonParser: YYTextSimpleEmoticonParser {
private let attachImageRegex = try! NSRegularExpression(pattern: "\\[attachimg\\](\\d+)\\[\\/attachimg\\]", options: .caseInsensitive)
override func parseText(_ text: NSMutableAttributedString?, selectedRange: NSRangePointer?) -> Bool {
if let text = text {
text.yy_setFont(UIFont.systemFont(ofSize: 17.0), range: text.yy_rangeOfAll())
text.yy_setColor(.black, range: text.yy_rangeOfAll())
attachImageRegex.enumerateMatches(in: text.string, options: .withoutAnchoringBounds, range: text.yy_rangeOfAll()) { (result, _, _) in
guard let result = result else { return }
let range = result.range
if range.location == NSNotFound || range.length < 1 {
return
}
text.yy_setColor(C.Color.navigationBarTintColor, range: range)
}
}
return super.parseText(text, selectedRange: selectedRange)
}
}
| mit | 1475fa97a5e38086087547617f364e47 | 38.8 | 145 | 0.623116 | 4.522727 | false | false | false | false |
cdmx/MiniMancera | miniMancera/Model/Home/Abstract/MHomeOptions.swift | 1 | 1187 | import UIKit
class MHomeOptions
{
private(set) weak var dataOption:DOption?
private(set) var title:String?
private(set) var descr:String?
private(set) var thumbnail:UIImage?
private(set) var splashImage:UIImage?
private(set) var scoreIcon:UIImage?
required init(dataOption:DOption)
{
self.dataOption = dataOption
}
//MARK: public
func gameController() -> UIViewController?
{
return nil
}
//MARK: final
final func gameControllerWith<T:MGame>(type:ControllerGame<T>.Type) -> ControllerGame<T>?
{
guard
let dataOption:DOption = self.dataOption
else
{
return nil
}
let controller:ControllerGame<T> = type.init(dataOption:dataOption)
return controller
}
final func available() -> Bool
{
guard
let dataOption:DOptionPurchase = dataOption as? DOptionPurchase
else
{
return true
}
let purchased:Bool = dataOption.purchased
return purchased
}
}
| mit | 361343fa7d1622381ae583a81c33f313 | 19.824561 | 93 | 0.551811 | 5.008439 | false | false | false | false |
bmichotte/HSTracker | HSTracker/Statistics/StatsHelper.swift | 1 | 13722 | //
// StatsHelper.swift
// HSTracker
//
// Created by Matthew Welborn on 6/9/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import RealmSwift
import CleanroomLogger
class StatsTableRow: NSObject { // Class instead of struct so we can use sortUsingDescriptors
// Used for display
var classIcon = ""
var opponentClassName = ""
var record = ""
var winRate = ""
var confidenceInterval = ""
// Used for sorting
var totalGames = 0
var winRateNumber = -1.0
var confidenceWindow = 1.0
}
class LadderTableRow: NSObject { // Class instead of struct so we can use sortUsingDescriptors
// Used for display
var rank = ""
var games = ""
var gamesCI = ""
var time = ""
var timeCI = ""
}
struct StatsDeckRecord {
var wins = 0
var losses = 0
var draws = 0
var total = 0
}
class StatsHelper {
static let statsUIConfidence: Double = 0.9 // Maybe this could become user settable
static let lg = LadderGrid()
static func getStatsUITableData(deck: Deck,
mode: GameMode = .ranked, season: Int) -> [StatsTableRow] {
var tableData = [StatsTableRow]()
for againstClass in [.neutral] + Cards.classes {
let dataRow = StatsTableRow()
if againstClass == .neutral {
dataRow.classIcon = "AppIcon"
} else {
dataRow.classIcon = againstClass.rawValue
}
dataRow.opponentClassName =
NSLocalizedString(againstClass.rawValue,
comment: "").capitalized
let record = getDeckRecord(deck: deck, againstClass: againstClass,
mode: mode, season: season)
dataRow.record = getDeckRecordString(record: record)
dataRow.winRate = getDeckWinRateString(record: record)
dataRow.winRateNumber = getDeckWinRate(record: record)
dataRow.totalGames = record.total
dataRow.confidenceInterval = getDeckConfidenceString(record: record,
confidence: statsUIConfidence)
let interval = binomialProportionCondifenceInterval(wins: record.wins,
losses: record.losses,
confidence: statsUIConfidence)
dataRow.confidenceWindow = interval.upper - interval.lower
tableData.append(dataRow)
}
return tableData
}
static func getLadderTableData(deck: Deck, rank: Int,
stars: Int, streak: Bool) -> [LadderTableRow] {
var tableData = [LadderTableRow]()
let record = getDeckRecord(deck: deck, againstClass: .neutral, mode: .ranked)
let tpg = getDeckTimePerGame(deck: deck, againstClass: .neutral, mode: .ranked)
let winRate = getDeckWinRate(record: record)
let totalStars = Ranks.starsAtRank[rank]! + stars
var bonus: Int = 0
if streak {
bonus = 2
}
for target_rank in [20, 15, 10, 5, 0] {
let dataRow = LadderTableRow()
if target_rank == 0 {
dataRow.rank = "Legend"
} else {
dataRow.rank = String(target_rank)
}
if rank <= target_rank || winRate == -1.0 {
dataRow.games = "--"
dataRow.gamesCI = "--"
dataRow.time = "--"
dataRow.timeCI = "--"
} else {
// Closures for repeated tasks
let getGames = { (winp: Double) -> Double? in
return lg.getGamesToRank(targetRank: target_rank,
stars: totalStars,
bonus: bonus,
winp: winp)
}
let formatGames = { (games: Double) -> String in
if games > 1000 {
return ">1000"
} else {
return String(Int(round(games)))
}
}
let formatTime = { (games: Double, timePerGame: Double) -> String in
let hours = games * timePerGame / 3600
if hours > 100 {
return ">100"
} else {
return String(format: "%.1f", hours)
}
}
// Means
if let g2r = getGames(winRate) {
dataRow.games = formatGames(g2r)
dataRow.time = formatTime(g2r, tpg)
} else {
dataRow.games = "Error"
dataRow.time = "Error"
}
//Confidence intervals
let interval = binomialProportionCondifenceInterval(wins: record.wins,
losses: record.losses,
confidence: statsUIConfidence)
if let lg2r = getGames(interval.lower),
let ug2r = getGames(interval.upper) {
dataRow.gamesCI = "\(formatGames(ug2r)) - \(formatGames(lg2r))"
dataRow.timeCI = "\(formatTime(ug2r, tpg)) - \(formatTime(lg2r, tpg))"
} else {
dataRow.gamesCI = "Error"
dataRow.timeCI = "Error"
}
}
tableData.append(dataRow)
}
return tableData
}
static func getDeckManagerRecordLabel(deck: Deck, mode: GameMode) -> String {
let record = getDeckRecord(deck: deck, mode: mode)
let totalGames = record.total
if totalGames == 0 {
return "0 - 0"
}
return "\(record.wins) - \(record.losses) (\(getDeckWinRateString(record: record)))"
}
static func getDeckRecordString(record: StatsDeckRecord) -> String {
return "\(record.wins)-\(record.losses)"
}
static func getDeckWinRate(record: StatsDeckRecord) -> Double {
let totalGames = record.wins + record.losses
var winRate = -1.0
if totalGames > 0 {
winRate = Double(record.wins)/Double(totalGames)
}
return winRate
}
static func getDeckTimePerGame(deck: Deck, againstClass: CardClass = .neutral,
mode: GameMode = .ranked) -> Double {
var stats = Array(deck.gameStats)
if againstClass != .neutral {
stats = stats.filter { $0.opponentHero == againstClass }
}
var rankedStats: [GameStats]
if mode == .all {
rankedStats = stats
} else {
rankedStats = stats.filter { $0.gameMode == mode }
}
var time: Double = 0.0
for stat in rankedStats {
let duration = stat.endTime.timeIntervalSince1970 - stat.startTime.timeIntervalSince1970
time += Double(duration)
}
time /= Double(rankedStats.count)
return time
}
static func getDeckWinRateString(record: StatsDeckRecord) -> String {
var winRateString = "N/A"
let winRate = getDeckWinRate(record: record)
if winRate >= 0.0 {
let winPercent = Int(round(winRate * 100))
winRateString = String(winPercent) + "%"
}
return winRateString
}
static func getDeckRecord(deck: Deck, againstClass: CardClass = .neutral,
mode: GameMode = .ranked, season: Int = 0) -> StatsDeckRecord {
var stats = Array(deck.gameStats)
if againstClass != .neutral {
stats = stats.filter { $0.opponentHero == againstClass }
}
if season > 0 {
stats = stats.filter { $0.season == season }
}
var rankedStats: [GameStats]
if mode == .all {
rankedStats = stats
} else {
rankedStats = stats.filter { $0.gameMode == mode }
}
let wins = rankedStats.filter { $0.result == .win }.count
let losses = rankedStats.filter { $0.result == .loss }.count
let draws = rankedStats.filter { $0.result == .draw }.count
return StatsDeckRecord(wins: wins,
losses: losses,
draws: draws,
total: wins + losses + draws)
}
static func getDeckConfidenceString(record: StatsDeckRecord,
confidence: Double = 0.9) -> String {
let interval = binomialProportionCondifenceInterval(wins: record.wins,
losses: record.losses,
confidence: confidence)
let intLower = Int(round(interval.lower*100))
let intUpper = Int(round(interval.upper*100))
return String(format: "%3d%% - %3d%%", arguments: [intLower, intUpper])
}
static func guessRank(deck: Deck) -> Int {
let isStandard = deck.standardViable()
guard let sdecks = RealmHelper.getDecks() else { return -1 }
let decks = sdecks
.filter({$0.standardViable() == isStandard})
.filter({!$0.isArena})
var mostRecent: GameStats?
for deck_i in decks {
let datedRankedGames = deck_i.gameStats.filter { $0.gameMode == .ranked }
if let latest = datedRankedGames.max(by: {$0.startTime < $1.startTime}) {
if let mr = mostRecent {
if mr.startTime < latest.startTime {
mostRecent = latest
}
} else {
mostRecent = latest
}
}
}
if let mr = mostRecent {
return mr.rank
} else {
return 25
}
}
struct BinomialInterval {
var lower: Double
var upper: Double
var mean: Double
}
static func binomialProportionCondifenceInterval(wins: Int, losses: Int,
confidence: Double = 0.9) -> BinomialInterval {
// Implements the Wilson interval
let alpha = 1.0 - confidence
assert(alpha >= 0.0)
assert(alpha <= 1.0)
let n = Double(wins + losses)
// bounds checking
if n < 1 {
return BinomialInterval(lower: 0.0, upper: 1.0, mean: 0.5)
}
let quantile = 1 - 0.5 * alpha
let z = sqrt(2) * erfinv(y: 2 * quantile - 1)
let p = Double(wins) / Double(n)
let center = p + z * z / (2 * n)
let spl = p * (1 - p) / n + z * z / (4 * n * n)
let spread = z * sqrt(spl)
let prefactor = 1 / (1 + z * z / n)
var lower = prefactor * (center - spread)
var upper = prefactor * (center + spread)
let mean = prefactor * (center)
lower = max(lower, 0.0)
upper = min(upper, 1.0)
return BinomialInterval(lower: lower, upper: upper, mean: mean)
}
static func erfinv(y: Double) -> Double {
// Taken from: http://stackoverflow.com/questions/36784763
let center = 0.7
let a = [ 0.886226899, -1.645349621, 0.914624893, -0.140543331]
let b = [-2.118377725, 1.442710462, -0.329097515, 0.012229801]
let c = [-1.970840454, -1.624906493, 3.429567803, 1.641345311]
let d = [ 3.543889200, 1.637067800]
if abs(y) <= center {
let z = pow(y, 2)
let num = (((a[3] * z + a[2]) * z + a[1]) * z) + a[0]
let den = ((((b[3] * z + b[2]) * z + b[1]) * z + b[0]) * z + 1.0)
var x = y * num / den
x -= (erf(x) - y) / (2.0 / sqrt(.pi) * exp(-x * x))
x -= (erf(x) - y) / (2.0 / sqrt(.pi) * exp(-x * x))
return x
} else if abs(y) > center && abs(y) < 1.0 {
let z = pow(-log((1.0 - abs(y)) / 2), 0.5)
let num = ((c[3] * z + c[2]) * z + c[1]) * z + c[0]
let den = (d[1] * z + d[0]) * z + 1
// should use the sign function instead of pow(pow(y,2),0.5)
var x = y / pow(pow(y, 2), 0.5) * num / den
x -= (erf(x) - y) / (2.0 / sqrt(.pi) * exp(-x * x))
x -= (erf(x) - y) / (2.0 / sqrt(.pi) * exp(-x * x))
return x
} else if abs(y) == 1 {
return y * Double(Int.max)
} else {
return Double.nan
}
}
static func GetBinCoeff(N: Int, K: Int) -> Int {
// This function gets the total number of unique combinations based upon N and K.
// N is the total number of items.
// K is the size of the group.
// Total number of unique combinations = N! / ( K! (N - K)! ).
// This function is less efficient,
// but is more likely to not overflow when N and K are large.
// Taken from: http://blog.plover.com/math/choose.html
//
var r = 1
var d = 0
if K > N { return 0 }
var n = N
d = 1
while d <= K {
r *= n
n -= 1
r /= d
d += 1
}
return r
}
}
| mit | ee8d0931c03062add6a22e07dbbc4100 | 33.913486 | 100 | 0.485679 | 4.506076 | false | false | false | false |
ViennaRSS/vienna-rss | Vienna/Sources/Main window/BrowserTab.swift | 2 | 12564 | //
// BrowserTab.swift
// Vienna
//
// Copyright 2018
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Cocoa
import WebKit
// MARK: State
class BrowserTab: NSViewController {
// MARK: Properties
var webView: CustomWKWebView
@IBOutlet private(set) weak var addressBarContainer: NSView!
@IBOutlet private(set) weak var addressField: NSTextField!
@IBOutlet private(set) weak var backButton: NSButton!
@IBOutlet private(set) weak var forwardButton: NSButton!
@IBOutlet private(set) weak var reloadButton: NSButton!
@IBOutlet private(set) weak var progressBar: LoadingIndicator?
var webViewTopConstraint: NSLayoutConstraint!
@IBOutlet private(set) weak var cancelButtonWidth: NSLayoutConstraint!
@IBOutlet private(set) weak var reloadButtonWidth: NSLayoutConstraint!
@IBOutlet private(set) weak var rssButtonWidth: NSLayoutConstraint!
var url: URL? {
didSet {
updateTabTitle()
updateUrlTextField()
}
}
var loadedTab = false
var loading = false
var loadingProgress: Double = 0 {
didSet { updateVisualLoadingProgress() }
}
/// functions that get callbacks on every navigation start
var navigationStartHandler: [() -> Void] = []
/// functions that get callbacks on every navigation end or abort
var navigationEndHandler: [(_ success: Bool) -> Void] = []
/// backing storage only, access via rssSubscriber property
weak var rssDelegate: RSSSubscriber?
/// backing storage only, access via rssUrl property
var rssFeedUrls: [URL] = []
var showRssButton = false
var viewVisible = false
private var titleObservation: NSKeyValueObservation?
private var loadingObservation: NSKeyValueObservation?
private var progressObservation: NSKeyValueObservation?
private var urlObservation: NSKeyValueObservation?
private var statusBarObservation: NSKeyValueObservation?
private var statusBar: OverlayStatusBar?
// MARK: object lifecycle
init(_ request: URLRequest? = nil, config: WKWebViewConfiguration = WKWebViewConfiguration()) {
self.webView = CustomWKWebView(configuration: config)
if #available(macOS 10.14, *) {
super.init(nibName: "BrowserTab", bundle: nil)
} else {
super.init(nibName: "BrowserTabWithLegacyAddressBar", bundle: nil)
}
titleObservation = webView.observe(\.title, options: .new) { [weak self] _, change in
guard let newValue = change.newValue ?? "", !newValue.isEmpty else {
return
}
self?.title = newValue
}
loadingObservation = webView.observe(\.isLoading, options: .new) { [weak self] _, change in
guard let newValue = change.newValue else {
return
}
self?.loading = newValue
}
progressObservation = webView.observe(\.estimatedProgress, options: .new) { [weak self] _, change in
guard let newValue = change.newValue else {
return
}
self?.loadingProgress = newValue
}
urlObservation = webView.observe(\.url, options: .new) { [weak self] _, change in
guard let newValue = change.newValue, newValue != nil else {
return
}
self?.url = newValue
}
statusBarObservation = Preferences.standard.observe(\.showStatusBar, options: [.initial, .new]) { [weak self] _, change in
guard let newValue = change.newValue else {
return
}
if newValue && self?.statusBar == nil {
let newBar = OverlayStatusBar()
self?.statusBar = newBar
self?.view.addSubview(newBar)
} else if !newValue && self?.statusBar != nil {
self?.statusBar?.removeFromSuperview()
self?.statusBar = nil
}
}
if let request = request {
webView.load(request)
}
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
titleObservation?.invalidate()
loadingObservation?.invalidate()
progressObservation?.invalidate()
urlObservation?.invalidate()
statusBarObservation?.invalidate()
}
// MARK: ViewController lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// set up webview (not yet possible via interface builder)
webView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(webView, positioned: .below, relativeTo: addressBarContainer)
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[webView]|", options: [], metrics: nil, views: ["webView": webView]))
webViewTopConstraint = NSLayoutConstraint(item: self.view, attribute: .top, relatedBy: .equal, toItem: webView, attribute: .top, multiplier: -1, constant: 0)
let webViewBottomConstraint = NSLayoutConstraint(item: webView, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: 0)
self.view.addConstraints([webViewTopConstraint, webViewBottomConstraint])
// title needs to be adjusted once view is loaded
// reload button / cancel button layout is not determined yet
self.loading = self.webView.isLoading
// set up url displayed in address field
if let url = webView.url {
self.url = url
}
self.viewDidLoadRss()
updateWebViewInsets()
// set up address bar handling
addressField.delegate = self
// set up navigation handling
webView.navigationDelegate = self
}
override func viewWillAppear() {
super.viewWillAppear()
addressBarContainer.layoutSubtreeIfNeeded()
self.viewVisible = true
}
override func viewDidAppear() {
super.viewDidAppear()
if self.loadedTab {
activateWebView()
}
}
override func viewDidDisappear() {
super.viewDidDisappear()
self.viewVisible = false
}
}
// MARK: Tab functionality
extension BrowserTab: Tab {
var tabUrl: URL? {
get {
self.url
}
set {
self.url = newValue
self.loadedTab = false
}
}
var textSelection: String {
webView.textSelection
}
var html: String {
"" // TODO: get HTML and return
}
var isLoading: Bool {
loading
}
func back() -> Bool {
let couldGoBack = self.webView.goBack() != nil
// title and url observation not triggered by goBack() -> manual setting
self.url = self.webView.url
updateTabTitle()
return couldGoBack
}
func forward() -> Bool {
let couldGoForward = self.webView.goForward() != nil
// title observation not triggered by goForware() -> manual setting
self.url = self.webView.url
updateTabTitle()
return couldGoForward
}
func canScrollDown() -> Bool {
return self.webView.canScrollDown
}
func canScrollUp() -> Bool {
return self.webView.canScrollUp
}
override func scrollPageDown(_ sender: Any?) {
self.webView.scrollPageDown(sender)
}
override func scrollPageUp(_ sender: Any?) {
self.webView.scrollPageUp(sender)
}
func searchFor(_ searchString: String, action: NSFindPanelAction) {
// webView.evaluateJavaScript("document.execCommand('HiliteColor', false, 'yellow')", completionHandler: nil)
self.webView.search(searchString, upward: action == .previous)
}
func loadTab() {
if self.isViewLoaded {
self.addressField.stringValue = self.url?.absoluteString ?? ""
}
if let url = self.url {
self.webView.load(URLRequest(url: url))
loadedTab = true
if self.isViewLoaded && self.view.window != nil {
self.activateWebView()
}
} else {
self.webView.load(URLRequest(url: URL.blank))
self.activateAddressBar()
}
}
func reloadTab() {
if self.webView.url != nil {
self.webView.reload()
// To know what we have reloaded if the text was changed manually
updateUrlTextField()
} else {
// When we have never loaded the webview yet, reload is actually load
loadTab()
}
}
func stopLoadingTab() {
let wasLoading = loading
self.webView.stopLoading()
if wasLoading {
// We must manually invoke navigation end callbacks
self.handleNavigationEnd(success: false)
}
}
func closeTab() {
stopLoadingTab()
// free webView by force stopping JavaScript and resetting delegates
self.webView.evaluateJavaScript("window.location.replace('about:blank');") { _, _ in
DispatchQueue.main.async {
self.webView.navigationDelegate = nil
self.webView.uiDelegate = nil
}
}
}
@objc
func resetTextSize() {
webView.makeTextStandardSize(self)
}
@objc
func decreaseTextSize() {
webView.makeTextSmaller(self)
}
@objc
func increaseTextSize() {
webView.makeTextLarger(self)
}
func printDocument(_ sender: Any?) {
webView.printView(sender)
}
func activateAddressBar() {
self.view.window?.makeFirstResponder(addressField)
}
func activateWebView() {
self.view.window?.makeFirstResponder(self.webView)
}
}
// MARK: Webview navigation
extension BrowserTab: WKNavigationDelegate {
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation?) {
handleNavigationStart()
if let webView = webView as? CustomWKWebView {
webView.hoverListener = self
self.statusBar?.label = ""
}
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation?, withError error: Error) {
// TODO: provisional navigation fail seems to translate to error in resolving URL or similar. Treat different from normal navigation fail
handleNavigationEnd(success: false)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation?, withError error: Error) {
// TODO: show failure to load as page or symbol
handleNavigationEnd(success: false)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation?) {
handleNavigationEnd(success: true)
}
func handleNavigationStart() {
navigationStartHandler.forEach { $0() }
updateAddressBarButtons()
}
func handleNavigationEnd(success: Bool) {
navigationEndHandler.forEach { $0(success) }
updateAddressBarButtons()
}
func registerNavigationStartHandler(_ navigationStartHandler: @escaping () -> Void) {
self.navigationStartHandler.append(navigationStartHandler)
}
func registerNavigationEndHandler(_ navigationEndHandler: @escaping (_ success: Bool) -> Void) {
self.navigationEndHandler.append(navigationEndHandler)
}
}
// MARK: Javascript messages handler
extension BrowserTab: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if self.statusBar != nil {
if message.name == CustomWKWebView.mouseDidEnterName {
if let link = message.body as? String {
self.statusBar?.label = link
}
} else if message.name == CustomWKWebView.mouseDidExitName {
self.statusBar?.label = ""
}
}
}
}
| apache-2.0 | c33f1d9e0bd9069dd2bb13535efcf911 | 30.331671 | 177 | 0.629815 | 5.053902 | false | false | false | false |
hevertonrodrigues/HRSkills | HRSkills/UIColorExtension.swift | 1 | 1915 | //
// UIColorExtension.swift
// HRSkills
//
// Created by Heverton Rodrigues on 16/09/14.
// Copyright (c) 2014 Heverton Rodrigues. All rights reserved.
//
import UIKit
/**
* String Extension
*
* @package HRSkills/Extesions
* @author Heverton Rodrigues
* @since 2014-09-16
* @version 1.0
*/
extension UIColor
{
/**
* Constructor with rgba STRING
*
* @param rgba String
*/
convenience init(rgba: String)
{
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if rgba.hasPrefix("#")
{
let index = advance(rgba.startIndex, 1)
let hex = rgba.substringFromIndex(index)
let scanner = NSScanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexLongLong(&hexValue)
{
if hex.length == 6
{
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
} else if hex.length == 8
{
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
} else
{
print("invalid rgb string, length should be 7 or 9")
}
} else
{
println("scan hex error")
}
} else
{
print("invalid rgb string, missing '#' as prefix")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
} | mit | 51c731066d1e1eda5d7967bb87f859cc | 28.476923 | 74 | 0.485117 | 4.181223 | false | false | false | false |
jianghongbing/APIReferenceDemo | Swift/Syntax/Generics.playground/Contents.swift | 1 | 1743 | //: Playground - noun: a place where people can play
import UIKit
//泛型:泛型能够根据自定义的需求,编写出适用于任意类型、灵活可重用的函数及类型。它能让你避免代码的重复,用一种清晰和抽象的方式来表达代码的意图
//1.泛型函数
//泛型参数类型放在参数表的括号的前面,T表示参数的类型
func swapTwoValues<T>(a: inout T, b: inout T) {
let temp = a
a = b
b = temp
}
var numberA = 10, numberB = 20
var stringA = "abc", stringB = "edg"
//swap(&numberA, &numberB)
swapTwoValues(a: &numberA, b: &numberB)
print(numberA, numberB)
swapTwoValues(a: &stringA, b: &stringB)
print(stringA, stringB)
//定义多个泛型参数的函数
//2.定义泛型类型
struct Stack<E> {
var elements = [E]()
mutating func pop() -> E?{
return elements.count > 0 ? elements.removeLast() : nil
}
mutating func push(element: E) {
elements.append(element)
}
}
//泛型类型的使用
var intStack = Stack<Int>()
intStack.push(element: 5)
intStack.push(element: 10)
intStack.push(element: 20)
intStack.pop()
intStack.pop()
var stringStack = Stack<String>()
stringStack.push(element: "a")
stringStack.push(element: "b")
stringStack.push(element: "c")
stringStack.pop()
//扩展泛型
extension Stack {
var last: E? {
return elements.last
}
var first: E? {
return elements.first
}
}
intStack.first
intStack.last
stringStack.first
stringStack.last
//3.类型约束
//约束类型符合Comparable协议,如果要求符合多个协议,协议之间用&符号来链接
func twoValuesIsEqual<T: Comparable>(a: T, b: T) -> Bool {
return a == b
}
twoValuesIsEqual(a: 10, b: 10)
//4.关联类型
| mit | ecc8830c19e77394071aa0045d11816c | 17.454545 | 72 | 0.672766 | 2.842 | false | false | false | false |
mrdepth/EVEOnlineAPI | EVEAPI/EVEAPI/EVECharacters.swift | 1 | 1876 | //
// EVECharacters.swift
// EVEAPI
//
// Created by Artem Shimanski on 28.11.16.
// Copyright © 2016 Artem Shimanski. All rights reserved.
//
import UIKit
public class EVECharactersItem: EVEObject {
public var characterID: Int64 = 0
public var characterName: String = ""
public var corporationID: Int64 = 0
public var corporationName: String = ""
public var allianceID: Int64 = 0
public var allianceName: String = ""
public var factionID: Int64 = 0
public var factionName: String = ""
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"characterID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"characterName":EVESchemeElementType.String(elementName:"name", transformer:nil),
"corporationID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"corporationName":EVESchemeElementType.String(elementName:nil, transformer:nil),
"allianceID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"allianceName":EVESchemeElementType.String(elementName:nil, transformer:nil),
"factionID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"factionName":EVESchemeElementType.String(elementName:nil, transformer:nil),
]
}
}
public class EVECharacters: EVEResult {
public var characters: [EVECharactersItem] = []
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"characters":EVESchemeElementType.Rowset(elementName: nil, type: EVECharactersItem.self, transformer: nil)
]
}
}
| mit | ca6d6fbb15b4ab5e40e80289820921cb | 30.779661 | 109 | 0.749867 | 3.834356 | false | false | false | false |
ioscreator/ioscreator | IOSAirPrintTutorial/IOSAirPrintTutorial/ViewController.swift | 1 | 1090 | //
// ViewController.swift
// IOSAirPrintTutorial
//
// Created by Arthur Knopper on 15/03/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBAction func printText(_ sender: Any) {
// 1
let printController = UIPrintInteractionController.shared
// 2
let printInfo = UIPrintInfo(dictionary:nil)
printInfo.outputType = .general
printInfo.jobName = "print Job"
printController.printInfo = printInfo
// 3
let formatter = UIMarkupTextPrintFormatter(markupText: textView.text)
formatter.perPageContentInsets = UIEdgeInsets(top: 72, left: 72, bottom: 72, right: 72)
printController.printFormatter = formatter
// 4
printController.present(animated: true, completionHandler: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
| mit | 8dea71f0a61fe0c0ce1f283b590a1eaf | 26.923077 | 95 | 0.652893 | 4.734783 | false | false | false | false |
csnu17/My-Swift-learning | HalfTunes/HalfTunes/TrackCell.swift | 1 | 3803 | /**
* Copyright (c) 2017 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.
*
* Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
* distribute, sublicense, create a derivative work, and/or sell copies of the
* Software in any work that is designed, intended, or marketed for pedagogical or
* instructional purposes related to programming, coding, application development,
* or information technology. Permission for such use, copying, modification,
* merger, publication, distribution, sublicensing, creation of derivative works,
* or sale is expressly withheld.
*
* 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
protocol TrackCellDelegate: class {
func pauseTapped(_ cell: TrackCell)
func resumeTapped(_ cell: TrackCell)
func cancelTapped(_ cell: TrackCell)
func downloadTapped(_ cell: TrackCell)
}
class TrackCell: UITableViewCell {
// Delegate identifies track for this cell,
// then passes this to a download service method.
weak var delegate: TrackCellDelegate?
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var artistLabel: UILabel!
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var progressLabel: UILabel!
@IBOutlet weak var pauseButton: UIButton!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var downloadButton: UIButton!
@IBAction func pauseOrResumeTapped(_ sender: AnyObject) {
if pauseButton.titleLabel?.text == "Pause" {
delegate?.pauseTapped(self)
} else {
delegate?.resumeTapped(self)
}
}
@IBAction func cancelTapped(_ sender: AnyObject) {
delegate?.cancelTapped(self)
}
@IBAction func downloadTapped(_ sender: AnyObject) {
delegate?.downloadTapped(self)
}
func configure(track: Track, download: Download?) {
titleLabel.text = track.name
artistLabel.text = track.artist
var showDownloadControls = false
if let download = download {
showDownloadControls = true
let title = download.isDownloading ? "Pause" : "Resume"
pauseButton.setTitle(title, for: .normal)
progressLabel.text = download.isDownloading ? "Downloading..." : "Paused"
}
pauseButton.isHidden = !showDownloadControls
cancelButton.isHidden = !showDownloadControls
progressLabel.isHidden = !showDownloadControls
progressView.isHidden = !showDownloadControls
// If the track is already downloaded, enable cell selection and hide the Download button
selectionStyle = track.downloaded ? .gray : .none
downloadButton.isHidden = track.downloaded || showDownloadControls
}
func updateDisplay(progress: Float, totalSize: String) {
progressView.progress = progress
progressLabel.text = String(format: "%.1f%% of %@", progress * 100, totalSize)
}
}
| mit | 5ec98ecc50460ef5b9e6cc091ee62fa7 | 37.806122 | 93 | 0.735735 | 4.73599 | false | false | false | false |
hgani/ganiweb-ios | ganiweb/Classes/HtmlForm/KeyValue.swift | 1 | 359 | struct KeyValue: CustomStringConvertible {
var text: String
var value: String
init(text: String, value: String) {
self.text = text
self.value = value
}
var description: String { return text }
}
extension KeyValue: Equatable {}
func ==(lhs: KeyValue, rhs: KeyValue) -> Bool {
return lhs.value == rhs.value
}
| mit | ccfc056037731b7b5c9173532def4ea7 | 20.117647 | 47 | 0.62117 | 4.174419 | false | false | false | false |
diegosanchezr/Chatto | Chatto/Source/ChatController/ChatViewController+Presenters.swift | 1 | 5073 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
extension ChatViewController: ChatCollectionViewLayoutDelegate {
public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.decoratedChatItems.count
}
public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let presenter = self.presenterForIndexPath(indexPath)
let cell = presenter.dequeueCell(collectionView: collectionView, indexPath: indexPath)
let decorationAttributes = self.decorationAttributesForIndexPath(indexPath)
presenter.configureCell(cell, decorationAttributes: decorationAttributes)
return cell
}
public func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
// Carefull: this index path can refer to old data source after an update. Don't use it to grab items from the model
// Instead let's use a mapping presenter <--> cell
if let oldPresenterForCell = self.presentersByCell.objectForKey(cell) as? ChatItemPresenterProtocol {
self.presentersByCell.removeObjectForKey(cell)
oldPresenterForCell.cellWasHidden(cell)
}
}
public func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
// Here indexPath should always referer to updated data source.
let presenter = self.presenterForIndexPath(indexPath)
self.presentersByCell.setObject(presenter, forKey: cell)
presenter.cellWillBeShown(cell)
}
public func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return self.presenterForIndexPath(indexPath).shouldShowMenu() ?? false
}
public func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
return self.presenterForIndexPath(indexPath).canPerformMenuControllerAction(action) ?? false
}
public func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
self.presenterForIndexPath(indexPath).performMenuControllerAction(action)
}
public func presenterForIndexPath(indexPath: NSIndexPath) -> ChatItemPresenterProtocol {
return self.presenterForIndex(indexPath.item, decoratedChatItems: self.decoratedChatItems)
}
public func presenterForIndex(index: Int, decoratedChatItems: [DecoratedChatItem]) -> ChatItemPresenterProtocol {
guard index < decoratedChatItems.count else {
// This can happen from didEndDisplayingCell if we reloaded with less messages
return DummyChatItemPresenter()
}
let chatItem = decoratedChatItems[index].chatItem
if let presenter = self.presentersByChatItem.objectForKey(chatItem) as? ChatItemPresenterProtocol {
return presenter
}
let presenter = self.createPresenterForChatItem(chatItem)
self.presentersByChatItem.setObject(presenter, forKey: chatItem)
return presenter
}
public func createPresenterForChatItem(chatItem: ChatItemProtocol) -> ChatItemPresenterProtocol {
for builder in self.presenterBuildersByType[chatItem.type] ?? [] {
if builder.canHandleChatItem(chatItem) {
return builder.createPresenterWithChatItem(chatItem)
}
}
return DummyChatItemPresenter()
}
public func decorationAttributesForIndexPath(indexPath: NSIndexPath) -> ChatItemDecorationAttributesProtocol? {
return self.decoratedChatItems[indexPath.item].decorationAttributes
}
}
| mit | 1eb8d67241aab49594d220e5379d5f7e | 49.73 | 183 | 0.758526 | 5.764773 | false | false | false | false |
flexih/CorePlayer.Swift | CorePlayer/CPModuleView.swift | 1 | 1085 | //
// CPModuleView.swift
// CorePlayer
//
// Created by flexih on 4/20/15.
// Copyright (c) 2015 flexih. All rights reserved.
//
#if os(iOS)
import UIKit
public typealias UXView = UIView
#else
import AppKit
public typealias UXView = NSView
#endif
public class CPModuleView: UXView, CPModuleViewDelegate {
public var moduleID: Int = 0
public weak var moduleManager: CPModuleManager?
public weak var moduleDelegate: CorePlayerFeature?
public func moduleType() -> ModuleType {
return .View
}
/**
View hierarchy of player's view
*/
public func viewIndex() -> Int {
return 0
}
/**
When player's view layout, do custom layout
*/
public func layoutView() {
}
public func willShow() {
#if os(iOS)
alpha = 1
#endif
}
public func willHide() {
#if os(iOS)
alpha = 0
#endif
}
public func initModule() {
}
public func deinitModule() {
}
}
| mit | c9ca4d22531d13bb7765e1ea0d7e935b | 17.083333 | 57 | 0.551152 | 4.288538 | false | false | false | false |
kennydust/refresher | PullToRefreshDemo/PullToRefreshViewController.swift | 2 | 4058 | //
// ViewController.swift
//
// Copyright (c) 2014 Josip Cavar
//
// 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 Refresher
enum ExampleMode {
case Default
case Beat
case Pacman
case Custom
}
class PullToRefreshViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var exampleMode = ExampleMode.Default
override func viewDidLoad() {
super.viewDidLoad()
switch exampleMode {
case .Default:
tableView.addPullToRefreshWithAction {
NSOperationQueue().addOperationWithBlock {
sleep(2)
NSOperationQueue.mainQueue().addOperationWithBlock {
self.tableView.stopPullToRefresh()
}
}
}
case .Beat:
let beatAnimator = BeatAnimator(frame: CGRectMake(0, 0, 320, 80))
tableView.addPullToRefreshWithAction({
NSOperationQueue().addOperationWithBlock {
sleep(2)
NSOperationQueue.mainQueue().addOperationWithBlock {
self.tableView.stopPullToRefresh()
}
}
}, withAnimator: beatAnimator)
case .Pacman:
let pacmanAnimator = PacmanAnimator(frame: CGRectMake(0, 0, 320, 80))
tableView.addPullToRefreshWithAction({
NSOperationQueue().addOperationWithBlock {
sleep(2)
NSOperationQueue.mainQueue().addOperationWithBlock {
self.tableView.stopPullToRefresh()
}
}
}, withAnimator: pacmanAnimator)
case .Custom:
if let customSubview = NSBundle.mainBundle().loadNibNamed("CustomSubview", owner: self, options: nil).first as? CustomSubview {
tableView.addPullToRefreshWithAction({
NSOperationQueue().addOperationWithBlock {
sleep(2)
NSOperationQueue.mainQueue().addOperationWithBlock {
self.tableView.stopPullToRefresh()
}
}
}, withAnimator: customSubview)
}
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
tableView.startPullToRefresh()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return 50
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "Cell")
cell.textLabel?.text = "Row " + String(indexPath.row + 1)
return cell
}
}
| mit | 61b8b42bb900d2973293d071db80a9c9 | 37.283019 | 139 | 0.618531 | 5.780627 | false | false | false | false |
STShenZhaoliang/iOS-GuidesAndSampleCode | 精通Swift设计模式/Chapter 04/ObjectTemplate/ObjectTemplate/Product.swift | 1 | 636 | class Product {
var name:String;
var price:Double;
private var stockBackingValue:Int = 0;
var stock:Int {
get {
return stockBackingValue;
}
set {
stockBackingValue = max(0, newValue);
}
}
init(name:String, price:Double, stock:Int) {
self.name = name;
self.price = price;
self.stock = stock;
}
func calculateTax(rate: Double) -> Double {
return min(10, self.price * rate);
}
var stockValue: Double {
get {
return self.price * Double(self.stock);
}
}
}
| mit | 62a94a54c3f6e48782134ff65ad42208 | 19.516129 | 51 | 0.503145 | 4.103226 | false | false | false | false |
edwellbrook/gosquared-swift | Sources/GoSquaredAPI.swift | 1 | 2220 | //
// GoSquaredAPI.swift
// GoSquaredAPI
//
// Created by Edward Wellbrook on 22/05/2015.
// Copyright (c) 2015-2016 Edward Wellbrook. All rights reserved.
//
import Foundation
public class GoSquaredAPI {
public typealias Handler = (_ response: Any?, _ error: Error?) -> Void
public static let CommonDateFormatter = DateFormatter(dateFormat: "yyyy-MM-dd HH:mm:ss")
public static let CommonDateFormat = "YYYY-MM-DD HH:mm:ss"
public struct CombiningFunction {
let endpoint: String
let parameters: [String: String]
public init(endpoint: String, parameters: [String: String]) {
self.endpoint = endpoint
self.parameters = parameters
}
}
public var apiKey: String?
public var project: String?
public var bearerToken: String?
public static var urlSession = URLSession.shared
lazy public var account: Account = Account(client: self)
lazy public var auth: Auth = Auth(client: self)
lazy public var chat: Chat = Chat(client: self)
lazy public var ecommerce: Ecommerce = Ecommerce(client: self)
lazy public var now: Now = Now(client: self)
lazy public var trends: Trends = Trends(client: self)
lazy public var people: People = People(client: self)
public init(apiKey: String?, project: String? = nil) {
self.apiKey = apiKey
self.project = project
}
public init(bearerToken: String?, project: String? = nil) {
self.bearerToken = bearerToken
self.project = project
}
public static func performRequest(_ request: URLRequest, completionHandler: Handler?) {
GoSquaredAPI.urlSession.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
if error != nil {
completionHandler?(nil, error)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
completionHandler?(json, nil)
} catch let err as NSError {
completionHandler?(nil, err)
}
}
}.resume()
}
}
| mit | 55021d7907f69d99c6fd32019a062a55 | 29.410959 | 102 | 0.611712 | 4.539877 | false | false | false | false |
jtwp470/my-programming-learning-book | swift/day2/Doll2Yen/Doll2Yen/ViewController.swift | 1 | 1724 | //
// ViewController.swift
// Doll2Yen
//
// Created by jtwp470 on 7/9/15.
// Copyright (c) 2015 jtwp470. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
let kDoll = "DollKey"
let kRate = "RateKey"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let userDefaults = NSUserDefaults.standardUserDefaults()
dollText.text = userDefaults.stringForKey(kDoll)
rateText.text = userDefaults.stringForKey(kRate)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func saveDefault() {
let userDefaults = NSUserDefaults.standardUserDefaults()
// ドルとレートをデフォルトに保存
userDefaults.setObject(dollText.text, forKey: kDoll)
userDefaults.setObject(rateText.text, forKey: kRate)
userDefaults.synchronize()
}
@IBOutlet weak var dollText: UITextField!
@IBOutlet weak var rateText: UITextField!
@IBAction func calc(sender: AnyObject) {
let doll = (dollText.text as NSString).doubleValue
let rate = (rateText.text as NSString).doubleValue
yenLabel.text = "\(doll * rate)"
// ユーザーデフォルトを保存
saveDefault()
}
@IBOutlet weak var yenLabel: UILabel!
override class func initialize() {
let defaultValue = ["DollKey": "10", "RateKey": "116.5"]
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.registerDefaults(defaultValue)
}
} | unlicense | 88ff43ed0c470c80b9a2f990c77146d3 | 30.528302 | 80 | 0.660479 | 4.406332 | false | false | false | false |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/0589-swift-diagnosticengine-diagnose.swift | 13 | 575 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum B {
func b<T, k : b: b
print(array: k) {
func g<T.b {
var e: Any) {
let a<T])() ->(n: d = F
struct D : c = ""foobar"""
var d {
protocol b where S(a<T>() -> {
}
case b = F>](mx : a {
}(n: Any, T {
}
b.Element == {
b() -> S {
return b: a {
}
protocol b {
(seq
protocol c = B<j : X<f = f: b<T> {
var b, AnyObject) {
func b(1](t: H) {
}
"foobar","A, U.Type
}
| apache-2.0 | 6e0c88c27285ac6bc547fc888b9f7671 | 17.548387 | 87 | 0.586087 | 2.53304 | false | true | false | false |
testpress/ios-app | ios-app/UI/RelatedContentsCell.swift | 1 | 4173 | //
// RelatedContentsCell.swift
// ios-app
//
// Created by Karthik raja on 12/8/19.
// Copyright © 2019 Testpress. All rights reserved.
//
import UIKit
class RelatedContentsCell: UITableViewCell {
@IBOutlet weak var contentIcon: UIImageView!
@IBOutlet weak var bookmarkIcon: UIImageView!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var desc: UILabel!
var content: Content?
var index: Int?
var contents: [Content]?
var parentViewController: UIViewController? = nil
var isAlreadySelected: Bool = false
func initCell(index: Int, contents: [Content], viewController: UIViewController, is_current: Bool=false) {
parentViewController = viewController
content = contents[index]
self.contents = contents
self.index = index
title.text = content?.name
bookmarkIcon.isHidden = false
isAlreadySelected = false
if content?.exam != nil {
contentIcon.image = Images.Quill.image
bookmarkIcon.isHidden = true
} else if content?.htmlContentTitle != nil {
contentIcon.image = Images.Article.image
} else if content?.video != nil {
contentIcon.image = Images.VideoIcon.image
} else if content?.attachment != nil {
contentIcon.image = Images.Attachment.image
}
if content?.bookmarkId != nil {
bookmarkIcon.image = Images.RemoveBookmark.image
} else {
bookmarkIcon.image = Images.AddBookmark.image
}
contentIcon.setImageColor(color: Colors.getRGB(Colors.DIM_GRAY))
bookmarkIcon.setImageColor(color: Colors.getRGB(Colors.DIM_GRAY))
self.backgroundColor = Colors.getRGB(Colors.WHITE)
title.textColor = Colors.getRGB(Colors.DIM_GRAY)
desc.textColor = Colors.getRGB(Colors.DIM_GRAY)
desc.isHidden = true
if (is_current) {
isAlreadySelected = true
contentIcon.setImageColor(color: Colors.getRGB(Colors.PRIMARY))
bookmarkIcon.setImageColor(color: Colors.getRGB(Colors.PRIMARY))
self.backgroundColor = Colors.getRGB(Colors.PRIMARY, alpha: 0.1)
title.textColor = Colors.getRGB(Colors.PRIMARY)
desc.textColor = Colors.getRGB(Colors.PRIMARY)
if (content?.video != nil) {
desc.text = "Now Playing..."
desc.isHidden = false
}
}
let tapRecognizer = UITapGestureRecognizer(target: self,
action: #selector(self.onItemClick))
addGestureRecognizer(tapRecognizer)
bookmarkIcon.addTapGestureRecognizer{
if let viewController = self.parentViewController as? VideoContentViewController {
viewController.addOrRemoveBookmark(content: self.content)
}
}
}
@objc func onItemClick() {
if isAlreadySelected {
return
}
if (content?.video != nil && content!.video!.embedCode.isEmpty) {
if let viewController = self.parentViewController as? VideoContentViewController {
viewController.updateVideoAttempt()
viewController.changeVideo(content: content)
return
}
}
let storyboard = UIStoryboard(name: Constants.CHAPTER_CONTENT_STORYBOARD, bundle: nil)
let viewController = storyboard.instantiateViewController(
withIdentifier: Constants.CONTENT_DETAIL_PAGE_VIEW_CONTROLLER)
as! ContentDetailPageViewController
viewController.contents = contents!
viewController.title = content?.name
viewController.position = index
parentViewController?.present(viewController, animated: false, completion: nil)
}
}
extension UIImageView {
func setImageColor(color: UIColor) {
let templateImage = self.image?.withRenderingMode(.alwaysTemplate)
self.image = templateImage
self.tintColor = color
}
}
| mit | e9f687c2f47dacd1672336abb5626397 | 34.65812 | 110 | 0.616491 | 5.221527 | false | false | false | false |
radu-costea/ATests | ATests/ATests/UI/RegisterScreen/RegisterViewController.swift | 1 | 6244 | //
// RegisterViewController.swift
// ATests
//
// Created by Radu Costea on 11/04/16.
// Copyright © 2016 Radu Costea. All rights reserved.
//
import Foundation
import UIKit
import MobileCoreServices
import Parse
protocol ImagePickerDelegate: UINavigationControllerDelegate, UIImagePickerControllerDelegate {}
class RegisterViewController: ValidationFormViewController, ImagePickerDelegate {
let defaults = NSUserDefaults.standardUserDefaults()
lazy var emailVM: FieldValidationViewModel = ValidationFieldViewModel(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}")
lazy var firstNameVM: FieldValidationViewModel = WordLengthValidationFieldViewModel(length: 1)
lazy var lastNameVM: FieldValidationViewModel = WordLengthValidationFieldViewModel(length: 1)
lazy var passwordVM: FieldValidationViewModel = WordLengthValidationFieldViewModel(length: 6)
lazy var passwordCheckVM: FieldValidationViewModel = BlockValidationFieldViewModel() { [unowned self] model in
return (self.passwordVM.isValid && self.passwordVM.text == model.text)
}
// MARK: - Outlets
@IBOutlet var firstNameField: ValidationTextField!
@IBOutlet var lastNameField: ValidationTextField!
@IBOutlet var passwordField: ValidationTextField!
@IBOutlet var retypePasswordField: ValidationTextField!
@IBOutlet var emailField: ValidationTextField!
@IBOutlet var registerButton: UIButton!
@IBOutlet var avatarImageView: UIImageView!
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
firstNameField.delegate = self
lastNameField.delegate = self
passwordField.delegate = self
retypePasswordField.delegate = self
emailField.delegate = self
}
// MARK: - Overrides
override func createBindings() -> [ValidationTextField : FieldValidationViewModel] {
return [
self.firstNameField : self.firstNameVM,
self.lastNameField : self.lastNameVM,
self.passwordField : self.passwordVM,
self.retypePasswordField : self.passwordCheckVM,
self.emailField : self.emailVM
]
}
override func createViewModels() -> [FieldValidationViewModel] {
return [
self.firstNameVM,
self.lastNameVM,
self.passwordVM,
self.passwordCheckVM,
self.emailVM
]
}
override func validationFieldTextDidChanged(validationField: ValidationTextField) {
super.validationFieldTextDidChanged(validationField)
registerButton.enabled = formIsValid
}
// MARK: - Actions
var image: UIImage?
var user: ParseUser!
@IBAction func register(sender: UIButton?) -> Void {
let usr = ParseUser.object()
usr.password = passwordVM.text!
usr.username = emailVM.text!
usr.firstName = firstNameVM.text
usr.lastName = lastNameVM.text
usr.email = emailVM.text!
if let img = image,
let imageFile = PFFile(image: img) {
AnimatingViewController.showInController(self, status: "Preparing image ..")
imageFile.saveInBackgroundWithBlock({ (success, error) in
if let err = error {
self.registerEncounteredAnError(err)
return
}
usr.avatar = imageFile
self.completeSignUp(usr)
}, progressBlock: { (progress) in
AnimatingViewController.setStatus("Uploading image..\(progress)%")
})
return
}
completeSignUp(usr)
}
func completeSignUp(user: ParseUser) {
AnimatingViewController.showInController(self, status: "Registering user ..")
user.signUpInBackgroundWithBlock{ [unowned self] (success, error) in
if let err = error {
self.registerEncounteredAnError(err)
return
}
let email = self.emailVM.text!
let password = self.passwordVM.text!
// Save username
self.defaults.setObject(email, forKey: "username")
self.defaults.synchronize()
// Save password
let keychain = KeychainItemWrapper(identifier: email)
keychain["password"] = password
self.user = user
AnimatingViewController.hide({ [unowned self] in
self.performSegueWithIdentifier("registerFinished", sender: nil)
})
}
}
func registerEncounteredAnError(error: NSError) {
AnimatingViewController.hide()
UIAlertController.showIn(self, message: "An error occured while trying to register: \(error.localizedDescription)", actions: [], cancelAction: (title: "Ok", action: nil))
}
/// MARK: -
/// MARK: Navigation
override var navigationCallbacks: [String: (UIViewController) -> Void] {
return [
"toMyAccount" : { [unowned self] next in
self.view.endEditing(true)
let myAccountScreen = next as! MyAccountViewController
myAccountScreen.user = self.user!
}
]
}
/// MARK: -
/// MARK: Actions
@IBAction func loadImage(sender: UIButton?) -> Void {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .PhotoLibrary
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.delegate = self
presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let img = info[UIImagePickerControllerOriginalImage] as? UIImage
image = img
avatarImageView.image = img
picker.dismissViewControllerAnimated(true) { }
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
picker.dismissViewControllerAnimated(true) { }
}
}
| mit | 0d2cb1983d86a3b406e03ff728340b1a | 35.296512 | 178 | 0.634471 | 5.476316 | false | false | false | false |
LanfordCai/LC-Badge-View-Swift | LCBadgeView/LCBadgeView/LCBadgeView.swift | 2 | 6803 | //
// LCBadgeView.swift
// LCBadgeView
//
// Created by Cai Linfeng on 12/24/15.
// Copyright © 2015 GavinFlying. All rights reserved.
//
import UIKit
class LCBadgeView: UIView {
enum BadgeShiftDirectionType {
case Left
case Justify
case Right
}
// The badgeView's shift direction while text in it changed
var shiftDirection: BadgeShiftDirectionType = .Left {
didSet {
setupBadgeFrame()
}
}
enum BadgeTextOverflowType {
case N, Points, Nines, NinesPlus
func overflowTag(charCount: Int) -> String {
switch self {
case N:
return "N"
case Points:
return "..."
case Nines:
var nines = ""
for _ in 0..<charCount {
nines += "9"
}
return nines
case NinesPlus:
var ninesPlus = ""
for _ in 0..<charCount {
ninesPlus += "9"
}
ninesPlus += "+"
return ninesPlus
}
}
}
var overflowType: BadgeTextOverflowType = .NinesPlus {
didSet {
setupBadgeFrame()
}
}
var text: String? {
didSet {
textLayer?.string = text
hideBadgeWhenZero()
}
}
var textColor: UIColor = UIColor.whiteColor() {
didSet {
textLayer?.foregroundColor = textColor.CGColor
}
}
var font: UIFont = UIFont.systemFontOfSize(14) {
didSet {
if font.lineHeight > frame.height {
print("Font lineheight larger than badgeView's height")
font = oldValue
}
textLayer?.font = font.fontName
textLayer?.fontSize = font.pointSize
}
}
// The padding between text and border of badgeView is fontSize * paddingFactor
var paddingFactor: CGFloat = 0.4 {
didSet {
setupBadgeFrame()
}
}
var cornerRadius: CGFloat? {
didSet {
badgePath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius ?? bounds.height * 0.5)
backgroundLayer?.path = badgePath!.CGPath
borderLayer?.path = badgePath!.CGPath
}
}
var badgeBackgroundColor: UIColor = UIColor.redColor() {
didSet {
backgroundLayer?.fillColor = badgeBackgroundColor.CGColor
}
}
var borderColor: UIColor = UIColor.blackColor() {
didSet {
borderLayer?.strokeColor = borderColor.CGColor
}
}
var borderWidth: CGFloat = 0.0 {
didSet {
borderLayer?.lineWidth = borderWidth
}
}
var maxCharsCount: Int = 2
var hideWhenZero = true
private var textLayer: CATextLayer?
private var backgroundLayer: CAShapeLayer?
private var borderLayer: CAShapeLayer?
private var badgePath: UIBezierPath?
private var minWidth: CGFloat = 24.0
private var anchorLeftX: CGFloat?
private var anchorMiddleX: CGFloat?
private var anchorRightX: CGFloat?
// MARK: Life-Cycle Methods
override func awakeFromNib() {
super.awakeFromNib()
configurations()
}
init(frame: CGRect, shiftDirection: BadgeShiftDirectionType, cornerRadius: CGFloat) {
self.shiftDirection = shiftDirection
super.init(frame: frame)
configurations()
self.cornerRadius = cornerRadius
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configurations()
}
override func layoutSubviews() {
super.layoutSubviews()
setupBadgeFrame()
}
// MARK: Private Methods
private func configurations() {
backgroundColor = UIColor.clearColor()
userInteractionEnabled = false
clipsToBounds = false
// Create textLayer
textLayer = CATextLayer()
textLayer?.foregroundColor = textColor.CGColor
textLayer?.font = font.fontName
textLayer?.fontSize = font.pointSize ?? 14.0
textLayer?.alignmentMode = kCAAlignmentCenter
textLayer?.contentsScale = UIScreen.mainScreen().scale
// Create backgroundLayer
backgroundLayer = CAShapeLayer()
backgroundLayer?.contentsScale = UIScreen.mainScreen().scale
// Create boarderLyaer
borderLayer = CAShapeLayer()
borderLayer?.strokeColor = borderColor.CGColor
borderLayer?.fillColor = UIColor.clearColor().CGColor
borderLayer?.lineWidth = borderWidth
borderLayer?.contentsScale = UIScreen.mainScreen().scale
layer.addSublayer(backgroundLayer!)
layer.addSublayer(borderLayer!)
layer.addSublayer(textLayer!)
}
private func setupBadgeFrame() {
anchorLeftX = anchorLeftX ?? frame.origin.x
anchorMiddleX = anchorMiddleX ?? frame.origin.x + 0.5 * bounds.width
anchorRightX = anchorRightX ?? frame.origin.x + bounds.width
minWidth = bounds.height != 0 ? bounds.height : 24.0
if text?.characters.count > maxCharsCount {
text = overflowType.overflowTag(maxCharsCount)
}
var tempFrame = frame
let textWidth = sizeForText(text).width
tempFrame.size.width = textWidth < minWidth ? minWidth : textWidth
switch shiftDirection {
case .Left:
tempFrame.origin.x = anchorRightX! - tempFrame.size.width
case .Justify:
tempFrame.origin.x = anchorMiddleX! - tempFrame.size.width * 0.5
case .Right:
tempFrame.origin.x = anchorLeftX!
}
frame = tempFrame
let textFrame = CGRect(x: 0, y: (bounds.height - font.lineHeight) * 0.5, width: bounds.width, height: font.lineHeight)
textLayer?.frame = textFrame
badgePath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius ?? bounds.height * 0.5)
backgroundLayer?.frame = bounds
backgroundLayer?.fillColor = badgeBackgroundColor.CGColor
backgroundLayer?.path = badgePath!.CGPath
borderLayer?.frame = bounds
borderLayer?.path = badgePath!.CGPath
}
private func sizeForText(text: String?) -> CGSize {
guard let text = text as NSString? else {
return CGSize(width: 0.0, height: 0.0)
}
let widthPadding: CGFloat = font.pointSize * paddingFactor
let attrDict = [NSFontAttributeName: font]
var textSize = text.sizeWithAttributes(attrDict)
textSize.width += widthPadding * 2.0
return textSize
}
private func hideBadgeWhenZero() {
self.hidden = text == "0" && hideWhenZero
}
}
| mit | 7ba3c71a7bbf1dc1ff9e2065ea70467a | 26.538462 | 126 | 0.593502 | 5.145234 | false | false | false | false |
raychrd/tada | tada/MK/MKLayer.swift | 3 | 7951 | //
// MKLayer.swift
// MaterialKit
//
// Created by Le Van Nghia on 11/15/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
import QuartzCore
enum MKTimingFunction {
case Linear
case EaseIn
case EaseOut
case Custom(Float, Float, Float, Float)
var function : CAMediaTimingFunction {
switch self {
case .Linear:
return CAMediaTimingFunction(name: "linear")
case .EaseIn:
return CAMediaTimingFunction(name: "easeIn")
case .EaseOut:
return CAMediaTimingFunction(name: "easeOut")
case .Custom(let cpx1, let cpy1, let cpx2, let cpy2):
return CAMediaTimingFunction(controlPoints: cpx1, cpy1, cpx2, cpy2)
}
}
}
enum MKRippleLocation {
case Center
case Left
case Right
case TapLocation
}
class MKLayer {
private var superLayer: CALayer!
private let circleLayer = CALayer()
private let backgroundLayer = CALayer()
private let maskLayer = CAShapeLayer()
var rippleLocation: MKRippleLocation = .TapLocation {
didSet {
var origin: CGPoint?
switch rippleLocation {
case .Center:
origin = CGPoint(x: superLayer.bounds.width/2, y: superLayer.bounds.height/2)
case .Left:
origin = CGPoint(x: superLayer.bounds.width * 0.25, y: superLayer.bounds.height/2)
case .Right:
origin = CGPoint(x: superLayer.bounds.width * 0.75, y: superLayer.bounds.height/2)
default:
origin = nil
}
if let originPoint = origin {
setCircleLayerLocationAt(originPoint)
}
}
}
var circleGrowRatioMax: Float = 0.9 {
didSet {
if circleGrowRatioMax > 0 {
let superLayerWidth = CGRectGetWidth(superLayer.bounds)
let superLayerHeight = CGRectGetHeight(superLayer.bounds)
let circleSize = CGFloat(max(superLayerWidth, superLayerHeight)) * CGFloat(circleGrowRatioMax)
let circleCornerRadius = circleSize/2
circleLayer.cornerRadius = circleCornerRadius
setCircleLayerLocationAt(CGPoint(x: superLayerWidth/2, y: superLayerHeight/2))
}
}
}
init(superLayer: CALayer) {
self.superLayer = superLayer
let superLayerWidth = CGRectGetWidth(superLayer.bounds)
let superLayerHeight = CGRectGetHeight(superLayer.bounds)
// background layer
backgroundLayer.frame = superLayer.bounds
backgroundLayer.opacity = 0.0
superLayer.addSublayer(backgroundLayer)
// circlelayer
let circleSize = CGFloat(max(superLayerWidth, superLayerHeight)) * CGFloat(circleGrowRatioMax)
let circleCornerRadius = circleSize/2
circleLayer.opacity = 0.0
circleLayer.cornerRadius = circleCornerRadius
setCircleLayerLocationAt(CGPoint(x: superLayerWidth/2, y: superLayerHeight/2))
backgroundLayer.addSublayer(circleLayer)
// mask layer
setMaskLayerCornerRadius(superLayer.cornerRadius)
backgroundLayer.mask = maskLayer
}
func superLayerDidResize() {
CATransaction.begin()
CATransaction.setDisableActions(true)
backgroundLayer.frame = superLayer.bounds
setMaskLayerCornerRadius(superLayer.cornerRadius)
CATransaction.commit()
setCircleLayerLocationAt(CGPoint(x: superLayer.bounds.width/2, y: superLayer.bounds.height/2))
}
func enableOnlyCircleLayer() {
backgroundLayer.removeFromSuperlayer()
superLayer.addSublayer(circleLayer)
}
func setBackgroundLayerColor(color: UIColor) {
backgroundLayer.backgroundColor = color.CGColor
}
func setCircleLayerColor(color: UIColor) {
circleLayer.backgroundColor = color.CGColor
}
func didChangeTapLocation(location: CGPoint) {
if rippleLocation == .TapLocation {
self.setCircleLayerLocationAt(location)
}
}
func setMaskLayerCornerRadius(cornerRadius: CGFloat) {
maskLayer.path = UIBezierPath(roundedRect: backgroundLayer.bounds, cornerRadius: cornerRadius).CGPath
}
func enableMask(enable: Bool = true) {
backgroundLayer.mask = enable ? maskLayer : nil
}
func setBackgroundLayerCornerRadius(cornerRadius: CGFloat) {
backgroundLayer.cornerRadius = cornerRadius
}
private func setCircleLayerLocationAt(center: CGPoint) {
let bounds = superLayer.bounds
let width = CGRectGetWidth(bounds)
let height = CGRectGetHeight(bounds)
let subSize = CGFloat(max(width, height)) * CGFloat(circleGrowRatioMax)
let subX = center.x - subSize/2
let subY = center.y - subSize/2
// disable animation when changing layer frame
CATransaction.begin()
CATransaction.setDisableActions(true)
circleLayer.cornerRadius = subSize / 2
circleLayer.frame = CGRect(x: subX, y: subY, width: subSize, height: subSize)
CATransaction.commit()
}
// MARK - Animation
func animateScaleForCircleLayer(fromScale: Float, toScale: Float, timingFunction: MKTimingFunction, duration: CFTimeInterval) {
let circleLayerAnim = CABasicAnimation(keyPath: "transform.scale")
circleLayerAnim.fromValue = fromScale
circleLayerAnim.toValue = toScale
let opacityAnim = CABasicAnimation(keyPath: "opacity")
opacityAnim.fromValue = 1.0
opacityAnim.toValue = 0.0
let groupAnim = CAAnimationGroup()
groupAnim.duration = duration
groupAnim.timingFunction = timingFunction.function
groupAnim.removedOnCompletion = false
groupAnim.fillMode = kCAFillModeForwards
groupAnim.animations = [circleLayerAnim, opacityAnim]
circleLayer.addAnimation(groupAnim, forKey: nil)
}
func animateAlphaForBackgroundLayer(timingFunction: MKTimingFunction, duration: CFTimeInterval) {
let backgroundLayerAnim = CABasicAnimation(keyPath: "opacity")
backgroundLayerAnim.fromValue = 1.0
backgroundLayerAnim.toValue = 0.0
backgroundLayerAnim.duration = duration
backgroundLayerAnim.timingFunction = timingFunction.function
backgroundLayer.addAnimation(backgroundLayerAnim, forKey: nil)
}
func animateSuperLayerShadow(fromRadius: CGFloat, toRadius: CGFloat, fromOpacity: Float, toOpacity: Float, timingFunction: MKTimingFunction, duration: CFTimeInterval) {
animateShadowForLayer(superLayer, fromRadius: fromRadius, toRadius: toRadius, fromOpacity: fromOpacity, toOpacity: toOpacity, timingFunction: timingFunction, duration: duration)
}
func animateMaskLayerShadow() {
}
private func animateShadowForLayer(layer: CALayer, fromRadius: CGFloat, toRadius: CGFloat, fromOpacity: Float, toOpacity: Float, timingFunction: MKTimingFunction, duration: CFTimeInterval) {
let radiusAnimation = CABasicAnimation(keyPath: "shadowRadius")
radiusAnimation.fromValue = fromRadius
radiusAnimation.toValue = toRadius
let opacityAnimation = CABasicAnimation(keyPath: "shadowOpacity")
opacityAnimation.fromValue = fromOpacity
opacityAnimation.toValue = toOpacity
let groupAnimation = CAAnimationGroup()
groupAnimation.duration = duration
groupAnimation.timingFunction = timingFunction.function
groupAnimation.removedOnCompletion = false
groupAnimation.fillMode = kCAFillModeForwards
groupAnimation.animations = [radiusAnimation, opacityAnimation]
layer.addAnimation(groupAnimation, forKey: nil)
}
}
| mit | f996a83c0ec9fb6509a14ee6c743d247 | 36.154206 | 194 | 0.663564 | 5.671184 | false | false | false | false |
jimmy54/iRime | iRime/Keyboard/tasty-imitation-keyboard/Controller/KeyboardViewController.swift | 1 | 36852 | //
// KeyboardViewController.swift
// Keyboard
//
// Created by Alexei Baboulevitch on 6/9/14.
// Copyright (c) 2014 Alexei Baboulevitch ("Archagon"). All rights reserved.
//
import UIKit
import AudioToolbox
let height = getBannerHeight()
let metrics: [String:CGFloat] = [
"topBanner": height
]
func metric(_ name: String) -> CGFloat { return metrics[name]! }
// TODO: move this somewhere else and localize
let kAutoCapitalization = "kAutoCapitalization"
let kPeriodShortcut = "kPeriodShortcut"
let kKeyboardClicks = "kKeyboardClicks"
let kSmallLowercase = "kSmallLowercase"
class KeyboardViewController: UIInputViewController {
let backspaceDelay: TimeInterval = 0.5
let backspaceRepeat: TimeInterval = 0.07
var keyboard: Keyboard!
var forwardingView: ForwardingView!
var layout: KeyboardLayout?
var heightConstraint: NSLayoutConstraint?
var bannerView: ExtraView?
var settingsView: ExtraView?
var currentMode: Int {
didSet {
if oldValue != currentMode {
setMode(currentMode)
}
}
}
var backspaceActive: Bool {
get {
return (backspaceDelayTimer != nil) || (backspaceRepeatTimer != nil)
}
}
var backspaceDelayTimer: Timer?
var backspaceRepeatTimer: Timer?
enum AutoPeriodState {
case noSpace
case firstSpace
}
var autoPeriodState: AutoPeriodState = .noSpace
var lastCharCountInBeforeContext: Int = 0
var shiftState: ShiftState {
didSet {
switch shiftState {
case .disabled:
self.updateKeyCaps(false)
case .enabled:
self.updateKeyCaps(true)
case .locked:
self.updateKeyCaps(true)
}
}
}
// state tracking during shift tap
var shiftWasMultitapped: Bool = false
var shiftStartingState: ShiftState?
var keyboardHeight: CGFloat {
get {
if let constraint = self.heightConstraint {
return constraint.constant
}
else {
return 0
}
}
set {
self.setHeight(newValue)
}
}
// TODO: why does the app crash if this isn't here?
convenience init() {
self.init(nibName: nil, bundle: nil)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
UserDefaults.standard.register(defaults: [
kAutoCapitalization: false,
kPeriodShortcut: false,
kKeyboardClicks: false,
kSmallLowercase: false
])
self.keyboard = defaultKeyboard()
self.shiftState = .disabled
self.currentMode = 0
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.forwardingView = ForwardingView(frame: CGRect.zero)
// self.forwardingView.backgroundColor = UIColor(red: 214.0 / 255.0, green:216.0 / 255.0, blue:220.0 / 255.0, alpha:1.0)
self.view.addSubview(self.forwardingView)
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardViewController.defaultsChanged(_:)), name: UserDefaults.didChangeNotification, object: nil)
}
required init?(coder: NSCoder) {
fatalError("NSCoding not supported")
}
deinit {
backspaceDelayTimer?.invalidate()
backspaceRepeatTimer?.invalidate()
NotificationCenter.default.removeObserver(self)
}
func defaultsChanged(_ notification: Notification) {
//let defaults = notification.object as? NSUserDefaults
self.updateKeyCaps(self.shiftState.uppercase())
}
// without this here kludge, the height constraint for the keyboard does not work for some reason
var kludge: UIView?
func setupKludge() {
if self.kludge == nil {
let kludge = UIView()
self.view.addSubview(kludge)
kludge.translatesAutoresizingMaskIntoConstraints = false
kludge.isHidden = true
let a = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 0)
let b = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 0)
let c = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)
let d = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)
self.view.addConstraints([a, b, c, d])
self.kludge = kludge
}
}
/*
BUG NOTE
For some strange reason, a layout pass of the entire keyboard is triggered
whenever a popup shows up, if one of the following is done:
a) The forwarding view uses an autoresizing mask.
b) The forwarding view has constraints set anywhere other than init.
On the other hand, setting (non-autoresizing) constraints or just setting the
frame in layoutSubviews works perfectly fine.
I don't really know what to make of this. Am I doing Autolayout wrong, is it
a bug, or is it expected behavior? Perhaps this has to do with the fact that
the view's frame is only ever explicitly modified when set directly in layoutSubviews,
and not implicitly modified by various Autolayout constraints
(even though it should really not be changing).
*/
var constraintsAdded: Bool = false
func setupLayout() {
if !constraintsAdded {
self.layout = type(of: self).layoutClass.init(model: self.keyboard, superview: self.forwardingView, layoutConstants: type(of: self).layoutConstants, globalColors: type(of: self).globalColors, darkMode: self.darkMode(), solidColorMode: self.solidColorMode())
self.layout?.initialize()
self.setMode(0)
self.setupKludge()
self.updateKeyCaps(self.shiftState.uppercase())
var capsWasSet = self.setCapsIfNeeded()
self.updateAppearances(self.darkMode())
self.addInputTraitsObservers()
self.constraintsAdded = true
}
}
// only available after frame becomes non-zero
func darkMode() -> Bool {
let darkMode = { () -> Bool in
let proxy = self.textDocumentProxy
return proxy.keyboardAppearance == UIKeyboardAppearance.dark
}()
return darkMode
}
func solidColorMode() -> Bool {
return UIAccessibilityIsReduceTransparencyEnabled()
}
var lastLayoutBounds: CGRect?
override func viewDidLayoutSubviews() {
if view.bounds == CGRect.zero {
return
}
self.setupLayout()
let orientationSavvyBounds = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.heightForOrientation(self.interfaceOrientation, withTopBanner: false))
if (lastLayoutBounds != nil && lastLayoutBounds == orientationSavvyBounds) {
// do nothing
}
else {
let uppercase = self.shiftState.uppercase()
let characterUppercase = (UserDefaults.standard.bool(forKey: kSmallLowercase) ? uppercase : true)
self.forwardingView.frame = orientationSavvyBounds
self.layout?.layoutKeys(self.currentMode, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: self.shiftState)
self.lastLayoutBounds = orientationSavvyBounds
self.setupKeys()
}
self.bannerView?.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: metric("topBanner"))
let newOrigin = CGPoint(x: 0, y: self.view.bounds.height - self.forwardingView.bounds.height)
self.forwardingView.frame.origin = newOrigin
}
override func loadView() {
super.loadView()
if let aBanner = self.createBanner() {
aBanner.isHidden = true
self.view.insertSubview(aBanner, belowSubview: self.forwardingView)
self.bannerView = aBanner
}
}
override func viewWillAppear(_ animated: Bool) {
self.bannerView?.isHidden = false
self.keyboardHeight = self.heightForOrientation(self.interfaceOrientation, withTopBanner: true)
self.updateReturnType()
}
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
self.forwardingView.resetTrackedViews()
self.shiftStartingState = nil
self.shiftWasMultitapped = false
// optimization: ensures smooth animation
if let keyPool = self.layout?.keyPool {
for view in keyPool {
view.shouldRasterize = true
}
}
self.keyboardHeight = self.heightForOrientation(toInterfaceOrientation, withTopBanner: true)
}
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
// optimization: ensures quick mode and shift transitions
if let keyPool = self.layout?.keyPool {
for view in keyPool {
view.shouldRasterize = false
}
}
}
func heightForOrientation(_ orientation: UIInterfaceOrientation, withTopBanner: Bool) -> CGFloat {
let isPad = UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad
//TODO: hardcoded stuff
let actualScreenWidth = (UIScreen.main.nativeBounds.size.width / UIScreen.main.nativeScale)
let canonicalPortraitHeight = (isPad ? CGFloat(264) : CGFloat(orientation.isPortrait && actualScreenWidth >= 400 ? 226 : 216))
let canonicalLandscapeHeight = (isPad ? CGFloat(352) : CGFloat(162))
let topBannerHeight = (withTopBanner ? metric("topBanner") : 0)
return CGFloat(orientation.isPortrait ? canonicalPortraitHeight + topBannerHeight : canonicalLandscapeHeight + topBannerHeight)
}
/*
BUG NOTE
None of the UIContentContainer methods are called for this controller.
*/
//override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
// super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
//}
func setupKeys() {
if self.layout == nil {
return
}
for page in keyboard.pages {
for rowKeys in page.rows { // TODO: quick hack
for key in rowKeys {
if let keyView = self.layout?.viewForKey(key) {
keyView.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
switch key.type {
case Key.KeyType.keyboardChange:
keyView.addTarget(self, action: "advanceTapped:", for: .touchUpInside)
case Key.KeyType.backspace:
// let cancelEvents: UIControlEvents = [UIControlEvents.TouchUpInside, UIControlEvents.TouchUpInside, UIControlEvents.TouchDragExit, UIControlEvents.TouchUpOutside, UIControlEvents.TouchCancel, UIControlEvents.TouchDragOutside]
let cancelEvents: UIControlEvents = [UIControlEvents.touchUpInside,UIControlEvents.touchCancel, UIControlEvents.touchDragExit, UIControlEvents.touchDragEnter]
keyView.addTarget(self, action: "backspaceDown:", for: .touchDown)
keyView.addTarget(self, action: "backspaceUp:", for: cancelEvents)
case Key.KeyType.shift:
keyView.addTarget(self, action: Selector("shiftDown:"), for: .touchDown)
keyView.addTarget(self, action: Selector("shiftUp:"), for: .touchUpInside)
keyView.addTarget(self, action: Selector("shiftDoubleTapped:"), for: .touchDownRepeat)
case Key.KeyType.modeChange:
keyView.addTarget(self, action: Selector("modeChangeTapped:"), for: .touchDown)
case Key.KeyType.settings:
keyView.addTarget(self, action: Selector("toggleSettings"), for: .touchUpInside)
case Key.KeyType.space:
keyView.addTarget(self, action: Selector("spaceDragInside:withEvent:"), for: .touchDragInside)
keyView.addTarget(self, action: Selector("spaceUpInside:withEvent:"), for: .touchUpInside)
keyView.addTarget(self, action: Selector("spaceDown:withEvent:"), for: .touchDown)
default:
break
}
if key.isCharacter {
if UIDevice.current.userInterfaceIdiom != UIUserInterfaceIdiom.pad {
keyView.addTarget(self, action: Selector("showPopup:"), for: [.touchDown, .touchDragInside, .touchDragEnter])
keyView.addTarget(keyView, action: Selector("hidePopup"), for: [.touchDragExit, .touchCancel])
keyView.addTarget(self, action: Selector("hidePopupDelay:"), for: [.touchUpInside, .touchUpOutside, .touchDragOutside])
}
}
if key.hasOutput {
keyView.addTarget(self, action: "keyPressedHelper:", for: .touchUpInside)
}
if key.type != Key.KeyType.shift && key.type != Key.KeyType.modeChange {
keyView.addTarget(self, action: Selector("highlightKey:"), for: [.touchDown, .touchDragInside, .touchDragEnter])
keyView.addTarget(self, action: Selector("unHighlightKey:"), for: [.touchUpInside, .touchUpOutside, .touchDragOutside, .touchDragExit, .touchCancel])
}
keyView.addTarget(self, action: Selector("playKeySound"), for: .touchDown)
}
}
}
}
}
/////////////////
// POPUP DELAY //
/////////////////
var keyWithDelayedPopup: KeyboardKey?
var popupDelayTimer: Timer?
func showPopup(_ sender: KeyboardKey) {
if sender == self.keyWithDelayedPopup {
self.popupDelayTimer?.invalidate()
}
sender.showPopup()
}
func hidePopupDelay(_ sender: KeyboardKey) {
self.popupDelayTimer?.invalidate()
if sender != self.keyWithDelayedPopup {
self.keyWithDelayedPopup?.hidePopup()
self.keyWithDelayedPopup = sender
}
if sender.popup != nil {
self.popupDelayTimer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(KeyboardViewController.hidePopupCallback), userInfo: nil, repeats: false)
}
}
func hidePopupCallback() {
self.keyWithDelayedPopup?.hidePopup()
self.keyWithDelayedPopup = nil
self.popupDelayTimer = nil
}
/////////////////////
// POPUP DELAY END //
/////////////////////
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated
}
// TODO: this is currently not working as intended; only called when selection changed -- iOS bug
override func textDidChange(_ textInput: UITextInput?) {
self.contextChanged()
}
func contextChanged() {
self.setCapsIfNeeded()
self.autoPeriodState = .noSpace
}
func setHeight(_ height: CGFloat) {
if self.heightConstraint == nil {
self.heightConstraint = NSLayoutConstraint(
item:self.view,
attribute:NSLayoutAttribute.height,
relatedBy:NSLayoutRelation.equal,
toItem:nil,
attribute:NSLayoutAttribute.notAnAttribute,
multiplier:0,
constant:height)
self.heightConstraint!.priority = 900
self.view.addConstraint(self.heightConstraint!) // TODO: what if view already has constraint added?
}
else {
self.heightConstraint?.constant = height
}
}
func updateAppearances(_ appearanceIsDark: Bool) {
self.layout?.solidColorMode = self.solidColorMode()
self.layout?.darkMode = appearanceIsDark
self.layout?.updateKeyAppearance()
self.bannerView?.darkMode = appearanceIsDark
self.settingsView?.darkMode = appearanceIsDark
}
func highlightKey(_ sender: KeyboardKey) {
sender.isHighlighted = true
}
func unHighlightKey(_ sender: KeyboardKey) {
sender.isHighlighted = false
}
func keyPressedHelper(_ sender: KeyboardKey) {
if let model = self.layout?.keyForView(sender) {
self.keyPressed(model)
// auto exit from special char subkeyboard
// if model.type == Key.KeyType.Space || model.type == Key.KeyType.Return {
// self.currentMode = 0
// }
// elseif model.lowercaseOutput == "'" {
// self.currentMode = 0
// }
// else if model.type == Key.KeyType.Character {
// self.currentMode = 0
// }
// auto period on double space
// TODO: timeout
self.handleAutoPeriod(model)
// TODO: reset context
}
self.setCapsIfNeeded()
}
func handleAutoPeriod(_ key: Key) {
if !UserDefaults.standard.bool(forKey: kPeriodShortcut) {
return
}
if self.autoPeriodState == .firstSpace {
if key.type != Key.KeyType.space {
self.autoPeriodState = .noSpace
return
}
let charactersAreInCorrectState = { () -> Bool in
let previousContext = self.textDocumentProxy.documentContextBeforeInput
if previousContext == nil || (previousContext!).characters.count < 3 {
return false
}
var index = previousContext!.endIndex
index = (previousContext?.index(before: index))! //Collection.index(before: index)
if previousContext![index] != " " {
return false
}
index = (previousContext?.index(before: index))! //Collection.index(before: index)
if previousContext![index] != " " {
return false
}
index = (previousContext?.index(before: index))! //<#T##Collection corresponding to `index`##Collection#>.index(before: index)
let char = previousContext![index]
if self.characterIsWhitespace(char) || self.characterIsPunctuation(char) || char == "," {
return false
}
return true
}()
if charactersAreInCorrectState {
self.textDocumentProxy.deleteBackward()
self.textDocumentProxy.deleteBackward()
self.textDocumentProxy.insertText(".")
self.textDocumentProxy.insertText(" ")
}
self.autoPeriodState = .noSpace
}
else {
if key.type == Key.KeyType.space {
self.autoPeriodState = .firstSpace
}
}
}
func cancelBackspaceTimers() {
self.backspaceDelayTimer?.invalidate()
self.backspaceRepeatTimer?.invalidate()
self.backspaceDelayTimer = nil
self.backspaceRepeatTimer = nil
}
func backspaceDown(_ sender: KeyboardKey) {
self.cancelBackspaceTimers()
// self.textDocumentProxy.deleteBackward()
self.setCapsIfNeeded()
// trigger for subsequent deletes
self.backspaceDelayTimer = Timer.scheduledTimer(timeInterval: backspaceDelay - backspaceRepeat, target: self, selector: #selector(KeyboardViewController.backspaceDelayCallback), userInfo: nil, repeats: false)
}
func backspaceUp(_ sender: KeyboardKey) {
self.cancelBackspaceTimers()
self.keyPressedHelper(sender)
}
func backspaceDelayCallback() {
self.backspaceDelayTimer = nil
self.backspaceRepeatTimer = Timer.scheduledTimer(timeInterval: backspaceRepeat, target: self, selector: #selector(KeyboardViewController.backspaceRepeatCallback), userInfo: nil, repeats: true)
}
func backspaceRepeatCallback() {
self.playKeySound()
self.textDocumentProxy.deleteBackward()
self.setCapsIfNeeded()
}
func shiftDown(_ sender: KeyboardKey) {
self.shiftStartingState = self.shiftState
if let shiftStartingState = self.shiftStartingState {
if shiftStartingState.uppercase() {
// handled by shiftUp
return
}
else {
switch self.shiftState {
case .disabled:
self.shiftState = .enabled
case .enabled:
self.shiftState = .disabled
case .locked:
self.shiftState = .disabled
}
(sender.shape as? ShiftShape)?.withLock = false
}
}
}
func shiftUp(_ sender: KeyboardKey) {
if self.shiftWasMultitapped {
// do nothing
}
else {
if let shiftStartingState = self.shiftStartingState {
if !shiftStartingState.uppercase() {
// handled by shiftDown
}
else {
switch self.shiftState {
case .disabled:
self.shiftState = .enabled
case .enabled:
self.shiftState = .disabled
case .locked:
self.shiftState = .disabled
}
(sender.shape as? ShiftShape)?.withLock = false
}
}
}
self.shiftStartingState = nil
self.shiftWasMultitapped = false
}
func shiftDoubleTapped(_ sender: KeyboardKey) {
self.shiftWasMultitapped = true
switch self.shiftState {
case .disabled:
self.shiftState = .locked
case .enabled:
self.shiftState = .locked
case .locked:
self.shiftState = .disabled
}
}
func updateKeyCaps(_ uppercase: Bool) {
//是否自动大小字母
let characterUppercase = (UserDefaults.standard.bool(forKey: kSmallLowercase) ? uppercase : true)
//更新LAYOUT的布局
self.layout?.updateKeyCaps(false, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: self.shiftState)
}
func modeChangeTapped(_ sender: KeyboardKey) {
if let toMode = self.layout?.viewToModel[sender]?.toMode {
self.currentMode = toMode
}
}
func setMode(_ mode: Int) {
self.forwardingView.resetTrackedViews()
self.shiftStartingState = nil
self.shiftWasMultitapped = false
let uppercase = self.shiftState.uppercase()
let characterUppercase = (UserDefaults.standard.bool(forKey: kSmallLowercase) ? uppercase : true)
self.layout?.layoutKeys(mode, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: self.shiftState)
self.setupKeys()
}
func advanceTapped(_ sender: KeyboardKey) {
self.forwardingView.resetTrackedViews()
self.shiftStartingState = nil
self.shiftWasMultitapped = false
self.advanceToNextInputMode()
}
@IBAction func toggleSettings() {
// lazy load settings
if self.settingsView == nil {
if let aSettings = self.createSettings() {
aSettings.darkMode = self.darkMode()
aSettings.isHidden = true
self.view.addSubview(aSettings)
self.settingsView = aSettings
aSettings.translatesAutoresizingMaskIntoConstraints = false
let widthConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.width, multiplier: 1, constant: 0)
let heightConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.height, multiplier: 1, constant: 0)
let centerXConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
let centerYConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)
self.view.addConstraint(widthConstraint)
self.view.addConstraint(heightConstraint)
self.view.addConstraint(centerXConstraint)
self.view.addConstraint(centerYConstraint)
}
}
if let settings = self.settingsView {
let hidden = settings.isHidden
settings.isHidden = !hidden
self.forwardingView.isHidden = hidden
self.forwardingView.isUserInteractionEnabled = !hidden
self.bannerView?.isHidden = hidden
}
}
var spaceDragPoint:CGPoint = CGPoint.zero
var spaceDragPointCount:NSInteger = 0
var spaceDragIsMoving: Bool = false
func spaceUpInside(_ sender: KeyboardKey, withEvent event:UIEvent) {
spaceDragPoint = CGPoint(x: 0, y: 0)
}
func spaceDown(_ sender: KeyboardKey, withEvent event:UIEvent) {
let touch = event.allTouches?.first
let p = touch?.location(in: sender)
spaceDragPoint = p!
}
func spaceDragInside(_ sender: KeyboardKey, withEvent event:UIEvent) {
let touch = event.allTouches?.first
let p = touch?.location(in: sender)
let off = (p!.x) - (spaceDragPoint.x)
guard abs(off) > 7 else {
return;
}
spaceDragIsMoving = true
print("x:%d y:%d off:%d", p?.x, p?.y, off)
if off > 0 {
self.textDocumentProxy.adjustTextPosition(byCharacterOffset: 1)
}else{
self.textDocumentProxy.adjustTextPosition(byCharacterOffset: -1)
}
spaceDragPoint = p!
}
func spaceTap(_ tap:UITapGestureRecognizer) {
}
func spaceSwip(_ swip: UISwipeGestureRecognizer) {
}
func setCapsIfNeeded() -> Bool {
if self.shouldAutoCapitalize() {
switch self.shiftState {
case .disabled:
self.shiftState = .enabled
case .enabled:
self.shiftState = .enabled
case .locked:
self.shiftState = .locked
}
return true
}
else {
switch self.shiftState {
case .disabled:
self.shiftState = .disabled
case .enabled:
self.shiftState = .disabled
case .locked:
self.shiftState = .locked
}
return false
}
}
func characterIsPunctuation(_ character: Character) -> Bool {
return (character == ".") || (character == "!") || (character == "?")
}
func characterIsNewline(_ character: Character) -> Bool {
return (character == "\n") || (character == "\r")
}
func characterIsWhitespace(_ character: Character) -> Bool {
// there are others, but who cares
return (character == " ") || (character == "\n") || (character == "\r") || (character == "\t")
}
func stringIsWhitespace(_ string: String?) -> Bool {
if string != nil {
for char in (string!).characters {
if !characterIsWhitespace(char) {
return false
}
}
}
return true
}
func shouldAutoCapitalize() -> Bool {
if !UserDefaults.standard.bool(forKey: kAutoCapitalization) {
return false
}
let traits = self.textDocumentProxy
if let autocapitalization = traits.autocapitalizationType {
let documentProxy = self.textDocumentProxy
//var beforeContext = documentProxy.documentContextBeforeInput
switch autocapitalization {
case .none:
return false
case .words:
if let beforeContext = documentProxy.documentContextBeforeInput {
let previousCharacter = beforeContext[beforeContext.characters.index(before: beforeContext.endIndex)]
return self.characterIsWhitespace(previousCharacter)
}
else {
return true
}
case .sentences:
if let beforeContext = documentProxy.documentContextBeforeInput {
let offset = min(3, beforeContext.characters.count)
var index = beforeContext.endIndex
for i in 0 ..< offset
{
index = (beforeContext.index(before: index)) //Collection.index(before: index)
let char = beforeContext[index]
if characterIsPunctuation(char) {
if i == 0 {
return false //not enough spaces after punctuation
}
else {
return true //punctuation with at least one space after it
}
}
else {
if !characterIsWhitespace(char) {
return false //hit a foreign character before getting to 3 spaces
}
else if characterIsNewline(char) {
return true //hit start of line
}
}
}
return true //either got 3 spaces or hit start of line
}
else {
return true
}
case .allCharacters:
return true
}
}
else {
return false
}
}
// this only works if full access is enabled
func playKeySound() {
if !UserDefaults.standard.bool(forKey: kKeyboardClicks) {
return
}
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async(execute: {
AudioServicesPlaySystemSound(1104)
})
}
//////////////////////////////////////
// MOST COMMONLY EXTENDABLE METHODS //
//////////////////////////////////////
class var layoutClass: KeyboardLayout.Type { get { return KeyboardLayout.self }}
class var layoutConstants: LayoutConstants.Type { get { return LayoutConstants.self }}
class var globalColors: GlobalColors.Type { get { return GlobalColors.self }}
func keyPressed(_ key: Key) {
self.textDocumentProxy.insertText(key.outputForCase(self.shiftState.uppercase()))
}
// a banner that sits in the empty space on top of the keyboard
func createBanner() -> ExtraView? {
// note that dark mode is not yet valid here, so we just put false for clarity
//return ExtraView(globalColors: self.dynamicType.globalColors, darkMode: false, solidColorMode: self.solidColorMode())
return nil
}
// a settings view that replaces the keyboard when the settings button is pressed
func createSettings() -> ExtraView? {
// note that dark mode is not yet valid here, so we just put false for clarity
let settingsView = DefaultSettings(globalColors: type(of: self).globalColors, darkMode: false, solidColorMode: self.solidColorMode())
settingsView.backButton?.addTarget(self, action: #selector(KeyboardViewController.toggleSettings), for: UIControlEvents.touchUpInside)
return settingsView
}
func getReturnKeyTitleString() -> String {
// case Default
// case Go
// case Google
// case Join
// case Next
// case Route
// case Search
// case Send
// case Yahoo
// case Done
// case EmergencyCall
// @available(iOS 9.0, *)
// case Continue
var returnString:String = "返回"
if self.textDocumentProxy.returnKeyType == UIReturnKeyType.go {
returnString = "Go"
}else if self.textDocumentProxy.returnKeyType == UIReturnKeyType.google {
returnString = "Google"
}else if self.textDocumentProxy.returnKeyType == UIReturnKeyType.join {
returnString = "加入"
}else if self.textDocumentProxy.returnKeyType == UIReturnKeyType.next {
returnString = "下一步"
}else if self.textDocumentProxy.returnKeyType == UIReturnKeyType.route {
returnString = "Route"
}else if self.textDocumentProxy.returnKeyType == UIReturnKeyType.search {
returnString = "搜索"
}else if self.textDocumentProxy.returnKeyType == UIReturnKeyType.send {
returnString = "发送"
}else if self.textDocumentProxy.returnKeyType == UIReturnKeyType.yahoo {
returnString = "Yahoo"
}else if self.textDocumentProxy.returnKeyType == UIReturnKeyType.done {
returnString = "完成"
}else if self.textDocumentProxy.returnKeyType == UIReturnKeyType.emergencyCall {
returnString = "EmergencyCall"
}else{
if #available(iOSApplicationExtension 9.0, *) {
if (self.textDocumentProxy.returnKeyType == UIReturnKeyType.continue) {
returnString = "继续"
}
}
}
return returnString
}
func updateReturnType() {
//find the return key
for page in keyboard.pages {
for row in page.rows {
for k in row {
if k.type == .return {
k.uppercaseKeyCap = self.getReturnKeyTitleString()
k.uppercaseOutput = "\n"
k.lowercaseOutput = "\n"
}
}
}
}
}
}
| gpl-3.0 | 37768475f9f17868956b4a8961547e64 | 36.546939 | 269 | 0.567725 | 5.916707 | false | false | false | false |
DroidsOnRoids/UIStackView-in-Swift-Part-1 | UIStackViewDemo-1/UIStackViewDemo-1/FunnyAnimalsTableViewController.swift | 1 | 2279 | //
// FunnyAnimalsTableViewController.swift
// UIStackViewDemo-1
//
// Created by Michal Pyrka on 26/09/15.
// Copyright © 2015 Droids On Roids. All rights reserved.
//
import UIKit
class FunnyAnimalsTableViewController: UITableViewController {
var animalsCollection: [FunnyAnimalsCollection] = [FunnyDogsCollection(), FunnyCatsCollection(), FunnyLlamasCollection()]
@IBAction func addNewCollectionTapped(sender: UIBarButtonItem) {
var allCollections: [FunnyAnimalsCollection] = [FunnyDogsCollection(), FunnyCatsCollection(), FunnyLlamasCollection()]
var newCollection = allCollections[random() % allCollections.count]
newCollection.isNew = true
animalsCollection.append(newCollection)
self.tableView.reloadData()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
@IBAction func showMoreTapped(sender: UIButton) {
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return animalsCollection.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("FunnyAnimalCollectionCell", forIndexPath: indexPath) as! AnimalsCollectionCell
let collection = animalsCollection[indexPath.row]
cell.thumbnailImageView.image = collection.thumbnailPhoto
cell.nameLabel.text = collection.name
cell.isNewLabel.hidden = !collection.isNew
cell.descriptionLabel.text = collection.collectionDescription
return cell
}
}
extension UITableView {
func cellWithSubview(cellSubview: UIView) -> AnimalsCollectionCell? {
let cellFrame = convertRect(cellSubview.bounds, fromView: cellSubview)
let cellCenter = CGPoint(x: CGRectGetMidX(cellFrame), y: CGRectGetMidY(cellFrame))
if let indexPath = indexPathForRowAtPoint(cellCenter), let cell = self.cellForRowAtIndexPath(indexPath) as? AnimalsCollectionCell {
return cell
}
return nil
}
}
| mit | 03e616927822f25ecf2cd8cac33e409a | 37.610169 | 142 | 0.723003 | 5.248848 | false | false | false | false |
yoonapps/QPXExpressWrapper | QPXExpressWrapper/Classes/TripOptionSliceSegmentFlight.swift | 1 | 643 | //
// Flight.swift
// Flights
//
// Created by Kyle Yoon on 2/14/16.
// Copyright © 2016 Kyle Yoon. All rights reserved.
//
import Foundation
import Gloss
public struct TripOptionSliceSegmentFlight: Decodable {
public let carrier: String?
public let number: String?
public init?(json: JSON) {
self.number = "number" <~~ json
self.carrier = "carrier" <~~ json
}
}
extension TripOptionSliceSegmentFlight: Equatable {}
public func ==(lhs: TripOptionSliceSegmentFlight, rhs: TripOptionSliceSegmentFlight) -> Bool {
return lhs.carrier == rhs.carrier &&
lhs.number == rhs.number
}
| mit | 1b7de59f33c7109234f4cef38330c775 | 21.137931 | 94 | 0.661994 | 3.821429 | false | false | false | false |
efeconirulez/be-focus | be #focused/StatsVC.swift | 1 | 3714 | //
// StatsVC.swift
// be #focused
//
// Created by Efe Helvaci on 29.01.2017.
// Copyright © 2017 efehelvaci. All rights reserved.
//
import UIKit
import KDCircularProgress
class StatsVC: UIViewController {
@IBOutlet var treePointsLabel: UILabel!
@IBOutlet var liveTreeLabel: UILabel!
@IBOutlet var deadTreeLabel: UILabel!
@IBOutlet var circularView: KDCircularProgress!
@IBOutlet var percentageLabel: UILabel!
@IBOutlet var resultLabel: UILabel!
let status0 = "Let's start focusing and grow your first tree!"
let status10 = "You should try harder. Live and let live!"
let status20 = "It's getting better! Focus on your work more!"
let status40 = "Not bad but it could be better! Work harder!"
let status50 = "A little bit of focusing and you will grow more trees than killing"
let status70 = "Yay! You are getting better and better!"
let status90 = "Fantastic! Keep up the good work!"
let status100 = "You have some serious focusing skills! Excellent!"
var mainPage : MainPageVC!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let treeWinPoints = UserDefaults.standard.integer(forKey: "treeWinPoints")
let treeLosePoints = UserDefaults.standard.integer(forKey: "treeLosePoints")
liveTreeLabel.text = "\(treeWinPoints)"
deadTreeLabel.text = "\(treeLosePoints)"
treePointsLabel.text = "\(mainPage.score) Tree Points!"
let totalPoints = Double(treeWinPoints + treeLosePoints)
if totalPoints != 0 {
let percentage = Double(treeWinPoints) / totalPoints
circularView.angle = percentage * 360
percentageLabel.text = "%\(Int(percentage*100))"
} else {
circularView.angle = 0
percentageLabel.text = "%0"
}
if totalPoints == 0 {
resultLabel.text = status0
} else {
switch (Double(treeWinPoints) / totalPoints) * 100 {
case 0...10:
resultLabel.text = status10
break
case 11...20:
resultLabel.text = status20
break
case 21...40:
resultLabel.text = status40
break
case 41...50:
resultLabel.text = status50
break
case 51...70:
resultLabel.text = status70
break
case 71...90:
resultLabel.text = status90
break
case 91...100:
resultLabel.text = status100
break
default:
resultLabel.text = "Live and let live!"
break
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func scoreboardButtonClicked(_ sender: Any) {
mainPage.scoreboardCheck(sender: self)
}
@IBAction func coolButtonClicked(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
/*
// 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 | 8d12980374c264481e8d64877e27e0d6 | 31.570175 | 106 | 0.594129 | 4.977212 | false | false | false | false |
khoogheem/GenesisKit | Shared/AutoComplete.swift | 1 | 2234 | //
// AutoComplete.swift
// GenesisKit
//
// Created by Kevin A. Hoogheem on 11/8/14.
// Copyright (c) 2014 Kevin A. Hoogheem. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
Method to take an array of Strings and provide an autocomplete array of strings
*/
@objc public class AutoComplete {
private lazy var candidates = [String]()
/**
Creates a AutoComplete Objct with a given array of Strings
:param: candidates An Array of Strings
*/
public init (candidates: [String]) {
self.candidates = candidates
sort(&self.candidates)
}
/**
Provides an Array of Suggested Strings from the given string.
Usage: Array of ["Bob", "Bill", "Frank"] - root passed in is B will return ["Bob", "Bill"]
:param: root The string you are evaluating
:returns: Array of Strings of the suggested candidates
*/
public func getSuggestions(# rootString:String) -> [String] {
if count(rootString) == 0 {
return candidates
}
let startPredicate = NSPredicate(format: "SELF BEGINSWITH[c] %@", rootString)
let filteredArray = candidates.filter { startPredicate.evaluateWithObject($0) };
return filteredArray
}
} | mit | b5c497303edfaf3f798294991892cfc3 | 33.384615 | 92 | 0.726947 | 4.144712 | false | false | false | false |
milseman/swift | test/stdlib/StringDiagnostics.swift | 7 | 6529 | // RUN: %target-typecheck-verify-swift
// XFAIL: linux
import Foundation
// Common pitfall: trying to subscript a string with integers.
func testIntSubscripting(s: String, i: Int) {
// FIXME swift-3-indexing-model: test new overloads of ..<, ...
_ = s[i] // expected-error{{'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion}}
_ = s[17] // expected-error{{'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion}}
_ = s[i...i] // expected-error{{subscript' is unavailable: cannot subscript String with a CountableClosedRange<Int>, see the documentation comment for discussion}}
_ = s[17..<20] // expected-error{{subscript' is unavailable: cannot subscript String with a CountableRange<Int>, see the documentation comment for discussion}}
_ = s[17...20] // expected-error{{subscript' is unavailable: cannot subscript String with a CountableClosedRange<Int>, see the documentation comment for discussion}}
_ = s[Range(i...i)] // expected-error{{subscript' is unavailable: cannot subscript String with a Range<Int>, see the documentation comment for discussion}}
_ = s[Range(17..<20)] // expected-error{{subscript' is unavailable: cannot subscript String with a Range<Int>, see the documentation comment for discussion}}
_ = s[Range(17...20)] // expected-error{{subscript' is unavailable: cannot subscript String with a Range<Int>, see the documentation comment for discussion}}
_ = s[CountableRange(i...i)] // expected-error{{subscript' is unavailable: cannot subscript String with a CountableRange<Int>, see the documentation comment for discussion}}
_ = s[CountableRange(17..<20)] // expected-error{{subscript' is unavailable: cannot subscript String with a CountableRange<Int>, see the documentation comment for discussion}}
_ = s[CountableRange(17...20)] // expected-error{{subscript' is unavailable: cannot subscript String with a CountableRange<Int>, see the documentation comment for discussion}}
_ = s[ClosedRange(i...i)] // expected-error{{subscript' is unavailable: cannot subscript String with a ClosedRange<Int>, see the documentation comment for discussion}}
_ = s[ClosedRange(17..<20)] // expected-error{{subscript' is unavailable: cannot subscript String with a ClosedRange<Int>, see the documentation comment for discussion}}
_ = s[ClosedRange(17...20)] // expected-error{{subscript' is unavailable: cannot subscript String with a ClosedRange<Int>, see the documentation comment for discussion}}
_ = s[CountableClosedRange(i...i)] // expected-error{{subscript' is unavailable: cannot subscript String with a CountableClosedRange<Int>, see the documentation comment for discussion}}
_ = s[CountableClosedRange(17..<20)] // expected-error{{subscript' is unavailable: cannot subscript String with a CountableClosedRange<Int>, see the documentation comment for discussion}}
_ = s[CountableClosedRange(17...20)] // expected-error{{subscript' is unavailable: cannot subscript String with a CountableClosedRange<Int>, see the documentation comment for discussion}}
}
func testNonAmbiguousStringComparisons() {
let s1 = "a"
let s2 = "b"
var x = false // expected-warning {{variable 'x' was written to, but never read}}
x = s1 > s2
x = s1 as String > s2
}
func testAmbiguousStringComparisons(s: String) {
let nsString = s as NSString
let a1 = s as NSString == nsString
let a2 = s as NSString != nsString
let a3 = s < nsString // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{24-24= as String}}
let a4 = s <= nsString // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{25-25= as String}}
let a5 = s >= nsString // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{25-25= as String}}
let a6 = s > nsString // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{24-24= as String}}
// now the other way
let a7 = nsString == s as NSString
let a8 = nsString != s as NSString
let a9 = nsString < s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{20-20= as String}}
let a10 = nsString <= s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{21-21= as String}}
let a11 = nsString >= s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{21-21= as String}}
let a12 = nsString > s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{21-21= as String}}
}
func testStringDeprecation(hello: String) {
let hello2 = hello
.addingPercentEscapes(using: .utf8) // expected-warning{{'addingPercentEscapes(using:)' is deprecated}}
_ = hello2?
.replacingPercentEscapes(using: .utf8) // expected-warning{{'replacingPercentEscapes(using:)' is deprecated}}
}
// Positive and negative tests for String collection types. Testing the complete
// set of conformance just in case protocol hierarchy changes.
func acceptsCollection<C: Collection>(_: C) {}
func acceptsBidirectionalCollection<C: BidirectionalCollection>(_: C) {}
func acceptsRandomAccessCollection<C: RandomAccessCollection>(_: C) {}
func testStringCollectionTypes(s: String) {
acceptsCollection(s.utf8)
acceptsBidirectionalCollection(s.utf8)
acceptsRandomAccessCollection(s.utf8) // expected-error{{argument type 'String.UTF8View' does not conform to expected type 'RandomAccessCollection'}}
acceptsCollection(s.utf16)
acceptsBidirectionalCollection(s.utf16)
acceptsRandomAccessCollection(s.utf16) // expected-error{{argument type 'String.UTF16View' does not conform to expected type 'RandomAccessCollection'}}
acceptsCollection(s.unicodeScalars)
acceptsBidirectionalCollection(s.unicodeScalars)
acceptsRandomAccessCollection(s.unicodeScalars) // expected-error{{argument type 'String.UnicodeScalarView' does not conform to expected type 'RandomAccessCollection'}}
acceptsCollection(s)
acceptsBidirectionalCollection(s)
acceptsRandomAccessCollection(s) // expected-error{{argument type 'String' does not conform to expected type 'RandomAccessCollection'}}
}
| apache-2.0 | 1ab4261e443c4a766c31fa7bc18621c1 | 73.193182 | 189 | 0.744524 | 4.447548 | false | true | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/BuySellUIKit/Core/PaymentMethods/Link Bank Flow/Yodlee Screen/Content/YodleeScreenContentReducer.swift | 1 | 9173 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import FeatureOpenBankingUI
import Localization
import PlatformKit
final class YodleeScreenContentReducer {
private enum Image {
static var filledBlockchainLogo: ImageResource {
.local(name: "filled_blockchain_logo", bundle: .platformUIKit)
}
static var largeBankIcon: ImageResource {
.local(name: "large-bank-icon", bundle: .platformUIKit)
}
static var filledYodleeLogo: ImageResource {
.local(name: "filled_yodlee_logo", bundle: .platformUIKit)
}
}
// MARK: Pending Content
typealias LocalizedStrings = LocalizationConstants.SimpleBuy.YodleeWebScreen
let continueButtonViewModel: ButtonViewModel = .primary(
with: LocalizedStrings.WebViewSuccessContent.mainActionButtonTitle
)
let tryAgainButtonViewModel: ButtonViewModel = .primary(
with: LocalizedStrings.FailurePendingContent.Generic.mainActionButtonTitle
)
let tryDifferentBankButtonViewModel: ButtonViewModel = .primary(
with: LocalizedStrings.FailurePendingContent.AccountUnsupported.mainActionButtonTitle
)
let cancelButtonViewModel: ButtonViewModel = .secondary(
with: LocalizedStrings.FailurePendingContent.Generic.cancelActionButtonTitle
)
let okButtonViewModel: ButtonViewModel = .secondary(
with: LocalizedStrings.FailurePendingContent.AlreadyLinked.mainActionButtonTitle
)
private let subtitleTextStyle = InteractableTextViewModel.Style(color: .descriptionText, font: .main(.regular, 14))
private let subtitleLinkTextStyle = InteractableTextViewModel.Style(color: .linkableText, font: .main(.regular, 14))
private let supportUrl = "https://support.blockchain.com/hc/en-us/requests/new"
// MARK: Pending Content
func webviewSuccessContent(bankName: String?) -> YodleePendingContent {
var subtitle = LocalizedStrings.WebViewSuccessContent.subtitleGeneric
if let bankName = bankName {
subtitle = String(format: LocalizedStrings.WebViewSuccessContent.subtitleWithBankName, bankName)
}
return YodleePendingContent(
compositeViewType: .composite(
.init(
baseViewType: .image(Image.largeBankIcon),
sideViewAttributes: .init(
type: .image(PendingStateViewModel.Image.success.imageResource),
position: .rightCorner
)
)
),
mainTitleContent: .init(
text: LocalizedStrings.WebViewSuccessContent.title,
font: .main(.bold, 20),
color: .darkTitleText,
alignment: .center
),
subtitleTextViewModel: .init(
inputs: [.text(string: subtitle)],
textStyle: subtitleTextStyle,
linkStyle: subtitleLinkTextStyle
),
buttonContent: continueButtonContent()
)
}
func webviewPendingContent() -> YodleePendingContent {
YodleePendingContent(
compositeViewType: .composite(
.init(
baseViewType: .image(Image.filledYodleeLogo),
sideViewAttributes: .init(type: .loader, position: .rightCorner)
)
),
mainTitleContent: .init(
text: LocalizedStrings.WebViewPendingContent.title,
font: .main(.bold, 20),
color: .darkTitleText,
alignment: .center
),
subtitleTextViewModel: .init(
inputs: [.text(string: LocalizedStrings.WebViewPendingContent.subtitle)],
textStyle: subtitleTextStyle,
linkStyle: subtitleLinkTextStyle
),
buttonContent: nil
)
}
func webviewFailureContent() -> YodleePendingContent {
YodleePendingContent(
compositeViewType: .composite(
.init(
baseViewType: .image(Image.filledBlockchainLogo),
sideViewAttributes: .init(
type: .image(PendingStateViewModel.Image.circleError.imageResource),
position: .rightCorner
)
)
),
mainTitleContent: .init(
text: LocalizedStrings.FailurePendingContent.Generic.title,
font: .main(.bold, 20),
color: .darkTitleText,
alignment: .center
),
subtitleTextViewModel: .init(
inputs: [
.text(string: LocalizedStrings.FailurePendingContent.Generic.subtitle),
.url(string: LocalizedStrings.FailurePendingContent.contactSupport, url: supportUrl)
],
textStyle: subtitleTextStyle,
linkStyle: subtitleLinkTextStyle
),
buttonContent: tryAgainAndCanceButtonContent()
)
}
func linkingBankPendingContent() -> YodleePendingContent {
YodleePendingContent(
compositeViewType: .composite(
.init(
baseViewType: .image(Image.filledBlockchainLogo),
sideViewAttributes: .init(type: .loader, position: .rightCorner)
)
),
mainTitleContent: .init(
text: LocalizedStrings.LinkingPendingContent.title,
font: .main(.bold, 20),
color: .darkTitleText,
alignment: .center
),
subtitleTextViewModel: .empty,
buttonContent: nil
)
}
func linkingBankFailureContent(error: LinkedBankData.LinkageError) -> YodleePendingContent {
let failureTitles = linkingBankFailureTitles(from: error)
let buttonContent = linkingBankFailureButtonContent(from: error)
return YodleePendingContent(
compositeViewType: .composite(
.init(
baseViewType: .image(Image.filledBlockchainLogo),
sideViewAttributes: .init(
type: .image(PendingStateViewModel.Image.circleError.imageResource),
position: .rightCorner
)
)
),
mainTitleContent: .init(
text: failureTitles.title,
font: .main(.bold, 20),
color: .darkTitleText,
alignment: .center
),
subtitleTextViewModel: failureTitles.subtitle,
buttonContent: buttonContent
)
}
// MARK: Button Content
func tryAgainAndCanceButtonContent() -> YodleeButtonsContent {
YodleeButtonsContent(
identifier: UUID(),
continueButtonViewModel: nil,
tryAgainButtonViewModel: tryAgainButtonViewModel,
cancelActionButtonViewModel: cancelButtonViewModel
)
}
func tryDifferentBankAndCancelButtonContent() -> YodleeButtonsContent {
YodleeButtonsContent(
identifier: UUID(),
continueButtonViewModel: nil,
tryAgainButtonViewModel: tryDifferentBankButtonViewModel,
cancelActionButtonViewModel: cancelButtonViewModel
)
}
func continueButtonContent() -> YodleeButtonsContent {
YodleeButtonsContent(
identifier: UUID(),
continueButtonViewModel: continueButtonViewModel,
tryAgainButtonViewModel: nil,
cancelActionButtonViewModel: nil
)
}
func okButtonContent() -> YodleeButtonsContent {
YodleeButtonsContent(
identifier: UUID(),
continueButtonViewModel: nil,
tryAgainButtonViewModel: nil,
cancelActionButtonViewModel: okButtonViewModel
)
}
// MARK: Private
private func linkingBankFailureButtonContent(
from linkageError: LinkedBankData.LinkageError
) -> YodleeButtonsContent {
switch linkageError {
case .alreadyLinked:
return okButtonContent()
case .infoNotFound:
return tryDifferentBankAndCancelButtonContent()
case .nameMismatch:
return tryDifferentBankAndCancelButtonContent()
case .failed:
return tryAgainAndCanceButtonContent()
default:
return tryAgainAndCanceButtonContent()
}
}
private func linkingBankFailureTitles(
from linkageError: LinkedBankData.LinkageError
) -> (title: String, subtitle: InteractableTextViewModel) {
let ui = BankState.UI.errors[.code(linkageError.rawValue), default: BankState.UI.defaultError]
return (
ui.info.title,
.init(
inputs: [
.text(string: ui.info.subtitle)
],
textStyle: subtitleTextStyle,
linkStyle: subtitleLinkTextStyle,
alignment: .center
)
)
}
}
| lgpl-3.0 | ce650fe4233ab7098f1968cf7d1b4f0b | 35.396825 | 120 | 0.598779 | 6.126921 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformKit/General/LinearInterpolator.swift | 1 | 825 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BigInt
import ToolKit
public enum LinearInterpolator {
/// Formula:Y = ( ( X - X1 )( Y2 - Y1) / ( X2 - X1) ) + Y1
/// X1, Y1 = first value, X2, Y2 = second value, X = target value, Y = result
public static func interpolate(x: [BigInt], y: [BigInt], xi: BigInt) -> BigInt {
let zero = BigInt.zero
precondition(x.count == y.count)
precondition(x.count == 2)
guard let firstX = x.first else { return zero }
guard let lastX = x.last else { return zero }
guard let firstY = y.first else { return zero }
guard let lastY = y.last else { return zero }
precondition(xi >= firstX && xi <= lastX)
return (((xi - firstX) * (lastY - firstY) / (lastX - firstX)) + firstY)
}
}
| lgpl-3.0 | d4be1cb74cd5bad444d6f57b60fd978b | 40.1 | 84 | 0.591241 | 3.512821 | false | false | false | false |
donmccaughey/Lunch | LunchApp/LunchApp/MasterViewController.swift | 1 | 3641 | //
// MasterViewController.swift
// LunchApp
//
// Created by Don McCaughey on 4/21/16.
// Copyright © 2016 Able Pear Software. All rights reserved.
//
import CoreLocation
import LunchKit
import UIKit
class MasterViewController: UITableViewController {
@IBOutlet weak var locationCell: LocationCell!
@IBOutlet weak var venuesCell: UITableViewCell!
var venueViewController: VenueViewController? = nil
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
if let split = self.splitViewController {
let controllers = split.viewControllers
self.venueViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? VenueViewController
}
addObserverFor(LunchAppWillRequestLocationNotification, selector: #selector(willRequestLocation))
addObserverFor(LunchAppDidReceivePlacemarkNotification, selector: #selector(didReceivePlacemark))
addObserverFor(LunchAppLocationUnavailableNotification, selector: #selector(locationUnavailable))
addObserverFor(LunchAppDidReceiveVenuesNotification, selector: #selector(didReceiveVenues))
addObserverFor(LunchAppDidHideVenueNotification, selector: #selector(didHideVenue))
addObserverFor(LunchAppDidShowVenueNotification, selector: #selector(didShowVenue))
}
// MARK: - Action methods
@IBAction func openGitHubURL(button: UIButton) {
let url = NSURL(string: button.titleForState(.Normal)!)
UIApplication.sharedApplication().openURL(url!)
}
// MARK: - Notification methods
func willRequestLocation(notification: NSNotification) {
locationCell.locationActivityIndicator.startAnimating()
locationCell.locationLabel.text = "finding location"
}
func didReceivePlacemark(notification: NSNotification) {
locationCell.locationActivityIndicator.stopAnimating()
if let placemark = notification.userInfo![LunchAppPlacemarkKey] as? CLPlacemark,
let address = placemark.name
{
locationCell.locationLabel.text = address
} else if let location = notification.userInfo![LunchAppLocationKey] as? CLLocation {
let latitude = String(format: "%.3f", location.coordinate.latitude)
let longitude = String(format: "%.3f", location.coordinate.longitude)
locationCell.locationLabel.text = "\(latitude), \(longitude)"
} else {
locationCell.locationLabel.text = "unknown location"
}
}
func locationUnavailable(notification: NSNotification) {
locationCell.locationActivityIndicator.stopAnimating()
locationCell.locationLabel.text = "unavailable"
}
func didReceiveVenues(notification: NSNotification) {
updateVenuesSection()
}
func didHideVenue(notification: NSNotification) {
updateVenuesSection()
}
func didShowVenue(notification: NSNotification) {
updateVenuesSection()
}
// MARK: - Other methods
func updateVenuesSection() {
let thumbsUpVenues = appDelegate.venues.getThumbsUpVenues()
venuesCell.detailTextLabel?.text = "\(thumbsUpVenues.count)"
if thumbsUpVenues.count > 0 {
venuesCell.accessoryType = .DisclosureIndicator
venuesCell.userInteractionEnabled = true
} else {
venuesCell.accessoryType = .None
venuesCell.userInteractionEnabled = false
}
}
}
| bsd-2-clause | 59e44d9767f4f872b7bf8fd8c0c94a54 | 35.767677 | 142 | 0.691484 | 5.574273 | false | false | false | false |
gregzo/AASingletons | AASingletons/AASingletons/PhotoLibraryManager.swift | 1 | 2525 | //
// PhotoLibraryManager.swift
// SwiftTest
//
// Created by Gregorio on 07/04/15.
// Copyright (c) 2015 Gregorio. All rights reserved.
//
import Foundation
import Photos
public class PhotoLibraryManager: AASingleton
{
final public class override var authorizationStatus : AsyncAuthorization
{
get
{
let status = PHPhotoLibrary.authorizationStatus()
return _asyncAuthorizationForAuthorization( status )
}
}
final internal class override func requestAuthorization( authCallback: AsyncAuthCallback )
{
PHPhotoLibrary.requestAuthorization()
{
( newStatus: PHAuthorizationStatus) -> Void in
dispatch_async( dispatch_get_main_queue() )
{
()->Void in
let asyncStatus : AsyncAuthorization = PhotoLibraryManager._asyncAuthorizationForAuthorization( newStatus )
authCallback( auth: asyncStatus )
}
}
}
private class func _asyncAuthorizationForAuthorization( status: PHAuthorizationStatus ) -> AsyncAuthorization
{
switch status
{
case .Authorized:
return AsyncAuthorization.Authorized
case .Denied, .Restricted:
return AsyncAuthorization.Denied
case .NotDetermined:
return AsyncAuthorization.NotDetermined
}
}
required public init?( token: Any )
{
super.init(token: token)
}
//FIXME: temp implementation
public func getLastPhoto( targetSize: CGSize, completion: ( image: UIImage? ) -> Void ) -> Void
{
let imgManager = PHImageManager.defaultManager()
var requestOptions = PHImageRequestOptions()
requestOptions.synchronous = true
var fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key:"creationDate", ascending: true)]
if let fetchResult = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: fetchOptions)
{
if fetchResult.count > 0
{
imgManager.requestImageForAsset( fetchResult.objectAtIndex(fetchResult.count - 1 ) as! PHAsset, targetSize: targetSize, contentMode: PHImageContentMode.AspectFill, options: requestOptions )
{ (image, _) in
completion( image: image )
}
}
}
}
}
| mit | b6f2c51f347ee200361a09e4429e7b0e | 29.792683 | 206 | 0.604356 | 5.92723 | false | false | false | false |
apple/swift | stdlib/private/OSLog/OSLogStringAlignment.swift | 7 | 3042 | //===----------------- OSLogStringAlignment.swift -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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
//
//===----------------------------------------------------------------------===//
// This file defines types and functions for specifying alignment of the
// interpolations passed to the os log APIs.
@usableFromInline
internal enum OSLogCollectionBound {
case start
case end
}
@frozen
public struct OSLogStringAlignment {
/// Minimum number of characters to be displayed. If the value to be printed
/// is shorter than this number, the result is padded with spaces. The value
/// is not truncated even if the result is larger. This value need not be a
/// compile-time constant, and is therefore an autoclosure.
@usableFromInline
internal var minimumColumnWidth: (() -> Int)?
/// This captures right/left alignment.
@usableFromInline
internal var anchor: OSLogCollectionBound
/// Initializes stored properties.
///
/// - Parameters:
/// - minimumColumnWidth: Minimum number of characters to be displayed. If the value to be
/// printed is shorter than this number, the result is padded with spaces. The value is not truncated
/// even if the result is larger.
/// - anchor: Use `.end` for right alignment and `.start` for left.
@_transparent
@usableFromInline
internal init(
minimumColumnWidth: (() -> Int)? = nil,
anchor: OSLogCollectionBound = .end
) {
self.minimumColumnWidth = minimumColumnWidth
self.anchor = anchor
}
/// Indicates no alignment.
@_semantics("constant_evaluable")
@inlinable
@_optimize(none)
public static var none: OSLogStringAlignment { OSLogStringAlignment(anchor: .end) }
/// Right align and display at least `columns` characters.
///
/// The interpolated value would be padded with spaces, if necessary, to
/// meet the specified `columns` characters.
///
/// - Parameter columns: minimum number of characters to display.
@_semantics("constant_evaluable")
@inlinable
@_optimize(none)
public static func right(
columns: @escaping @autoclosure () -> Int
) -> OSLogStringAlignment {
OSLogStringAlignment(minimumColumnWidth: columns, anchor: .end)
}
/// Left align and display at least `columns` characters.
///
/// The interpolated value would be padded with spaces, if necessary, to
/// meet the specified `columns` characters.
///
/// - Parameter columns: minimum number of characters to display.
@_semantics("constant_evaluable")
@inlinable
@_optimize(none)
public static func left(
columns: @escaping @autoclosure () -> Int
) -> OSLogStringAlignment {
OSLogStringAlignment(minimumColumnWidth: columns, anchor: .start)
}
}
| apache-2.0 | 801fab19381850cc2c5cccd950ffc36c | 33.965517 | 106 | 0.683761 | 4.730949 | false | false | false | false |
haitran2011/Rocket.Chat.iOS | Rocket.Chat/Models/Subscription.swift | 1 | 3478 | //
// Subscription.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/9/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import Foundation
import RealmSwift
import SwiftyJSON
enum SubscriptionType: String {
case directMessage = "d"
case channel = "c"
case group = "p"
}
class Subscription: BaseModel {
dynamic var auth: Auth?
fileprivate dynamic var privateType = SubscriptionType.channel.rawValue
var type: SubscriptionType {
get { return SubscriptionType(rawValue: privateType) ?? SubscriptionType.group }
set { privateType = newValue.rawValue }
}
dynamic var rid = ""
dynamic var name = ""
dynamic var unread = 0
dynamic var open = false
dynamic var alert = false
dynamic var favorite = false
dynamic var createdAt: Date?
dynamic var lastSeen: Date?
dynamic var roomTopic: String?
dynamic var roomDescription: String?
dynamic var otherUserId: String?
var directMessageUser: User? {
guard let otherUserId = otherUserId else { return nil }
guard let users = try? Realm().objects(User.self).filter("identifier = '\(otherUserId)'") else { return nil }
return users.first
}
let messages = LinkingObjects(fromType: Message.self, property: "subscription")
}
extension Subscription {
func isValid() -> Bool {
return self.rid.characters.count > 0
}
func isJoined() -> Bool {
return auth != nil || type != .channel
}
func fetchRoomIdentifier(_ completion: @escaping MessageCompletionObject <Subscription>) {
if type == .channel {
SubscriptionManager.getRoom(byName: name, completion: { [weak self] (response) in
guard !response.isError() else { return }
let result = response.result["result"]
Realm.executeOnMainThread({ realm in
if let obj = self {
obj.update(result, realm: realm)
realm.add(obj, update: true)
}
})
guard let strongSelf = self else { return }
completion(strongSelf)
})
} else if type == .directMessage {
SubscriptionManager.createDirectMessage(name, completion: { [weak self] (response) in
guard !response.isError() else { return }
let rid = response.result["result"]["rid"].string ?? ""
Realm.executeOnMainThread({ realm in
if let obj = self {
obj.rid = rid
realm.add(obj, update: true)
}
})
guard let strongSelf = self else { return }
completion(strongSelf)
})
}
}
func fetchMessages() -> Results<Message> {
let filter = NSPredicate(format: "userBlocked == false")
return self.messages.filter(filter).sorted(byKeyPath: "createdAt", ascending: true)
}
func updateFavorite(_ favorite: Bool) {
Realm.executeOnMainThread({ _ in
self.favorite = favorite
})
}
}
extension Subscription {
static func find(rid: String, realm: Realm) -> Subscription? {
var object: Subscription?
if let findObject = realm.objects(Subscription.self).filter("rid == '\(rid)'").first {
object = findObject
}
return object
}
}
| mit | 09349021fa08ed9ba596a9b14c2de8a2 | 27.735537 | 117 | 0.581823 | 4.917963 | false | false | false | false |
carabina/ActionSwift3 | ActionSwift3/media/SoundChannel.swift | 1 | 1450 | //
// SoundChannel.swift
// ActionSwift
//
// Created by Craig on 6/08/2015.
// Copyright (c) 2015 Interactive Coconut. All rights reserved.
//
import SpriteKit
import AVFoundation
public class SoundChannel: EventDispatcher,AVAudioPlayerDelegate {
var audioPlayer:AVAudioPlayer = AVAudioPlayer()
internal func play(name:String,startTime:Number=0, loops:int=1) {
var pathExtension = name.pathExtension
if (pathExtension == "") {pathExtension = "mp3"}
var path = NSBundle.mainBundle().pathForResource(name.stringByDeletingPathExtension, ofType: pathExtension)
if let path = path {
var url = NSURL.fileURLWithPath(path)
var error: NSError?
self.audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
self.audioPlayer.delegate = self
self.audioPlayer.numberOfLoops = loops
if (startTime > 0) {
self.audioPlayer.currentTime = NSTimeInterval(startTime)
}
self.audioPlayer.play()
}
}
func stop() {
self.audioPlayer.stop()
}
public func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool) {
dispatchEvent(Event(EventType.SoundComplete.rawValue,false))
}
public func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer!, error: NSError!) {
dispatchEvent(Event(EventType.SoundError.rawValue,false))
}
}
| mit | 03f840e7716f9ec4b805b2457c31bb11 | 35.25 | 115 | 0.667586 | 4.849498 | false | false | false | false |
apple/swift-nio-http2 | Sources/NIOHTTP2/ConnectionStateMachine/RemotelyQuiescingState.swift | 1 | 823 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// A state where the connection is being quiesced by the remote peer. In this state,
/// the local peer may not initiate new streams.
///
/// This protocol should only be conformed to by states for the HTTP/2 connection state machine.
protocol RemotelyQuiescingState {
var lastLocalStreamID: HTTP2StreamID { get set }
}
| apache-2.0 | f6c3d8672ff66b0d496de58c37ef2e71 | 38.190476 | 96 | 0.600243 | 4.957831 | false | false | false | false |
jpedrosa/sua | examples/socket_hello/Sources/main.swift | 1 | 1380 |
import Glibc
import CSua
import Sua
func printHostIP(hostName: String) {
var sa = SocketAddress(hostName: hostName)
if let s = sa.ip6ToString() {
print("Host: \(hostName), IP: \(s)")
} else {
print("Error: couldn't find address for \"\(hostName)\".")
let msg = sa.errorMessage ?? ""
print("Error message: \(msg)")
}
}
var addressName = "google.com"
printHostIP(hostName: addressName)
printHostIP(hostName: "reddit.com")
var sa = SocketAddress(hostName: addressName)
p(sa.ip4ToUInt32())
p(sa.ip4ToString())
p(sa.ip6ToString())
if let a = sa.ip4ToStringList() {
for ip in a {
printList(ip)
}
}
var count = 0
var sw = Stopwatch()
sw.start()
for _ in 0..<1000 {
var sample = "GET / HTTP/1.1\r\nHost: 127.0.0.1:9123\r\nUser-Agent: curl/7.43.0\r\nAccept: */*\r\n\r\n"
var a = [UInt8](sample.utf8)
var parser = HeaderParser()
try parser.parse(bytes: a)
if parser.header.method == "GET" {
count += 1
}
// p(parser)
}
p("Count \(count) Elapsed: \(sw.millis)")
let serverSocket = try ServerSocket(hostName: "127.0.0.1", port: 9123)
defer {
serverSocket.close()
}
var buffer = [UInt8](repeating: 0, count: 1024)
while true {
if let socket = serverSocket.accept() {
defer {
socket.close()
}
var n = socket.read(buffer: &buffer, maxBytes: buffer.count)
let _ = socket.write(string: "Hello World\n")
}
}
| apache-2.0 | 5186e7526b118ac607d8a8b31e0ed180 | 19.909091 | 105 | 0.638406 | 2.93617 | false | false | false | false |
ul7290/realm-cocoa | RealmSwift-swift1.2/Tests/ObjectCreationTests.swift | 2 | 24637 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import XCTest
import Realm.Private
import RealmSwift
import Foundation
class ObjectCreationTests: TestCase {
// MARK: Init tests
func testInitWithDefaults() {
// test all properties are defaults
let object = SwiftObject()
XCTAssertNil(object.realm)
// test defaults values
verifySwiftObjectWithDictionaryLiteral(object, dictionary: SwiftObject.defaultValues(), boolObjectValue: false, boolObjectListValues: [])
// test realm properties are nil for standalone
XCTAssertNil(object.realm)
XCTAssertNil(object.objectCol!.realm)
XCTAssertNil(object.arrayCol.realm)
}
func testInitWithOptionalWithoutDefaults() {
let object = SwiftOptionalObject()
for prop in object.objectSchema.properties {
let value: AnyObject? = object[prop.name]
if let value = value as? RLMOptionalBase {
XCTAssertNil(value.underlyingValue)
} else {
XCTAssertNil(value)
}
}
}
func testInitWithOptionalDefaults() {
let object = SwiftOptionalDefaultValuesObject()
verifySwiftOptionalObjectWithDictionaryLiteral(object, dictionary: SwiftOptionalDefaultValuesObject.defaultValues(), boolObjectValue: true)
}
func testInitWithDictionary() {
// dictionary with all values specified
let baselineValues =
["boolCol": true as NSNumber,
"intCol": 1 as NSNumber,
"floatCol": 1.1 as NSNumber,
"doubleCol": 11.1 as NSNumber,
"stringCol": "b" as NSString,
"binaryCol": "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData,
"dateCol": NSDate(timeIntervalSince1970: 2) as NSDate,
"objectCol": SwiftBoolObject(value: [true]) as AnyObject,
"arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()] as AnyObject
]
// test with valid dictionary literals
let props = Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[props[propNum].name] = validValue
let object = SwiftObject(value: values)
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true, boolObjectListValues: [true, false])
}
}
// test with invalid dictionary literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[props[propNum].name] = invalidValue
assertThrows(SwiftObject(value: values), "Invalid property value")
}
}
}
func testInitWithDefaultsAndDictionary() {
// test with dictionary with mix of default and one specified value
let object = SwiftObject(value: ["intCol": 200])
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
verifySwiftObjectWithDictionaryLiteral(object, dictionary: valueDict, boolObjectValue: false, boolObjectListValues: [])
}
func testInitWithArray() {
// array with all values specified
let baselineValues = [true, 1, 1.1, 11.1, "b", "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData, NSDate(timeIntervalSince1970: 2) as NSDate, ["boolCol": true], [[true], [false]]] as [AnyObject]
// test with valid dictionary literals
let props = Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[propNum] = validValue
let object = SwiftObject(value: values)
verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true, boolObjectListValues: [true, false])
}
}
// test with invalid dictionary literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[propNum] = invalidValue
assertThrows(SwiftObject(value: values), "Invalid property value")
}
}
}
func testInitWithKVCObject() {
// test with kvc object
let objectWithInt = SwiftObject(value: ["intCol": 200])
let objectWithKVCObject = SwiftObject(value: objectWithInt)
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
verifySwiftObjectWithDictionaryLiteral(objectWithKVCObject, dictionary: valueDict, boolObjectValue: false, boolObjectListValues: [])
}
func testGenericInit() {
func createObject<T: Object>() -> T {
return T()
}
let obj1: SwiftBoolObject = createObject()
let obj2 = SwiftBoolObject()
XCTAssertEqual(obj1.boolCol, obj2.boolCol, "object created via generic initializer should equal object created by calling initializer directly")
}
// MARK: Creation tests
func testCreateWithDefaults() {
let realm = Realm()
assertThrows(realm.create(SwiftObject), "Must be in write transaction")
var object: SwiftObject!
let objects = realm.objects(SwiftObject)
XCTAssertEqual(0, objects.count)
realm.write {
// test create with all defaults
object = realm.create(SwiftObject)
return
}
verifySwiftObjectWithDictionaryLiteral(object, dictionary: SwiftObject.defaultValues(), boolObjectValue: false, boolObjectListValues: [])
// test realm properties are populated correctly
XCTAssertEqual(object.realm!, realm)
XCTAssertEqual(object.objectCol!.realm!, realm)
XCTAssertEqual(object.arrayCol.realm!, realm)
}
func testCreateWithOptionalWithoutDefaults() {
let realm = Realm()
realm.write {
let object = realm.create(SwiftOptionalObject)
for prop in object.objectSchema.properties {
XCTAssertNil(object[prop.name])
}
}
}
func testCreateWithOptionalDefaults() {
let realm = Realm()
realm.write {
let object = realm.create(SwiftOptionalDefaultValuesObject)
self.verifySwiftOptionalObjectWithDictionaryLiteral(object, dictionary: SwiftOptionalDefaultValuesObject.defaultValues(), boolObjectValue: true)
}
}
func testCreateWithOptionalIgnoredProperties() {
let realm = Realm()
realm.write {
let object = realm.create(SwiftOptionalIgnoredPropertiesObject)
let properties = object.objectSchema.properties
XCTAssertEqual(properties, [])
}
}
func testCreateWithDictionary() {
// dictionary with all values specified
let baselineValues =
["boolCol": true as NSNumber,
"intCol": 1 as NSNumber,
"floatCol": 1.1 as NSNumber,
"doubleCol": 11.1 as NSNumber,
"stringCol": "b" as NSString,
"binaryCol": "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData,
"dateCol": NSDate(timeIntervalSince1970: 2) as NSDate,
"objectCol": SwiftBoolObject(value: [true]) as AnyObject,
"arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()] as AnyObject
]
// test with valid dictionary literals
let props = Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[props[propNum].name] = validValue
Realm().beginWrite()
let object = Realm().create(SwiftObject.self, value: values)
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true, boolObjectListValues: [true, false])
Realm().commitWrite()
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true, boolObjectListValues: [true, false])
}
}
// test with invalid dictionary literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[props[propNum].name] = invalidValue
Realm().beginWrite()
assertThrows(Realm().create(SwiftObject.self, value: values), "Invalid property value")
Realm().cancelWrite()
}
}
}
func testCreateWithDefaultsAndDictionary() {
// test with dictionary with mix of default and one specified value
let realm = Realm()
realm.beginWrite()
let objectWithInt = realm.create(SwiftObject.self, value: ["intCol": 200])
realm.commitWrite()
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
verifySwiftObjectWithDictionaryLiteral(objectWithInt, dictionary: valueDict, boolObjectValue: false, boolObjectListValues: [])
}
func testCreateWithArray() {
// array with all values specified
let baselineValues = [true, 1, 1.1, 11.1, "b", "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData, NSDate(timeIntervalSince1970: 2) as NSDate, ["boolCol": true], [[true], [false]]] as [AnyObject]
// test with valid dictionary literals
let props = Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[propNum] = validValue
Realm().beginWrite()
let object = Realm().create(SwiftObject.self, value: values)
verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true, boolObjectListValues: [true, false])
Realm().commitWrite()
verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true, boolObjectListValues: [true, false])
}
}
// test with invalid array literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[propNum] = invalidValue
Realm().beginWrite()
assertThrows(Realm().create(SwiftObject.self, value: values),
"Invalid property value '\(invalidValue)' for property number \(propNum)")
Realm().cancelWrite()
}
}
}
func testCreateWithKVCObject() {
// test with kvc object
Realm().beginWrite()
let objectWithInt = Realm().create(SwiftObject.self, value: ["intCol": 200])
let objectWithKVCObject = Realm().create(SwiftObject.self, value: objectWithInt)
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
Realm().commitWrite()
verifySwiftObjectWithDictionaryLiteral(objectWithKVCObject, dictionary: valueDict, boolObjectValue: false, boolObjectListValues: [])
XCTAssertEqual(Realm().objects(SwiftObject).count, 2, "Object should have been copied")
}
func testCreateWithNestedObjects() {
let standalone = SwiftPrimaryStringObject(value: ["p0", 11])
Realm().beginWrite()
let objectWithNestedObjects = Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["p1", ["p1", 11], [standalone]])
Realm().commitWrite()
let stringObjects = Realm().objects(SwiftPrimaryStringObject)
XCTAssertEqual(stringObjects.count, 2)
let persistedObject = stringObjects.first!
XCTAssertNotEqual(standalone, persistedObject) // standalone object should be copied into the realm, not added directly
XCTAssertEqual(objectWithNestedObjects.object!, persistedObject)
XCTAssertEqual(objectWithNestedObjects.objects.first!, stringObjects.last!)
let standalone1 = SwiftPrimaryStringObject(value: ["p3", 11])
Realm().beginWrite()
assertThrows(Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["p3", ["p3", 11], [standalone1]]), "Should throw with duplicate primary key")
Realm().commitWrite()
}
func testUpdateWithNestedObjects() {
let standalone = SwiftPrimaryStringObject(value: ["primary", 11])
Realm().beginWrite()
let object = Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["otherPrimary", ["primary", 12], [["primary", 12]]], update: true)
Realm().commitWrite()
let stringObjects = Realm().objects(SwiftPrimaryStringObject)
XCTAssertEqual(stringObjects.count, 1)
let persistedObject = object.object!
XCTAssertEqual(persistedObject.intCol, 12)
XCTAssertNil(standalone.realm) // the standalone object should be copied, rather than added, to the realm
XCTAssertEqual(object.object!, persistedObject)
XCTAssertEqual(object.objects.first!, persistedObject)
}
func testCreateWithObjectsFromAnotherRealm() {
let values = [
"boolCol": true as NSNumber,
"intCol": 1 as NSNumber,
"floatCol": 1.1 as NSNumber,
"doubleCol": 11.1 as NSNumber,
"stringCol": "b" as NSString,
"binaryCol": "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData,
"dateCol": NSDate(timeIntervalSince1970: 2) as NSDate,
"objectCol": SwiftBoolObject(value: [true]) as AnyObject,
"arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()] as AnyObject,
]
realmWithTestPath().beginWrite()
let otherRealmObject = realmWithTestPath().create(SwiftObject.self, value: values)
realmWithTestPath().commitWrite()
Realm().beginWrite()
let object = Realm().create(SwiftObject.self, value: otherRealmObject)
Realm().commitWrite()
XCTAssertNotEqual(otherRealmObject, object)
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true, boolObjectListValues: [true, false])
}
func testUpdateWithObjectsFromAnotherRealm() {
realmWithTestPath().beginWrite()
let otherRealmObject = realmWithTestPath().create(SwiftLinkToPrimaryStringObject.self, value: ["primary", NSNull(), [["2", 2], ["4", 4]]])
realmWithTestPath().commitWrite()
Realm().beginWrite()
Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["primary", ["10", 10], [["11", 11]]])
let object = Realm().create(SwiftLinkToPrimaryStringObject.self, value: otherRealmObject, update: true)
Realm().commitWrite()
XCTAssertNotEqual(otherRealmObject, object) // the object from the other realm should be copied into this realm
XCTAssertEqual(Realm().objects(SwiftLinkToPrimaryStringObject).count, 1)
XCTAssertEqual(Realm().objects(SwiftPrimaryStringObject).count, 4)
}
func testCreateWithNSNullLinks() {
let values = [
"boolCol": true as NSNumber,
"intCol": 1 as NSNumber,
"floatCol": 1.1 as NSNumber,
"doubleCol": 11.1 as NSNumber,
"stringCol": "b" as NSString,
"binaryCol": "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData,
"dateCol": NSDate(timeIntervalSince1970: 2) as NSDate,
"objectCol": NSNull(),
"arrayCol": NSNull(),
]
realmWithTestPath().beginWrite()
let object = realmWithTestPath().create(SwiftObject.self, value: values)
realmWithTestPath().commitWrite()
XCTAssertNil(object.objectCol)
XCTAssertEqual(object.arrayCol.count, 0)
}
// test null object
// test null list
// MARK: Add tests
func testAddWithExisingNestedObjects() {
Realm().beginWrite()
let existingObject = Realm().create(SwiftBoolObject)
Realm().commitWrite()
Realm().beginWrite()
let object = SwiftObject(value: ["objectCol" : existingObject])
Realm().add(object)
Realm().commitWrite()
XCTAssertNotNil(object.realm)
XCTAssertEqual(object.objectCol!, existingObject)
}
func testAddAndUpdateWithExisingNestedObjects() {
Realm().beginWrite()
let existingObject = Realm().create(SwiftPrimaryStringObject.self, value: ["primary", 1])
Realm().commitWrite()
Realm().beginWrite()
let object = SwiftLinkToPrimaryStringObject(value: ["primary", ["primary", 2], []])
Realm().add(object, update: true)
Realm().commitWrite()
XCTAssertNotNil(object.realm)
XCTAssertEqual(object.object!, existingObject) // the existing object should be updated
XCTAssertEqual(existingObject.intCol, 2)
}
func testAddStandaloneObjectWithDynamicListProperty() {
let obj = SwiftObject()
obj.boolCol = true
let arrayObj = SwiftDynamicListOfSwiftObject()
arrayObj.array.append(obj)
let realm = Realm()
realm.write {
realm.add(arrayObj)
}
XCTAssertEqual(1, arrayObj.array.count)
XCTAssertEqual(true, arrayObj.array[0].boolCol)
}
// MARK: Private utilities
private func verifySwiftObjectWithArrayLiteral(object: SwiftObject, array: [AnyObject], boolObjectValue: Bool, boolObjectListValues: [Bool]) {
XCTAssertEqual(object.boolCol, array[0] as! Bool)
XCTAssertEqual(object.intCol, array[1] as! Int)
XCTAssertEqual(object.floatCol, array[2] as! Float)
XCTAssertEqual(object.doubleCol, array[3] as! Double)
XCTAssertEqual(object.stringCol, array[4] as! String)
XCTAssertEqual(object.binaryCol, array[5] as! NSData)
XCTAssertEqual(object.dateCol, array[6] as! NSDate)
XCTAssertEqual(object.objectCol!.boolCol, boolObjectValue)
XCTAssertEqual(object.arrayCol.count, boolObjectListValues.count)
for i in 0..<boolObjectListValues.count {
XCTAssertEqual(object.arrayCol[i].boolCol, boolObjectListValues[i])
}
}
private func verifySwiftObjectWithDictionaryLiteral(object: SwiftObject, dictionary: [String:AnyObject], boolObjectValue: Bool, boolObjectListValues: [Bool]) {
XCTAssertEqual(object.boolCol, dictionary["boolCol"] as! Bool)
XCTAssertEqual(object.intCol, dictionary["intCol"] as! Int)
XCTAssertEqual(object.floatCol, dictionary["floatCol"] as! Float)
XCTAssertEqual(object.doubleCol, dictionary["doubleCol"] as! Double)
XCTAssertEqual(object.stringCol, dictionary["stringCol"] as! String)
XCTAssertEqual(object.binaryCol, dictionary["binaryCol"] as! NSData)
XCTAssertEqual(object.dateCol, dictionary["dateCol"] as! NSDate)
XCTAssertEqual(object.objectCol!.boolCol, boolObjectValue)
XCTAssertEqual(object.arrayCol.count, boolObjectListValues.count)
for i in 0..<boolObjectListValues.count {
XCTAssertEqual(object.arrayCol[i].boolCol, boolObjectListValues[i])
}
}
private func verifySwiftOptionalObjectWithDictionaryLiteral(object: SwiftOptionalDefaultValuesObject, dictionary: [String:AnyObject], boolObjectValue: Bool?) {
let get = { (key: String) -> AnyObject? in
let val: AnyObject? = dictionary[key]
if let _ = val as? NSNull { return nil }
return val
}
XCTAssert(object.optBoolCol.value == (get("optBoolCol") as! Bool?))
XCTAssert(object.optIntCol.value == (get("optIntCol") as! Int?))
XCTAssert(object.optInt8Col.value == (get("optInt8Col") as! Int8?))
XCTAssert(object.optInt16Col.value == (get("optInt16Col") as! Int16?))
XCTAssert(object.optInt32Col.value == (get("optInt32Col") as! Int32?))
XCTAssert(object.optInt64Col.value == (get("optInt64Col") as! Int64?))
XCTAssert(object.optFloatCol.value == (get("optFloatCol") as! Float?))
XCTAssert(object.optDoubleCol.value == (get("optDoubleCol") as! Double?))
XCTAssert(object.optStringCol == (get("optStringCol") as! String?))
XCTAssert(object.optNSStringCol == (get("optNSStringCol") as! String?))
XCTAssert(object.optBinaryCol == (get("optBinaryCol") as! NSData?))
XCTAssert(object.optDateCol == (get("optDateCol") as! NSDate?))
XCTAssert(object.optObjectCol?.boolCol == boolObjectValue)
}
private func defaultSwiftObjectValuesWithReplacements(replace: [String: AnyObject]) -> [String: AnyObject] {
var valueDict = SwiftObject.defaultValues()
for (key, value) in replace {
valueDict[key] = value
}
return valueDict
}
// return an array of valid values that can be used to initialize each type
private func validValuesForSwiftObjectType(type: PropertyType) -> [AnyObject] {
Realm().beginWrite()
let persistedObject = Realm().create(SwiftBoolObject.self, value: [true])
Realm().commitWrite()
switch type {
case .Bool: return [true, 0 as Int, 1 as Int]
case .Int: return [1 as Int]
case .Float: return [1 as Int, 1.1 as Float, 11.1 as Double]
case .Double: return [1 as Int, 1.1 as Float, 11.1 as Double]
case .String: return ["b"]
case .Data: return ["b".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! as NSData]
case .Date: return [NSDate(timeIntervalSince1970: 2) as AnyObject]
case .Object: return [[true], ["boolCol": true], SwiftBoolObject(value: [true]), persistedObject]
case .Array: return [[[true], [false]], [["boolCol": true], ["boolCol": false]], [SwiftBoolObject(value: [true]), SwiftBoolObject(value: [false])], [persistedObject, [false]]]
case .Any: XCTFail("not supported")
}
return []
}
private func invalidValuesForSwiftObjectType(type: PropertyType) -> [AnyObject] {
Realm().beginWrite()
let persistedObject = Realm().create(SwiftIntObject)
Realm().commitWrite()
switch type {
case .Bool: return ["invalid", 2 as Int, 1.1 as Float, 11.1 as Double]
case .Int: return ["invalid", 1.1 as Float, 11.1 as Double]
case .Float: return ["invalid", true, false]
case .Double: return ["invalid", true, false]
case .String: return [0x197A71D, true, false]
case .Data: return ["invalid"]
case .Date: return ["invalid"]
case .Object: return ["invalid", ["a"], ["boolCol": "a"], SwiftIntObject()]
case .Array: return ["invalid", [["a"]], [["boolCol" : "a"]], [[SwiftIntObject()]], [[persistedObject]]]
case .Any: XCTFail("not supported")
}
return []
}
}
| apache-2.0 | 3f23cb41f18aee409b444234815294c9 | 44.70872 | 207 | 0.638308 | 5.409969 | false | true | false | false |
VikingDen/actor-platform | actor-apps/app-ios/ActorApp/Controllers Support/AATableViewController.swift | 24 | 2595 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
class AATableViewController: AAViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: -
// MARK: Public vars
var tableView: UITableView!
var tableViewStyle: UITableViewStyle!
// MARK: -
// MARK: Constructors
init(style: UITableViewStyle) {
super.init()
tableViewStyle = style
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: -
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.backBarButtonItem = UIBarButtonItem(title: NSLocalizedString("NavigationBack",comment:"Back button"), style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
}
override func loadView() {
super.loadView()
// view.backgroundColor = UIColor.whiteColor()
tableView = UITableView(frame: view.bounds, style: tableViewStyle)
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
}
// MARK: -
// MARK: Methods
func showPlaceholderWithImage(image: UIImage?, title: String?, subtitle: String?) {
placeholder.setImage(image, title: title, subtitle: subtitle)
super.showPlaceholder()
}
// MARK: -
// MARK: Setters
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
tableView.setEditing(editing, animated: animated)
}
// MARK: -
// MARK: Getters
private func placeholderViewFrame() -> CGRect {
let navigationBarHeight: CGFloat = 64.0 + Utils.retinaPixel() // TODO: if will be landscape then change to manual calc
return CGRect(x: 0, y: navigationBarHeight, width: view.bounds.size.width, height: view.bounds.size.height - navigationBarHeight)
}
// MARK: -
// MARK: Layout
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
tableView.frame = view.bounds;
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 0
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return UITableViewCell()
}
}
extension AATableViewController: UITableViewDelegate {
} | mit | 787629d986eb581e93ae20ebe5a2ca5d | 26.041667 | 185 | 0.63237 | 5.138614 | false | false | false | false |
goaairlines/capetown-ios | capetown/Views/ConverterView.swift | 1 | 3382 | //
// ConverterView.swift
// capetown
//
// Created by Alex Berger on 3/10/16.
// Copyright © 2016 goa airlines. All rights reserved.
//
import UIKit
struct ConverterViewConstants {
static let currencyViewAspectRatio: CGFloat = 150.0 / 120.0
static let currencyViewInset: CGFloat = 16.0
static let currencySwapIconWidth: CGFloat = 44.0
}
class ConverterView: UIView {
var fromCurrency: Currency!
var toCurrency: Currency!
private var fromCurrencyView: CurrencyValueView!
private var currencySwapIconView: CurrencySwapIconView!
private var toCurrencyView: CurrencyValueView!
init(fromCurrency: Currency, toCurrency: Currency) {
super.init(frame: CGRectZero)
self.fromCurrency = fromCurrency
self.toCurrency = toCurrency
setupView()
}
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func updateConstraints() {
setupConstraints()
super.updateConstraints()
}
}
extension ConverterView {
private func setupView() {
fromCurrencyView = CurrencyValueView(currency: self.fromCurrency)
self.addSubview(fromCurrencyView)
currencySwapIconView = CurrencySwapIconView()
self.addSubview(currencySwapIconView)
toCurrencyView = CurrencyValueView(currency: self.toCurrency)
self.addSubview(toCurrencyView)
}
private func setupConstraints() {
let fromCurrencyViewAspectRatioConstraint = NSLayoutConstraint(
item: fromCurrencyView,
attribute: NSLayoutAttribute.Width,
relatedBy: NSLayoutRelation.Equal,
toItem: fromCurrencyView,
attribute: NSLayoutAttribute.Height,
multiplier: ConverterViewConstants.currencyViewAspectRatio,
constant: 0.0)
fromCurrencyView.addConstraint(fromCurrencyViewAspectRatioConstraint)
fromCurrencyView.snp_makeConstraints { make in
make.left.equalTo(ConverterViewConstants.currencyViewInset)
make.right.equalTo(currencySwapIconView.snp_left)
make.centerY.equalTo(snp_centerY)
}
currencySwapIconView.snp_makeConstraints { make in
make.width.height.equalTo(ConverterViewConstants.currencySwapIconWidth)
make.center.equalTo(snp_center)
}
let toCurrencyViewAspectRatioConstraint = NSLayoutConstraint(
item: toCurrencyView,
attribute: NSLayoutAttribute.Width,
relatedBy: NSLayoutRelation.Equal,
toItem: toCurrencyView,
attribute: NSLayoutAttribute.Height,
multiplier: ConverterViewConstants.currencyViewAspectRatio,
constant: 0.0)
toCurrencyView.addConstraint(toCurrencyViewAspectRatioConstraint)
toCurrencyView.snp_makeConstraints { make in
make.right.equalTo(-ConverterViewConstants.currencyViewInset)
make.left.equalTo(currencySwapIconView.snp_right)
make.centerY.equalTo(snp_centerY)
}
}
func updateConverterAmounts(fromAmount: Double, toAmount: Double) {
fromCurrencyView.updateAmountLabel(fromAmount)
toCurrencyView.updateAmountLabel(toAmount)
}
}
| mit | 135ebcbc3581e33c6f8fabb6dafcda90 | 31.509615 | 99 | 0.672582 | 5.52451 | false | false | false | false |
mdpianelli/ios-shopfinder | ShopFinder/ShopFinder/MenuController.swift | 1 | 2158 | //
// LeftMenuController.swift
// ShopFinder
//
// Created by Marcos Pianelli on 08/07/15.
// Copyright (c) 2015 Barkala Studios. All rights reserved.
//
import UIKit
import RESideMenu
class MenuController: UIViewController, RESideMenuDelegate, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
let titles = ["Home", "Calendar", "Profile", "Settings"]
let images = ["IconHome", "IconCalendar", "IconProfile", "IconSettings"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.contentInset = UIEdgeInsetsMake(100, 0,0, 0)
}
//MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titles.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
func tableView(atableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell!
cell.textLabel!.textColor = UIColor.whiteColor()
cell.textLabel!.text = titles[indexPath.row];
cell.imageView!.image = UIImage(named:images[indexPath.row])
return cell
}
//MARK : - UITableViewDelegate
func tableView(atableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
switch(indexPath.row)
{
case 0 :
self.sideMenuViewController.setContentViewController(self.storyboard!.instantiateViewControllerWithIdentifier("NavShopListController") , animated: true)
case 3:
self.sideMenuViewController.setContentViewController(self.storyboard!.instantiateViewControllerWithIdentifier("NavSettingsController") , animated: true)
default:break;
}
self.sideMenuViewController.hideMenuViewController()
}
} | mit | daccf5bd66feba4bae26451fd905c80d | 27.407895 | 168 | 0.652456 | 5.785523 | false | false | false | false |
nodekit-io/nodekit-darwin-lite | src/nodekit/NKScripting/util/NKArchive/NKAR_Uncompressor.swift | 1 | 8095 | /*
* nodekit.io
*
* Copyright (c) 2016-7 OffGrid Networks. All Rights Reserved.
* Portions Copyright (c) 2013 GitHub, Inc. under MIT License
* Portions Copyright (c) 2015 lazyapps. 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 Foundation
import Compression
struct NKAR_Uncompressor {
static func uncompressWithArchiveData(_ cdir: NKAR_CentralDirectory, data: Data) -> Data? {
let bytes = (data as NSData).bytes.assumingMemoryBound(to: UInt8.self)
let offsetBytes = bytes.advanced(by: Int(cdir.dataOffset))
return uncompressWithFileBytes(cdir, fromBytes: offsetBytes)
}
func unzip_(_ compressedData:Data) -> Data? {
let streamPtr = UnsafeMutablePointer<compression_stream>.allocate(capacity: 1)
var stream = streamPtr.pointee
var status: compression_status
status = compression_stream_init(&stream, COMPRESSION_STREAM_DECODE, COMPRESSION_ZLIB)
stream.src_ptr = (compressedData as NSData).bytes.bindMemory(to: UInt8.self, capacity: compressedData.count)
stream.src_size = compressedData.count
let dstBufferSize: size_t = 4096
let dstBufferPtr = UnsafeMutablePointer<UInt8>.allocate(capacity: dstBufferSize)
stream.dst_ptr = dstBufferPtr
stream.dst_size = dstBufferSize
let decompressedData = NSMutableData()
repeat {
status = compression_stream_process(&stream, 0)
switch status {
case COMPRESSION_STATUS_OK:
if stream.dst_size == 0 {
decompressedData.append(dstBufferPtr, length: dstBufferSize)
stream.dst_ptr = dstBufferPtr
stream.dst_size = dstBufferSize
}
case COMPRESSION_STATUS_END:
if stream.dst_ptr > dstBufferPtr {
decompressedData.append(dstBufferPtr, length: stream.dst_ptr - dstBufferPtr)
}
default:
break
}
}
while status == COMPRESSION_STATUS_OK
compression_stream_destroy(&stream)
if status == COMPRESSION_STATUS_END {
return decompressedData as Data
} else {
print("Unzipping failed")
return nil
}
}
static func uncompressWithFileBytes(_ cdir: NKAR_CentralDirectory, fromBytes bytes: UnsafePointer<UInt8>) -> Data? {
let len = Int(cdir.uncompressedSize)
let out = UnsafeMutablePointer<UInt8>.allocate(capacity: len)
switch cdir.compressionMethod {
case .none:
out.assign(from: UnsafeMutablePointer<UInt8>(mutating: bytes), count: len)
case .deflate:
let streamPtr = UnsafeMutablePointer<compression_stream>.allocate(capacity: 1)
var stream = streamPtr.pointee
var status : compression_status
let op : compression_stream_operation = COMPRESSION_STREAM_DECODE
let flags : Int32 = 0
let algorithm : compression_algorithm = Compression.COMPRESSION_ZLIB
status = compression_stream_init(&stream, op, algorithm)
guard status != COMPRESSION_STATUS_ERROR else {
// an error occurred
return nil
}
// setup the stream's source
stream.src_ptr = bytes
stream.src_size = Int(cdir.compressedSize)
stream.dst_ptr = out
stream.dst_size = len
repeat {
status = compression_stream_process(&stream, flags)
switch status {
case COMPRESSION_STATUS_OK:
// do nothing
break
case COMPRESSION_STATUS_END:
break
case COMPRESSION_STATUS_ERROR:
print("Unexpected error in stream when uncompressing nkar")
default:
break
}
}
while status == COMPRESSION_STATUS_OK
compression_stream_destroy(&stream)
}
return Data(bytesNoCopy: UnsafeMutablePointer<UInt8>(out), count: len, deallocator: .free)
}
static func uncompressWithCentralDirectory(_ cdir: NKAR_CentralDirectory, fromBytes bytes: UnsafePointer<UInt8>) -> Data? {
let offsetBytes = bytes.advanced(by: Int(cdir.dataOffset))
let offsetMBytes = UnsafeMutablePointer<UInt8>(mutating: offsetBytes)
let len = Int(cdir.uncompressedSize)
let out = UnsafeMutablePointer<UInt8>.allocate(capacity: len)
switch cdir.compressionMethod {
case .none:
out.assign(from: offsetMBytes, count: len)
case .deflate:
let streamPtr = UnsafeMutablePointer<compression_stream>.allocate(capacity: 1)
var stream = streamPtr.pointee
var status : compression_status
let op : compression_stream_operation = COMPRESSION_STREAM_DECODE
let flags : Int32 = 0
let algorithm : compression_algorithm = Compression.COMPRESSION_ZLIB
status = compression_stream_init(&stream, op, algorithm)
guard status != COMPRESSION_STATUS_ERROR else {
// an error occurred
return nil
}
// setup the stream's source
stream.src_ptr = UnsafePointer<UInt8>(offsetMBytes)
stream.src_size = Int(cdir.compressedSize)
stream.dst_ptr = out
stream.dst_size = len
status = compression_stream_process(&stream, flags)
switch status.rawValue {
case COMPRESSION_STATUS_END.rawValue:
// OK
break
case COMPRESSION_STATUS_OK.rawValue:
print("Unexpected end of stream")
return nil
case COMPRESSION_STATUS_ERROR.rawValue:
print("Unexpected error in stream")
return nil
default:
break
}
compression_stream_destroy(&stream)
}
return Data(bytesNoCopy: UnsafeMutablePointer<UInt8>(out), count: len, deallocator: .free)
}
}
| apache-2.0 | 1fa32c82749562d8edd2c8fdae8b16a1 | 34.818584 | 127 | 0.505621 | 6.072768 | false | false | false | false |
renyufei8023/WeiBo | weibo/Classes/Me/Controller/MeTableViewController.swift | 1 | 3138 | //
// MeTableViewController.swift
// weibo
//
// Created by 任玉飞 on 16/4/25.
// Copyright © 2016年 任玉飞. All rights reserved.
//
import UIKit
class MeTableViewController: BaseTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
if !userLogin
{
visitorView?.setupVisitorInfo(false, imageName: "visitordiscover_image_profile", message: "登录后,你的微博、相册、个人资料会显示在这里,展示给别人")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 2b17cc31bf92dfd4a34b506a3fe3cc83 | 31.62766 | 157 | 0.676883 | 5.371278 | false | false | false | false |
polkahq/PLKSwift | Sources/polka/ui/PLKAlert.swift | 1 | 1869 | //
// PLKAlert.swift
//
// Created by Alvaro Talavera on 4/18/16.
// Copyright © 2016 Polka. All rights reserved.
//
import UIKit
public class PLKAlert: NSObject {
public static func showAlert(title:String, message:String, controller:UIViewController) {
let alert:UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
DispatchQueue.main.async {
controller.present(alert, animated: true, completion: nil)
}
}
public static func showError(message:String, controller:UIViewController) {
self.showAlert(title: "Error", message: message, controller: controller)
}
static private var loader:UIAlertController?
public static func loaderShow(controller:UIViewController) {
if(self.loader == nil) {
self.loader = UIAlertController(title: " ", message: nil, preferredStyle: .alert)
let indicator = UIActivityIndicatorView(frame: self.loader!.view.bounds)
indicator.activityIndicatorViewStyle = .whiteLarge
indicator.color = UIColor.black
indicator.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.loader!.view.addSubview(indicator)
indicator.isUserInteractionEnabled = false
indicator.startAnimating()
}
DispatchQueue.main.async {
controller.present(self.loader!, animated: true, completion: nil)
}
}
public static func loaderHide() {
if(self.loader != nil) {
DispatchQueue.main.async {
self.loader!.dismiss(animated: true, completion: nil)
self.loader = nil
}
}
}
}
| mit | 381e922114e4f2ded8879136a583dd58 | 31.77193 | 111 | 0.619914 | 4.954907 | false | false | false | false |
GabrielGhe/HackTheNorth | NoteCopy/NoteCopy/Agent.swift | 1 | 6237 | //
// Agent.swift
// Agent
//
// Created by Christoffer Hallas on 6/2/14.
// Copyright (c) 2014 Christoffer Hallas. All rights reserved.
//
import Foundation
import UIKit
class Agent {
typealias Headers = Dictionary<String, String>
typealias Data = AnyObject!
typealias Response = (NSHTTPURLResponse!, Data!, NSError!) -> Void
/**
* Members
*/
var request: NSMutableURLRequest
let queue = NSOperationQueue()
/**
* Initialize
*/
init(method: String, url: String, headers: Headers?) {
self.request = NSMutableURLRequest(URL: NSURL(string: url))
self.request.HTTPMethod = method;
if (headers != nil) {
self.request.allHTTPHeaderFields = headers!
}
}
/**
* GET
*/
class func get(url: String) -> Agent {
return Agent(method: "GET", url: url, headers: nil)
}
class func get(url: String, headers: Headers) -> Agent {
return Agent(method: "GET", url: url, headers: headers)
}
class func get(url: String, done: Response) -> Agent {
return Agent.get(url).end(done)
}
class func get(url: String, headers: Headers, done: Response) -> Agent {
return Agent.get(url, headers: headers).end(done)
}
/**
* POST
*/
class func post(url: String) -> Agent {
return Agent(method: "POST", url: url, headers: nil)
}
class func post(url: String, headers: Headers) -> Agent {
return Agent(method: "POST", url: url, headers: headers)
}
class func post(url: String, done: Response) -> Agent {
return Agent.post(url).end(done)
}
class func post(url: String, headers: Headers, data: Data) -> Agent {
return Agent.post(url, headers: headers).send(data)
}
class func post(url: String, data: Data) -> Agent {
return Agent.post(url).send(data)
}
class func post(url: String, data: Data, done: Response) -> Agent {
return Agent.post(url, data: data).send(data).end(done)
}
class func post(url: String, headers: Headers, data: Data, done: Response) -> Agent {
return Agent.post(url, headers: headers, data: data).send(data).end(done)
}
/**
* PUT
*/
class func put(url: String) -> Agent {
return Agent(method: "PUT", url: url, headers: nil)
}
class func put(url: String, headers: Headers) -> Agent {
return Agent(method: "PUT", url: url, headers: headers)
}
class func put(url: String, done: Response) -> Agent {
return Agent.put(url).end(done)
}
class func put(url: String, headers: Headers, data: Data) -> Agent {
return Agent.put(url, headers: headers).send(data)
}
class func put(url: String, data: Data) -> Agent {
return Agent.put(url).send(data)
}
class func put(url: String, data: Data, done: Response) -> Agent {
return Agent.put(url, data: data).send(data).end(done)
}
class func put(url: String, headers: Headers, data: Data, done: Response) -> Agent {
return Agent.put(url, headers: headers, data: data).send(data).end(done)
}
/**
* DELETE
*/
class func delete(url: String) -> Agent {
return Agent(method: "DELETE", url: url, headers: nil)
}
class func delete(url: String, headers: Headers) -> Agent {
return Agent(method: "DELETE", url: url, headers: headers)
}
class func delete(url: String, done: Response) -> Agent {
return Agent.delete(url).end(done)
}
class func delete(url: String, headers: Headers, done: Response) -> Agent {
return Agent.delete(url, headers: headers).end(done)
}
/**
* Methods
*/
func send(data: Data) -> Agent {
var error: NSError?
let json = NSJSONSerialization.dataWithJSONObject(data, options: nil, error: &error)
self.set("Content-Type", value: "application/json")
self.request.HTTPBody = json
return self
}
func attachImage(named: String, withBoundry: String = "---------------------------14737809831466499882746641449" ) -> Agent {
let image = UIImage(named: named)
let imageContent = UIImagePNGRepresentation(image)
if let imageData = imageContent {
// set Content-Type in HTTP header
let boundaryConstant = withBoundry;
self.request.addValue("multipart/form-data; boundary=\(boundaryConstant)", forHTTPHeaderField: "Content-Type")
// create body
var body = NSMutableData()
body.appendData( ("--\(boundaryConstant)\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData( ("Content-Disposition: attachment; name=\"file\"; filename=\"\(named).png\"\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData( ("Content-Type: application/octet-stream\r\n\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSData(data: imageData))
body.appendData( ("\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData( ("--\(boundaryConstant)--\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
self.request.HTTPBody = body
}
return self
}
func set(header: String, value: String) -> Agent {
self.request.setValue(value, forHTTPHeaderField: header)
return self
}
func end(done: Response) -> Agent {
let completion = { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
let res = response as NSHTTPURLResponse!
if (error != nil) {
println(error)
return
}
var error: NSError?
var textData = NSString(data: data, encoding: NSUTF8StringEncoding)
done(res, textData, error)
}
NSURLConnection.sendAsynchronousRequest(self.request, queue: self.queue, completionHandler: completion)
return self
}
} | mit | 0c81e639bfde4cdc355d19514929e56b | 30.826531 | 164 | 0.589065 | 4.237092 | false | false | false | false |
StanZabroda/Hydra | Pods/Nuke/Nuke/Source/Core/ImageDataLoader.swift | 10 | 4659 | // The MIT License (MIT)
//
// Copyright (c) 2015 Alexander Grebenyuk (github.com/kean).
import UIKit
// MARK: ImageDataLoading
public typealias ImageDataLoadingCompletionHandler = (data: NSData?, response: NSURLResponse?, error: ErrorType?) -> Void
public typealias ImageDataLoadingProgressHandler = (completedUnitCount: Int64, totalUnitCount: Int64) -> Void
public protocol ImageDataLoading {
/** Compares two requests for equivalence with regard to loading image data. Requests should be considered equivalent if the image fetcher can handle both requests with a single data task.
*/
func isRequestLoadEquivalent(lhs: ImageRequest, toRequest rhs: ImageRequest) -> Bool
/** Compares two requests for equivalence with regard to caching image data. ImageManager uses this method for memory caching only, which means that there is no need for filtering out the dynamic part of the request (is there is any).
*/
func isRequestCacheEquivalent(lhs: ImageRequest, toRequest rhs: ImageRequest) -> Bool
/** Creates image data task with a given url
*/
func imageDataTaskWithURL(url: NSURL, progressHandler: ImageDataLoadingProgressHandler, completionHandler: ImageDataLoadingCompletionHandler) -> NSURLSessionDataTask
/** Invalidates the receiver
*/
func invalidate()
func removeAllCachedImages()
}
// MARK: ImageDataLoader
public class ImageDataLoader: NSObject, NSURLSessionDataDelegate, ImageDataLoading {
public private(set) var session: NSURLSession!
private var taskHandlers = [NSURLSessionTask: URLSessionDataTaskHandler]()
private let queue = dispatch_queue_create("ImageDataLoader-InternalSerialQueue", DISPATCH_QUEUE_SERIAL)
public init(sessionConfiguration: NSURLSessionConfiguration) {
super.init()
self.session = NSURLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)
}
public convenience override init() {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.URLCache = NSURLCache(memoryCapacity: 0, diskCapacity: 200 * 1024 * 1024, diskPath: "com.github.kean.nuke-image-cache")
configuration.timeoutIntervalForRequest = 60.0
configuration.timeoutIntervalForResource = 360.0
self.init(sessionConfiguration: configuration)
}
// MARK: ImageDataLoading
public func isRequestLoadEquivalent(lhs: ImageRequest, toRequest rhs: ImageRequest) -> Bool {
return lhs.URL.isEqual(rhs.URL)
}
public func isRequestCacheEquivalent(lhs: ImageRequest, toRequest rhs: ImageRequest) -> Bool {
return lhs.URL.isEqual(rhs.URL)
}
public func imageDataTaskWithURL(URL: NSURL, progressHandler: ImageDataLoadingProgressHandler, completionHandler: ImageDataLoadingCompletionHandler) -> NSURLSessionDataTask {
let dataTask = self.session.dataTaskWithURL(URL)
dispatch_sync(self.queue) {
self.taskHandlers[dataTask] = URLSessionDataTaskHandler(progressHandler: progressHandler, completionHandler: completionHandler)
}
return dataTask
}
public func invalidate() {
self.session.invalidateAndCancel()
}
public func removeAllCachedImages() {
self.session.configuration.URLCache?.removeAllCachedResponses()
}
// MARK: NSURLSessionDataDelegate
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
dispatch_sync(self.queue) {
if let handler = self.taskHandlers[dataTask] {
handler.data.appendData(data)
handler.progressHandler(completedUnitCount: dataTask.countOfBytesReceived, totalUnitCount: dataTask.countOfBytesExpectedToReceive)
}
}
}
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
dispatch_sync(self.queue) {
if let handler = self.taskHandlers[task] {
handler.completionHandler(data: handler.data, response: task.response, error: error)
self.taskHandlers[task] = nil
}
}
}
}
private class URLSessionDataTaskHandler {
let data = NSMutableData()
let progressHandler: ImageDataLoadingProgressHandler
let completionHandler: ImageDataLoadingCompletionHandler
init(progressHandler: ImageDataLoadingProgressHandler, completionHandler: ImageDataLoadingCompletionHandler) {
self.progressHandler = progressHandler
self.completionHandler = completionHandler
}
}
| mit | be4beee84885d21f9737b7117af9e44b | 41.743119 | 239 | 0.725263 | 5.674787 | false | true | false | false |
OpenKitten/MongoKitten | Sources/MongoKitten/GridFS/GridFSFileWriter.swift | 2 | 3917 | import Foundation
import NIO
public final class GridFSFileWriter {
static let allocator = ByteBufferAllocator()
static let encoder = BSONEncoder()
let fs: GridFSBucket
let fileId: Primitive
let chunkSize: Int32
var buffer: ByteBuffer
var nextChunkNumber = 0
var length: Int
var finalized = false
public init(toBucket fs: GridFSBucket, fileId: Primitive = ObjectId(), chunkSize: Int32 = GridFSBucket.defaultChunkSize) {
self.fs = fs
self.fileId = fileId
self.chunkSize = chunkSize
self.buffer = GridFSFileWriter.allocator.buffer(capacity: Int(chunkSize))
self.length = self.buffer.readableBytes
}
internal init(fs: GridFSBucket, fileId: Primitive = ObjectId(), chunkSize: Int32 = GridFSBucket.defaultChunkSize, buffer: ByteBuffer? = nil) {
self.fs = fs
self.fileId = fileId
self.chunkSize = chunkSize
self.buffer = buffer ?? GridFSFileWriter.allocator.buffer(capacity: Int(chunkSize))
self.length = self.buffer.readableBytes
}
public func write(data: ByteBuffer) -> EventLoopFuture<Void> {
assert(self.finalized == false, "Writing to a finalized writer is an error")
self.length += data.readableBytes
var source = data
buffer.writeBuffer(&source)
guard buffer.readableBytes >= chunkSize else {
return fs.eventLoop.makeSucceededFuture(())
}
return self.flush()
}
public func finalize(filename: String? = nil, metadata: Document? = nil) -> EventLoopFuture<GridFSFile> {
assert(self.finalized == false, "Finalizing a finalized writer is an error")
self.finalized = true
return self.flush(finalize: true).flatMap {
let file = GridFSFile(
id: self.fileId,
length: self.length,
chunkSize: self.chunkSize,
metadata: metadata,
filename: filename,
fs: self.fs
)
do {
let encoded = try GridFSFileWriter.encoder.encode(file)
return self.fs.filesCollection.insert(encoded).map { _ in
return file
}
} catch {
return self.fs.eventLoop.makeFailedFuture(error)
}
}._mongoHop(to: fs.filesCollection.hoppedEventLoop)
}
public func flush(finalize: Bool = false) -> EventLoopFuture<Void> {
let chunkSize = Int(self.chunkSize) // comparison here is always to int
guard buffer.readableBytes > 0, finalize || buffer.readableBytes >= chunkSize else {
return fs.eventLoop.makeSucceededFuture(())._mongoHop(to: fs.filesCollection.hoppedEventLoop)
}
guard let slice = buffer.readSlice(length: buffer.readableBytes >= chunkSize ? chunkSize : buffer.readableBytes) else {
return fs.eventLoop.makeFailedFuture(MongoKittenError(.invalidGridFSChunk, reason: nil))._mongoHop(to: fs.filesCollection.hoppedEventLoop)
}
do {
let chunk = GridFSChunk(filesId: fileId, sequenceNumber: nextChunkNumber, data: .init(buffer: slice))
nextChunkNumber += 1
let encoded = try GridFSFileWriter.encoder.encode(chunk)
return fs.chunksCollection.insert(encoded).flatMap { _ in
return self.flush(finalize: finalize)
}
} catch {
return fs.eventLoop.makeFailedFuture(error)._mongoHop(to: fs.filesCollection.hoppedEventLoop)
}
}
deinit {
assert(finalized == true || length == 0, "A GridFS FileWriter was deinitialized, while the writing has not been finalized. This will cause orphan chunks in the chunks collection in GridFS.")
}
}
| mit | 1a848c87d535eae16b730ba45916f50e | 38.17 | 198 | 0.612459 | 5.015365 | false | false | false | false |
wdkk/CAIM | Metal/answer/caimmetal07_earth_A/basic/DrawingViewController.swift | 1 | 4584 | //
// DrawingViewController.swift
// CAIM Project
// https://kengolab.net/CreApp/wiki/
//
// Copyright (c) Watanabe-DENKI Inc.
// https://wdkk.co.jp/
//
// This software is released under the MIT License.
// https://opensource.org/licenses/mit-license.php
//
import Metal
import simd
// 1頂点情報の構造体(VertexDescriptorを使うため、CAIMMetalVertexFormatterプロトコルを使用する)
struct Vertex : CAIMMetalVertexFormatter {
var pos:Float2 = Float2()
var rgba:Float4 = Float4()
// CAIMMetalVertexFormatterで作成を義務付けられる関数: 構造体の型と同じ型をformats: [...]のなかで指定していく
static func vertexDescriptor(at idx: Int) -> MTLVertexDescriptor {
return makeVertexDescriptor(at: idx, formats: [.float2, .float4])
}
}
struct Uniform : CAIMMetalBufferAllocatable {
var modelMatrix:Matrix4x4 = .identity
}
struct SharedUniform : CAIMMetalBufferAllocatable {
var viewMatrix:Matrix4x4 = .identity
var projectionMatrix:Matrix4x4 = .identity
}
// CAIM-Metalを使うビューコントローラ
class DrawingViewController : CAIMViewController
{
private var metal_view:CAIMMetalView? // Metalビュー
private var pipeline_3d = CAIMMetalRenderPipeline()
private var shared_uniform = SharedUniform()
private var uniform = Uniform()
private var mesh = CAIMMetalMesh.sphere(at: 0)
private var texture = CAIMMetalTexture(with:"earth.jpg")
// 準備関数
override func setup() {
super.setup()
// Metalを使うビューを作成してViewControllerに追加
metal_view = CAIMMetalView( frame: view.bounds )
metal_view?.clearColor = CAIMColor(R: 0.88, G: 0.88, B: 0.88, A: 1.0)
self.view.addSubview( metal_view! )
// 3D描画の準備
setup3D()
}
private func setup3D() {
// パイプライン作成
pipeline_3d.make {
// シェーダを指定
$0.vertexShader = CAIMMetalShader( "vert3d" )
$0.fragmentShader = CAIMMetalShader( "frag3d" )
// 頂点をどのように使うのかを設定
$0.vertexDesc = CAIMMetalMesh.defaultVertexDesc( at: 0 )
// 合成設定
$0.colorAttachment.composite(type: .alphaBlend )
}
}
// 繰り返し処理関数
var move:Float = 0.0
// 繰り返し処理関数
override func update() {
super.update()
let aspect = Float( metal_view!.pixelBounds.width / metal_view!.pixelBounds.height )
let trans = Matrix4x4.translate(0.0, 0.0, 0.0)
let rotate_y = Matrix4x4.rotateY(byAngle: move.toRadian)
move += 0.5
uniform.modelMatrix = trans * rotate_y
shared_uniform.viewMatrix = Matrix4x4.translate(0.0, 0.0, -5.0)
shared_uniform.projectionMatrix = Matrix4x4.perspective(aspect: aspect, fieldOfViewY: 60.0, near: 0.01, far: 1000.0)
// MetalViewのレンダリングを実行
metal_view?.execute( renderFunc: self.render )
}
// Metalで実際に描画を指示する関数
func render( encoder:MTLRenderCommandEncoder ) {
// エンコーダにカリングの設定
encoder.setCullMode( .front )
// エンコーダにデプスの設定
let depth_desc = MTLDepthStencilDescriptor()
// デプスを有効にする
depth_desc.depthCompareFunction = .less
depth_desc.isDepthWriteEnabled = true
encoder.setDepthStencilDescriptor( depth_desc )
// 準備したpipeline_3dを使って、描画を開始(クロージャの$0は引数省略表記。$0 = encoder)
encoder.use( pipeline_3d ) {
// 頂点シェーダのバッファ1番に行列uniformをセット
$0.setVertexBuffer( uniform, index:1 )
// 頂点シェーダのバッファ2番にユニフォーム行列shared_uniformをセット
$0.setVertexBuffer( shared_uniform, index:2 )
// フラグメントシェーダのサンプラ0番にデフォルトのサンプラを設定
$0.setFragmentSamplerState( CAIMMetalSampler.default, index:0 )
// フラグメントシェーダのテクスチャ0番にtextureを設定
$0.setFragmentTexture( texture.metalTexture, index:0 )
// メッシュデータ群の頂点をバッファ0番にセットし描画を実行
$0.drawShape( mesh, index:0 )
}
}
}
| mit | 619b599c4cdd8e39089fb02812b08f30 | 31.605042 | 124 | 0.636082 | 3.470483 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/ArticleScrolling.swift | 1 | 6440 | import Foundation
protocol ArticleScrolling: AnyObject {
/// Used to wait for the callback that the anchor is ready for scrollin'
typealias ScrollToAnchorCompletion = (_ anchor: String, _ rect: CGRect) -> Void
var webView: WKWebView { get }
var messagingController: ArticleWebMessagingController { get }
var scrollToAnchorCompletions: [ScrollToAnchorCompletion] { get set }
var scrollViewAnimationCompletions: [() -> Void] { get set }
}
extension ArticleScrolling where Self: ViewController {
/// Must set `webView.scrollView.delegate = self` in `viewDidLoad`, as it is not permitted to override functions in extensions.
// There is also some related code in ViewController.scrollViewDidEndScrollingAnimation
// It's a tad hacky, but we need to call something on it and the function can't be overridden here.
/// Scroll to a given offset in the article
///
/// - Parameters:
/// - anchor: The anchor to scroll to. The anchor corresponds to an `id` attribute on a HTML tag in the article.
/// - centered: If this parameter is true, the element will be centered in the visible area of the article view after scrolling. If this parameter is false, theelement will be at the top of the visible area of the article view.
/// - animated: Whether or not to animate the scroll change.
/// - completion: A completion that is called when the scroll change is complete. The Boolean pased into the completion is `true` if the point was successfully found and scrolled to or `false` if the point was invalid.
func scroll(to anchor: String, centered: Bool = false, highlighted: Bool = false, animated: Bool, completion: ((Bool) -> Void)? = nil) {
guard !anchor.isEmpty else {
webView.scrollView.scrollRectToVisible(CGRect(x: 0, y: 1, width: 1, height: 1), animated: animated)
completion?(true)
return
}
messagingController.prepareForScroll(to: anchor, highlight: highlighted) { (result) in
assert(Thread.isMainThread)
switch result {
case .failure(let error):
self.showError(error)
completion?(false)
case .success:
// The actual scroll happens via a callback event from the WebView
// When that event is received, the scrollToAnchorCompletion is called
let scrollCompletion: ScrollToAnchorCompletion = { (anchor, rect) in
let point = CGPoint(x: self.webView.scrollView.contentOffset.x, y: rect.origin.y + self.webView.scrollView.contentOffset.y)
self.scroll(to: point, centered: centered, animated: animated, completion: completion)
}
self.scrollToAnchorCompletions.insert(scrollCompletion, at: 0)
}
}
}
/// Scroll to a given offset in the article
/// - Parameters:
/// - offset: The content offset point to scroll to.
/// - centered: If this parameter is true, the content offset point will be centered in the visible area of the article view after scrolling. If this parameter is false, the content offset point will be at the top of the visible area of the article view.
/// - animated: Whether or not to animate the scroll change.
/// - completion: A completion that is called when the scroll change is complete. The Boolean pased into the completion is `true` if the point was successfully found and scrolled to or `false` if the point was invalid.
func scroll(to offset: CGPoint, centered: Bool = false, animated: Bool, completion: ((Bool) -> Void)? = nil) {
assert(Thread.isMainThread)
let scrollView = webView.scrollView
guard !offset.x.isNaN && !offset.x.isInfinite && !offset.y.isNaN && !offset.y.isInfinite else {
completion?(false)
return
}
let overlayTop = self.webView.yOffsetHack + self.navigationBar.hiddenHeight
let adjustmentY: CGFloat
if centered {
let overlayBottom = self.webView.scrollView.contentInset.bottom
let height = self.webView.scrollView.bounds.height
adjustmentY = -0.5 * (height - overlayTop - overlayBottom)
} else {
adjustmentY = overlayTop
}
let minYScrollPoint = 0 - scrollView.contentInset.top
let largestY = scrollView.contentSize.height + scrollView.contentInset.bottom
/// If there is less than one screen of content, do not let this number be negative, to ensure the ranges below are valid.
let maxYScrollPoint = max(largestY - scrollView.bounds.height, 0)
/// If y lies within the last screen, scroll should be to the final full screen.
let yContentPoint = offset.y + adjustmentY
let y = (maxYScrollPoint...largestY).contains(yContentPoint) ? maxYScrollPoint : yContentPoint
guard (minYScrollPoint...maxYScrollPoint).contains(y) else {
completion?(false)
return
}
let boundedOffset = CGPoint(x: scrollView.contentOffset.x, y: y)
guard WMFDistanceBetweenPoints(boundedOffset, scrollView.contentOffset) >= 2 else {
scrollView.flashScrollIndicators()
completion?(true)
return
}
guard animated else {
scrollView.setContentOffset(boundedOffset, animated: false)
completion?(true)
return
}
/*
Setting scrollView.contentOffset inside of an animation block
results in a broken animation https://phabricator.wikimedia.org/T232689
Calling [scrollView setContentOffset:offset animated:YES] inside
of an animation block fixes the animation but doesn't guarantee
the content offset will be updated when the animation's completion
block is called.
It appears the only reliable way to get a callback after the default
animation is to use scrollViewDidEndScrollingAnimation
*/
scrollViewAnimationCompletions.insert({ completion?(true) }, at: 0)
scrollView.setContentOffset(boundedOffset, animated: true)
}
func isBoundingClientRectVisible(_ rect: CGRect) -> Bool {
let scrollView = webView.scrollView
return rect.minY > scrollView.contentInset.top && rect.maxY < scrollView.bounds.size.height - scrollView.contentInset.bottom
}
}
| mit | 74ad80b2d04f902a858f55f5c1c54c8b | 54.517241 | 260 | 0.670652 | 4.916031 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.