repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
SVKorosteleva/heartRateMonitor | HeartMonitor/HeartMonitor/TrainingsListViewController.swift | 1 | 2402 | //
// TrainingsListViewController.swift
// HeartMonitor
//
// Created by Светлана Коростелёва on 9/22/17.
// Copyright © 2017 home. All rights reserved.
//
import UIKit
class TrainingsListViewController: UIViewController {
@IBOutlet private weak var tableView: UITableView!
private var trainings: [Training] = []
override func viewDidLoad() {
super.viewDidLoad()
title = "Trainings"
trainings = DataStorageManager.shared.trainingsManager?.trainings() ?? []
trainings = trainings.filter { $0.duration > 0 }
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let cell = sender as? UITableViewCell,
let indexPath = tableView.indexPath(for: cell),
let trainingDataVC = segue.destination as? TrainingDataViewController else {
return
}
tableView.deselectRow(at: indexPath, animated: true)
trainingDataVC.training = trainings[indexPath.row]
}
}
extension TrainingsListViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return trainings.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell =
tableView.dequeueReusableCell(withIdentifier: "TrainingCell", for: indexPath)
cell.textLabel?.textColor = UIColor(red: 107.0 / 255.0,
green: 160.0 / 255.0,
blue: 232.0 / 255.0,
alpha: 1.0)
let training = trainings[indexPath.row]
cell.textLabel?.text =
"\(TrainingDataSource.text(forDate: training.dateTimeStart ?? Date())), " +
"\(TrainingDataSource.text(forTimeInSeconds: UInt32(training.duration)))"
return cell
}
}
extension TrainingsListViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView,
heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
}
| mit |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Services/AtomicAuthenticationService.swift | 2 | 1980 | import AutomatticTracks
import Foundation
import WordPressKit
class AtomicAuthenticationService {
let remote: AtomicAuthenticationServiceRemote
fileprivate let context = ContextManager.sharedInstance().mainContext
init(remote: AtomicAuthenticationServiceRemote) {
self.remote = remote
}
convenience init(account: WPAccount) {
let wpComRestApi = account.wordPressComRestV2Api
let remote = AtomicAuthenticationServiceRemote(wordPressComRestApi: wpComRestApi)
self.init(remote: remote)
}
func getAuthCookie(
siteID: Int,
success: @escaping (_ cookie: HTTPCookie) -> Void,
failure: @escaping (Error) -> Void) {
remote.getAuthCookie(siteID: siteID, success: success, failure: failure)
}
func loadAuthCookies(
into cookieJar: CookieJar,
username: String,
siteID: Int,
success: @escaping () -> Void,
failure: @escaping (Error) -> Void) {
cookieJar.hasWordPressComAuthCookie(
username: username,
atomicSite: true) { hasCookie in
guard !hasCookie else {
success()
return
}
self.getAuthCookie(siteID: siteID, success: { cookies in
cookieJar.setCookies([cookies]) {
success()
}
}) { error in
// Make sure this error scenario isn't silently ignored.
WordPressAppDelegate.crashLogging?.logError(error)
// Even if getting the auth cookies fail, we'll still try to load the URL
// so that the user sees a reasonable error situation on screen.
// We could opt to create a special screen but for now I'd rather users report
// the issue when it happens.
failure(error)
}
}
}
}
| gpl-2.0 |
pixelmaid/DynamicBrushes | swift/Palette-Knife/models/behavior/State.swift | 1 | 4944 | //
// State.swift
// PaletteKnife
//
// Created by JENNIFER MARY JACOBS on 7/20/16.
// Copyright © 2016 pixelmaid. All rights reserved.
//
import Foundation
class State {
var transitions = [String:StateTransition]()
var constraint_mappings = [String:Constraint]()
let name: String
let id: String
init(id:String,name:String){
self.id = id;
self.name = name;
}
func addConstraintMapping(key:String, reference:Observable<Float>, relativeProperty:Observable<Float>, type:String){
let mapping = Constraint(id:key,reference: reference, relativeProperty:relativeProperty,type:type)
constraint_mappings[key] = mapping;
}
func removeAllConstraintMappings(brush:Brush){
for (key,_) in constraint_mappings{
_ = removeConstraintMapping(key:key,brush:brush);
}
}
func removeAllTransitions()->[StateTransition]{
var removed = [StateTransition]();
for (key,_) in transitions{
removed.append(removeTransitionMapping(key:key)!);
}
return removed;
}
func removeConstraintMapping(key:String, brush:Brush)->Constraint?{
constraint_mappings[key]!.relativeProperty.constrained = false;
constraint_mappings[key]!.reference.unsubscribe(id:brush.id);
constraint_mappings[key]!.reference.didChange.removeHandler(key:key)
constraint_mappings[key]!.relativeProperty.constraintTarget = nil;
return constraint_mappings.removeValue(forKey: key)
}
func addStateTransitionMapping(id:String, name:String, reference:Emitter,toStateId:String)->StateTransition{
let mapping = StateTransition(id:id, name:name, reference:reference,toStateId:toStateId)
transitions[id] = mapping;
return mapping;
}
func removeTransitionMapping(key:String)->StateTransition?{
return transitions.removeValue(forKey: key)
}
func getConstraintMapping(key:String)->Constraint?{
if let _ = constraint_mappings[key] {
return constraint_mappings[key]
}
else {
return nil
}
}
func getTransitionMapping(key:String)->StateTransition?{
if let _ = transitions[key] {
return transitions[key]
}
else {
return nil
}
}
func hasTransitionKey(key:String)->Bool{
if(transitions[key] != nil){
return true
}
return false
}
func hasConstraintKey(key:String)->Bool{
if(constraint_mappings[key] != nil){
return true
}
return false
}
func toJSON()->String{
var data = "{\"id\":\""+(self.id)+"\","
data += "\"name\":\""+self.name+"\","
data += "\"mappings\":[";
var count = 0;
for (_, mapping) in constraint_mappings{
if(count>0){
data += ","
}
data += mapping.toJSON();
count += 1;
}
data += "]"
data += "}"
return data;
}
}
struct Constraint{
var reference:Observable<Float>
var relativeProperty:Observable<Float>
var id:String
var type:String
init(id:String, reference:Observable<Float>, relativeProperty:Observable<Float>,type:String){
self.reference = reference
self.relativeProperty = relativeProperty
self.id = id;
self.type = type; //should be active or passive
}
func toJSON()->String{
let data = "{\"id\":\""+(self.id)+"\"}"
return data;
}
}
class Method{
var name: String;
var id: String;
var arguments: [Any]?
init(id:String,name:String,arguments:[Any]?){
self.name = name;
self.id = id;
self.arguments = arguments;
}
func toJSON()->String{
var data = "{\"id\":\""+(self.id)+"\","
data += "\"name\":\""+(self.name)+"\"}"
return data;
}
}
class StateTransition{
var reference:Emitter
var toStateId: String
var methods = [Method]()
let name: String
let id: String
init(id:String, name:String, reference:Emitter, toStateId:String){
self.reference = reference
self.toStateId = toStateId
self.name = name
self.id = id;
}
func addMethod(id:String, name:String, arguments:[Any]?){
methods.append(Method(id:id, name:name,arguments:arguments));
}
func toJSON()->String{
var data = "{\"id\":\""+(self.id)+"\","
data += "\"name\":\""+self.name+"\","
data += "\"methods\":[";
for i in 0..<methods.count{
if(i>0){
data += ","
}
data += methods[i].toJSON();
}
data += "]"
data += "}"
return data;
}
}
| mit |
realm/SwiftLint | Source/SwiftLintFramework/Rules/Metrics/LargeTupleRuleExamples.swift | 1 | 3464 | struct LargeTupleRuleExamples {
static let nonTriggeringExamples: [Example] = [
Example("let foo: (Int, Int)\n"),
Example("let foo: (start: Int, end: Int)\n"),
Example("let foo: (Int, (Int, String))\n"),
Example("func foo() -> (Int, Int)\n"),
Example("func foo() -> (Int, Int) {}\n"),
Example("func foo(bar: String) -> (Int, Int)\n"),
Example("func foo(bar: String) -> (Int, Int) {}\n"),
Example("func foo() throws -> (Int, Int)\n"),
Example("func foo() throws -> (Int, Int) {}\n"),
Example("let foo: (Int, Int, Int) -> Void\n"),
Example("let foo: (Int, Int, Int) throws -> Void\n"),
Example("func foo(bar: (Int, String, Float) -> Void)\n"),
Example("func foo(bar: (Int, String, Float) throws -> Void)\n"),
Example("var completionHandler: ((_ data: Data?, _ resp: URLResponse?, _ e: NSError?) -> Void)!\n"),
Example("func getDictionaryAndInt() -> (Dictionary<Int, String>, Int)?\n"),
Example("func getGenericTypeAndInt() -> (Type<Int, String, Float>, Int)?\n"),
Example("func foo() async -> (Int, Int)\n"),
Example("func foo() async -> (Int, Int) {}\n"),
Example("func foo(bar: String) async -> (Int, Int)\n"),
Example("func foo(bar: String) async -> (Int, Int) {}\n"),
Example("func foo() async throws -> (Int, Int)\n"),
Example("func foo() async throws -> (Int, Int) {}\n"),
Example("let foo: (Int, Int, Int) async -> Void\n"),
Example("let foo: (Int, Int, Int) async throws -> Void\n"),
Example("func foo(bar: (Int, String, Float) async -> Void)\n"),
Example("func foo(bar: (Int, String, Float) async throws -> Void)\n"),
Example("func getDictionaryAndInt() async -> (Dictionary<Int, String>, Int)?\n"),
Example("func getGenericTypeAndInt() async -> (Type<Int, String, Float>, Int)?\n")
]
static let triggeringExamples: [Example] = [
Example("let foo: ↓(Int, Int, Int)\n"),
Example("let foo: ↓(start: Int, end: Int, value: String)\n"),
Example("let foo: (Int, ↓(Int, Int, Int))\n"),
Example("func foo(bar: ↓(Int, Int, Int))\n"),
Example("func foo() -> ↓(Int, Int, Int)\n"),
Example("func foo() -> ↓(Int, Int, Int) {}\n"),
Example("func foo(bar: String) -> ↓(Int, Int, Int)\n"),
Example("func foo(bar: String) -> ↓(Int, Int, Int) {}\n"),
Example("func foo() throws -> ↓(Int, Int, Int)\n"),
Example("func foo() throws -> ↓(Int, Int, Int) {}\n"),
Example("func foo() throws -> ↓(Int, ↓(String, String, String), Int) {}\n"),
Example("func getDictionaryAndInt() -> (Dictionary<Int, ↓(String, String, String)>, Int)?\n"),
Example("func foo(bar: ↓(Int, Int, Int)) async\n"),
Example("func foo() async -> ↓(Int, Int, Int)\n"),
Example("func foo() async -> ↓(Int, Int, Int) {}\n"),
Example("func foo(bar: String) async -> ↓(Int, Int, Int)\n"),
Example("func foo(bar: String) async -> ↓(Int, Int, Int) {}\n"),
Example("func foo() async throws -> ↓(Int, Int, Int)\n"),
Example("func foo() async throws -> ↓(Int, Int, Int) {}\n"),
Example("func foo() async throws -> ↓(Int, ↓(String, String, String), Int) {}\n"),
Example("func getDictionaryAndInt() async -> (Dictionary<Int, ↓(String, String, String)>, Int)?\n")
]
}
| mit |
tingting-anne/WebEditor | WebEditor/Classes/WebEditorToolBar.swift | 1 | 2138 | //
// WebEditorToolBar.swift
// WebEditor
//
// Created by liutingting on 16/7/12.
// Copyright (c) 2016 liutingting. All rights reserved.
//
import Foundation
import SnapKit
public class WebEditorToolBar: UIView {
public var leading: CGFloat = 15
public var trailing: CGFloat = 15
public var itemSpacing: CGFloat = 15
public var items: [WebEditorToolItem] = [] {
didSet {
for value in oldValue {
value.removeFromSuperview()
}
updateItems()
}
}
private let containerView = UIScrollView()
override init(frame: CGRect) {
super.init(frame: frame)
containerView.bounces = false
containerView.showsHorizontalScrollIndicator = false
self.addSubview(containerView)
containerView.snp.makeConstraints() {make in
make.edges.equalTo(self)
}
let lineView = UIView()
lineView.backgroundColor = UIColor(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 1)
self.addSubview(lineView)
lineView.snp.makeConstraints() {make in
make.height.equalTo(0.5)
make.leading.equalTo(self)
make.trailing.equalTo(self)
make.top.equalTo(self)
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func updateItems() {
let width: CGFloat = items.reduce(0) {sum, new in
return sum + new.itemSize.width + itemSpacing
}
containerView.contentSize.width = width - itemSpacing + leading + trailing
var leadingOffset = leading
for value in items {
containerView.addSubview(value)
value.snp.makeConstraints() {make in
make.leading.equalTo(containerView).offset(leadingOffset)
make.size.equalTo(value.itemSize)
make.centerY.equalTo(containerView)
}
leadingOffset += value.itemSize.width + itemSpacing
}
}
}
| mit |
openHPI/xikolo-ios | WidgetExtension/Extensions/Color+appColors.swift | 1 | 346 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import SwiftUI
extension Color {
static let appPrimary: Color = {
guard let primaryUIColor = UIColor(named: "primary", in: Bundle.appBundle, compatibleWith: nil) else { return .gray }
return Color(primaryUIColor)
}()
}
| gpl-3.0 |
qiuncheng/for-graduation | SpeechRecognition/Helper/String+Speech.swift | 1 | 1006 | //
// String+Speed.swift
// SpeedRecognition
//
// Created by yolo on 2017/3/20.
// Copyright © 2017年 Qiun Cheng. All rights reserved.
//
import UIKit
extension String {
func getHeight(maxWidth width: CGFloat, font: UIFont) -> CGFloat {
return self.boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: [.usesFontLeading, .usesLineFragmentOrigin], attributes: [NSFontAttributeName: font], context: nil).height
}
func getWidth(maxHeight height: CGFloat, font: UIFont) -> CGFloat {
return self.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: height), options: [.usesFontLeading, .usesLineFragmentOrigin], attributes: [NSFontAttributeName: font], context: nil).width
}
mutating func replace(withStr str: String, for forStr: String) -> String {
if let range = range(of: forStr) {
let result = replacingCharacters(in: range, with: str)
return result
}
else {
return self
}
}
}
| apache-2.0 |
bourvill/HydraKit | HydraKit/Classes/URLRequest.swift | 1 | 185 | //
// URLRequest.swift
// HydraKit
//
// Created by maxime marinel on 26/06/2017.
//
import Foundation
extension URLRequest {
enum HttpMethod: String {
case POST
}
}
| mit |
PopcornTimeTV/PopcornTimeTV | PopcornTime/UI/tvOS/Views/LoadExternalTorrentViewController.swift | 1 | 6397 |
import Foundation
import GCDWebServer
import PopcornKit
class LoadExternalTorrentViewController:UIViewController,GCDWebServerDelegate,PCTPlayerViewControllerDelegate,UIViewControllerTransitioningDelegate{
@IBOutlet var infoLabel:UITextView!
var webserver:GCDWebServer!
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.tabBarController?.tabBar.isHidden = true
if webserver == nil {
webserver=GCDWebServer()
webserver?.addGETHandler(forBasePath: "/", directoryPath: Bundle.main.path(forResource: "torrent_upload", ofType: "")!, indexFilename: "index.html", cacheAge: 3600, allowRangeRequests: false) // serve the website located in Supporting Files/torrent_upload when we receive a GET request for /
webserver?.addHandler(forMethod: "GET", path: "/torrent", request: GCDWebServerRequest.self, processBlock: {request in
let magnetLink = request.query?["link"]!.removingPercentEncoding ?? ""// get magnet link that is inserted as a link tag from the website
DispatchQueue.main.async {
let userTorrent = Torrent.init(health: .excellent, url: magnetLink, quality: "1080p", seeds: 100, peers: 100, size: nil)
var title = magnetLink
if let startIndex = title.range(of: "dn="){
title = String(title[startIndex.upperBound...])
title = String(title[title.startIndex ... title.range(of: "&tr")!.lowerBound])
}
let magnetTorrentMedia = Movie.init(title: title, id: "34", tmdbId: nil, slug: "magnet-link", summary: "", torrents: [userTorrent], subtitles: [:], largeBackgroundImage: nil, largeCoverImage: nil)
let storyboard = UIStoryboard.main
let loadingViewController = storyboard.instantiateViewController(withIdentifier: "PreloadTorrentViewController") as! PreloadTorrentViewController
loadingViewController.transitioningDelegate = self
loadingViewController.loadView()
loadingViewController.titleLabel.text = magnetLink
self.present(loadingViewController, animated: true)
//Movie completion Blocks
let error: (String) -> Void = { (errorMessage) in
if self.presentedViewController != nil {
self.dismiss(animated: false)
}
let vc = UIAlertController(title: "Error".localized, message: errorMessage, preferredStyle: .alert)
vc.addAction(UIAlertAction(title: "OK".localized, style: .cancel, handler: nil))
self.present(vc, animated: true)
}
let finishedLoading: (PreloadTorrentViewController, UIViewController) -> Void = { (loadingVc, playerVc) in
let flag = UIDevice.current.userInterfaceIdiom != .tv
self.dismiss(animated: flag)
self.present(playerVc, animated: flag)
}
let selectTorrent: (Array<String>) -> Int32 = { (torrents) in
var selected = -1
let torrentSelection = UIAlertController(title: "Select file to play".localized, message: nil, preferredStyle: .alert)
for torrent in torrents{
torrentSelection.addAction(UIAlertAction(title: torrent, style: .default, handler: { _ in
selected = torrents.firstIndex(of: torrent) ?? -1
}))
}
DispatchQueue.main.sync{
torrentSelection.show(animated: true)
}
while selected == -1{ print("hold") }
return Int32(selected)
}
//Movie player view controller calls
let playViewController = storyboard.instantiateViewController(withIdentifier: "PCTPlayerViewController") as! PCTPlayerViewController
playViewController.delegate = self
magnetTorrentMedia.play(fromFileOrMagnetLink: magnetLink, nextEpisodeInSeries: nil, loadingViewController: loadingViewController, playViewController: playViewController, progress: 0, errorBlock: error, finishedLoadingBlock: finishedLoading, selectingTorrentBlock: selectTorrent)
}// start to stream the new movie asynchronously as we do not want to mess the web server response
return GCDWebServerDataResponse(statusCode:200)
})//handle the request that returns the magnet link
}
super.viewWillAppear(true)
webserver?.start(withPort: 54320, bonjourName: "popcorn")
infoLabel.text = .localizedStringWithFormat("Please navigate to the webpage %@ and insert the magnet link of the torrent you would like to play".localized, webserver?.serverURL?.absoluteString ?? "")
}
@IBAction func exitView(_ sender: Any) {
self.navigationController?.pop(animated: true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
if webserver != nil {
webserver.stop()
webserver = nil
}
}
// MARK: - Presentation
dynamic func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if presented is PreloadTorrentViewController {
return PreloadTorrentViewControllerAnimatedTransitioning(isPresenting: true)
}
return nil
}
dynamic func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if dismissed is PreloadTorrentViewController {
return PreloadTorrentViewControllerAnimatedTransitioning(isPresenting: false)
}
return nil
}
}
| gpl-3.0 |
LibraryLoupe/PhotosPlus | PhotosPlus/Cameras/Canon/Canon5D.swift | 3 | 483 | //
// Photos Plus, https://github.com/LibraryLoupe/PhotosPlus
//
// Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved.
//
import Foundation
extension Cameras.Manufacturers.Canon {
public struct EOS5D: CameraModel {
public init() {}
public let name = "Canon EOS 5D"
public let manufacturerType: CameraManufacturer.Type = Cameras.Manufacturers.Canon.self
}
}
public typealias Canon5D = Cameras.Manufacturers.Canon.EOS5D
| mit |
SusanDoggie/Doggie | Sources/DoggieGraphics/ColorPixel/RGB/BGRA32ColorPixel.swift | 1 | 1590 | //
// BGRA32ColorPixel.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
@frozen
public struct BGRA32ColorPixel: _RGBColorPixel {
public var b: UInt8
public var g: UInt8
public var r: UInt8
public var a: UInt8
@inlinable
@inline(__always)
public init(red: UInt8, green: UInt8, blue: UInt8, opacity: UInt8 = 0xFF) {
self.r = red
self.g = green
self.b = blue
self.a = opacity
}
}
| mit |
taufikobet/Fusuma | Sources/FSVideoCameraView.swift | 1 | 19287 | //
// FSVideoCameraView.swift
// Fusuma
//
// Created by Brendan Kirchner on 3/18/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import AVFoundation
import MZTimerLabel
import CoreMotion
@objc protocol FSVideoCameraViewDelegate: class {
func videoFinished(withFileURL fileURL: URL)
}
final class FSVideoCameraView: UIView {
@IBOutlet weak var previewViewContainer: UIView!
@IBOutlet weak var shotButton: CameraButton!
@IBOutlet weak var flashButton: UIButton!
@IBOutlet weak var flipButton: UIButton!
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var recordIndicator: UIView!
@IBOutlet weak var placeholderTopConstraint: NSLayoutConstraint!
@IBOutlet weak var timerLabelTopConstraint: NSLayoutConstraint!
lazy var mzTimerLabel:MZTimerLabel = MZTimerLabel(label: self.timerLabel, andTimerType: MZTimerLabelTypeStopWatch)
weak var delegate: FSVideoCameraViewDelegate? = nil
var session: AVCaptureSession?
var device: AVCaptureDevice?
var audioDevice: AVCaptureDevice?
var videoInput: AVCaptureDeviceInput?
var audioInput: AVCaptureDeviceInput?
var videoOutput: AVCaptureMovieFileOutput?
var focusView: UIView?
var flashOffImage: UIImage?
var flashOnImage: UIImage?
var videoStartImage: UIImage?
var videoStopImage: UIImage?
let motionManager: CMMotionManager = CMMotionManager()
var videoOrientation:UIInterfaceOrientation = .portrait
fileprivate var isRecording = false
static func instance() -> FSVideoCameraView {
return UINib(nibName: "FSVideoCameraView", bundle: Bundle(for: self.classForCoder())).instantiate(withOwner: self, options: nil)[0] as! FSVideoCameraView
}
func initialize() {
if session != nil {
return
}
self.backgroundColor = fusumaBackgroundColor
self.isHidden = false
// AVCapture
session = AVCaptureSession()
session?.sessionPreset = AVCaptureSessionPreset640x480
for device in AVCaptureDevice.devices() {
if let device = device as? AVCaptureDevice , device.position == AVCaptureDevicePosition.back {
self.device = device
}
}
for device in AVCaptureDevice.devices(withMediaType: AVMediaTypeAudio) {
if let device = device as? AVCaptureDevice {
self.audioDevice = device
}
}
do {
if let session = session {
videoInput = try AVCaptureDeviceInput(device: device)
audioInput = try AVCaptureDeviceInput(device: audioDevice)
session.addInput(videoInput)
session.addInput(audioInput)
videoOutput = AVCaptureMovieFileOutput()
let totalSeconds = 60.0 //Total Seconds of capture time
let timeScale: Int32 = 30 //FPS
let maxDuration = CMTimeMakeWithSeconds(totalSeconds, timeScale)
videoOutput?.maxRecordedDuration = maxDuration
videoOutput?.minFreeDiskSpaceLimit = 1024 * 1024 //SET MIN FREE SPACE IN BYTES FOR RECORDING TO CONTINUE ON A VOLUME
if session.canAddOutput(videoOutput) {
session.addOutput(videoOutput)
}
let videoLayer = AVCaptureVideoPreviewLayer(session: session)
videoLayer?.frame = self.previewViewContainer.bounds
videoLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
self.previewViewContainer.layer.addSublayer(videoLayer!)
session.startRunning()
}
// Focus View
self.focusView = UIView(frame: CGRect(x: 0, y: 0, width: 90, height: 90))
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(FSVideoCameraView.focus(_:)))
self.previewViewContainer.addGestureRecognizer(tapRecognizer)
} catch {
}
let bundle = Bundle(for: self.classForCoder)
flashOnImage = fusumaFlashOnImage != nil ? fusumaFlashOnImage : UIImage(named: "ic_flash_on", in: bundle, compatibleWith: nil)
flashOffImage = fusumaFlashOffImage != nil ? fusumaFlashOffImage : UIImage(named: "ic_flash_off", in: bundle, compatibleWith: nil)
let flipImage = fusumaFlipImage != nil ? fusumaFlipImage : UIImage(named: "ic_loop", in: bundle, compatibleWith: nil)
videoStartImage = fusumaVideoStartImage != nil ? fusumaVideoStartImage : UIImage(named: "video_button", in: bundle, compatibleWith: nil)
videoStopImage = fusumaVideoStopImage != nil ? fusumaVideoStopImage : UIImage(named: "video_button_rec", in: bundle, compatibleWith: nil)
if(fusumaTintIcons) {
flashButton.tintColor = fusumaBaseTintColor
flipButton.tintColor = fusumaBaseTintColor
flashButton.setImage(flashOffImage?.withRenderingMode(.alwaysTemplate), for: UIControlState())
flipButton.setImage(flipImage?.withRenderingMode(.alwaysTemplate), for: UIControlState())
} else {
flashButton.setImage(flashOffImage, for: UIControlState())
flipButton.setImage(flipImage, for: UIControlState())
}
flashConfiguration()
}
public override func safeAreaInsetsDidChange() {
if #available(iOS 11.0, *) {
super.safeAreaInsetsDidChange()
let topInset = self.safeAreaInsets.top
if topInset > 0 {
placeholderTopConstraint.constant += topInset
timerLabelTopConstraint.constant += topInset
}
}
}
func setupMotionManager() {
motionManager.deviceMotionUpdateInterval = 5.0
if motionManager.isAccelerometerAvailable {
let queue = OperationQueue.main
motionManager.startAccelerometerUpdates(to: queue, withHandler: {
[weak self] data, error in
guard let data = data else {
return
}
let angle = (atan2(data.acceleration.y,data.acceleration.x))*180/M_PI
//print(angle)
if (fabs(angle)<=45) {
self?.videoOrientation = .landscapeLeft
}
else if ((fabs(angle)>45)&&(fabs(angle)<135)) {
if(angle>0){
self?.videoOrientation = .portraitUpsideDown
} else {
self?.videoOrientation = .portrait
}
} else {
self?.videoOrientation = .landscapeRight
}
})
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func startCamera() {
let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
if status == AVAuthorizationStatus.authorized {
session?.startRunning()
setupMotionManager()
} else if status == AVAuthorizationStatus.denied || status == AVAuthorizationStatus.restricted {
session?.stopRunning()
stopMotionManager()
}
}
func stopCamera() {
if self.isRecording {
self.toggleRecording()
}
session?.stopRunning()
stopMotionManager()
}
@IBAction func shotButtonPressed(_ sender: UIButton) {
self.toggleRecording()
if self.isRecording {
stopMotionManager()
}
}
func stopMotionManager() {
motionManager.stopDeviceMotionUpdates()
motionManager.stopAccelerometerUpdates()
}
func startAnimatingRecordIndicator() {
recordIndicator.isHidden = false
UIView.animate(withDuration: 0.75, delay: 0.0, options: .repeat, animations: {
self.recordIndicator.alpha = 0.0
}, completion: nil)
}
func stopAnimatingRecordIndicator() {
recordIndicator.layer.removeAllAnimations()
recordIndicator.isHidden = true
}
fileprivate func toggleRecording() {
guard let videoOutput = videoOutput else {
return
}
self.isRecording = !self.isRecording
let shotImage: UIImage?
if self.isRecording {
shotImage = videoStopImage
mzTimerLabel.start()
startAnimatingRecordIndicator()
} else {
shotImage = videoStartImage
mzTimerLabel.pause()
mzTimerLabel.reset()
stopAnimatingRecordIndicator()
}
if self.isRecording {
let outputPath = "\(NSTemporaryDirectory())output.mov"
let outputURL = URL(fileURLWithPath: outputPath)
let fileManager = FileManager.default
if fileManager.fileExists(atPath: outputPath) {
do {
try fileManager.removeItem(atPath: outputPath)
} catch {
print("error removing item at path: \(outputPath)")
self.isRecording = false
return
}
}
self.flipButton.isEnabled = false
self.flashButton.isEnabled = false
videoOutput.startRecording(toOutputFileURL: outputURL, recordingDelegate: self)
} else {
videoOutput.stopRecording()
self.flipButton.isEnabled = true
self.flashButton.isEnabled = true
}
return
}
@IBAction func flipButtonPressed(_ sender: UIButton) {
session?.stopRunning()
do {
session?.beginConfiguration()
if let session = session {
for input in session.inputs {
session.removeInput(input as! AVCaptureInput)
}
let position = (videoInput?.device.position == AVCaptureDevicePosition.front) ? AVCaptureDevicePosition.back : AVCaptureDevicePosition.front
for device in AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) {
if let device = device as? AVCaptureDevice , device.position == position {
videoInput = try AVCaptureDeviceInput(device: device)
session.addInput(videoInput)
}
}
for device in AVCaptureDevice.devices(withMediaType: AVMediaTypeAudio) {
if let device = device as? AVCaptureDevice {
audioInput = try AVCaptureDeviceInput(device: device)
session.addInput(audioInput)
}
}
}
session?.commitConfiguration()
} catch {
}
session?.startRunning()
}
@IBAction func flashButtonPressed(_ sender: UIButton) {
do {
if let device = device {
try device.lockForConfiguration()
if device.hasFlash {
let mode = device.flashMode
if mode == AVCaptureFlashMode.off {
device.flashMode = AVCaptureFlashMode.on
flashButton.setImage(flashOnImage, for: UIControlState())
} else if mode == AVCaptureFlashMode.on {
device.flashMode = AVCaptureFlashMode.off
flashButton.setImage(flashOffImage, for: UIControlState())
}
}
device.unlockForConfiguration()
}
} catch _ {
flashButton.setImage(flashOffImage, for: UIControlState())
return
}
}
}
extension FSVideoCameraView: AVCaptureFileOutputRecordingDelegate {
func capture(_ captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAt fileURL: URL!, fromConnections connections: [Any]!) {
print("started recording to: \(fileURL)")
}
func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) {
print("finished recording to: \(outputFileURL)")
exportVideo(withURL: outputFileURL, orientation: videoOrientation) { (url) in
if let url = url {
self.delegate?.videoFinished(withFileURL: url)
}
}
}
}
extension FSVideoCameraView {
func focus(_ recognizer: UITapGestureRecognizer) {
let point = recognizer.location(in: self)
let viewsize = self.bounds.size
let newPoint = CGPoint(x: point.y/viewsize.height, y: 1.0-point.x/viewsize.width)
let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
do {
try device?.lockForConfiguration()
} catch _ {
return
}
if device?.isFocusModeSupported(AVCaptureFocusMode.autoFocus) == true {
device?.focusMode = AVCaptureFocusMode.autoFocus
device?.focusPointOfInterest = newPoint
}
if device?.isExposureModeSupported(AVCaptureExposureMode.continuousAutoExposure) == true {
device?.exposureMode = AVCaptureExposureMode.continuousAutoExposure
device?.exposurePointOfInterest = newPoint
}
device?.unlockForConfiguration()
self.focusView?.alpha = 0.0
self.focusView?.center = point
self.focusView?.backgroundColor = UIColor.clear
self.focusView?.layer.borderColor = UIColor.white.cgColor
self.focusView?.layer.borderWidth = 1.0
self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.addSubview(self.focusView!)
UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.8,
initialSpringVelocity: 3.0, options: UIViewAnimationOptions.curveEaseIn, // UIViewAnimationOptions.BeginFromCurrentState
animations: {
self.focusView!.alpha = 1.0
self.focusView!.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
}, completion: {(finished) in
self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.focusView!.removeFromSuperview()
})
}
func flashConfiguration() {
do {
if let device = device {
try device.lockForConfiguration()
if device.hasFlash {
device.flashMode = AVCaptureFlashMode.off
flashButton.setImage(flashOffImage, for: UIControlState())
}
device.unlockForConfiguration()
}
} catch _ {
return
}
}
}
extension FSVideoCameraView {
func exportVideo(withURL url: URL, orientation:UIInterfaceOrientation, completionHandler:@escaping (URL?)->()) {
let asset = AVURLAsset(url: url)
let exportSession = SDAVAssetExportSession(asset: asset)!
let outputPath = NSTemporaryDirectory().appending("temp.mov")
if FileManager.default.fileExists(atPath: outputPath) {
try! FileManager.default.removeItem(atPath: outputPath)
}
exportSession.outputURL = URL(fileURLWithPath: outputPath)
exportSession.outputFileType = AVFileTypeQuickTimeMovie
// exportSession.shouldOptimizeForNetworkUse = true
var size:CGSize = CGSize.zero
if let naturalSize = asset.tracks(withMediaType: AVMediaTypeVideo).first?.naturalSize,
let preferredTransform = asset.tracks(withMediaType: AVMediaTypeVideo).first?.preferredTransform
{
size = naturalSize
if isVideoRotated90_270(preferredTransform: preferredTransform) {
let flippedSize:CGSize = size
size.width = flippedSize.height
size.height = flippedSize.width
}
}
exportSession.videoSettings = [
AVVideoCodecKey: AVVideoCodecH264,
AVVideoWidthKey: size.width,
AVVideoHeightKey: size.height,
AVVideoCompressionPropertiesKey: [
AVVideoAverageBitRateKey: 1216000,
AVVideoProfileLevelKey: AVVideoProfileLevelH264High41,
],
]
exportSession.audioSettings = [
AVFormatIDKey: NSNumber(value: Int32(kAudioFormatMPEG4AAC)),
AVNumberOfChannelsKey: 1,
AVSampleRateKey: 44100,
AVEncoderBitRateKey: 64000,
]
exportSession.exportAsynchronously(with: orientation, completionHandler: {
DispatchQueue.main.async {
print(exportSession.status)
switch exportSession.status {
case .cancelled:
print("cancelled")
case .failed:
print("failed")
completionHandler(nil)
case .unknown:
print("unknown")
case .completed:
if let outputURL = exportSession.outputURL {
completionHandler(outputURL)
}
default: break
}
}
})
}
func isVideoRotated90_270(preferredTransform: CGAffineTransform) -> Bool {
var isRotated90_270 = false
let t: CGAffineTransform = preferredTransform
if t.a == 0 && t.b == 1.0 && t.c == -1.0 && t.d == 0 {
isRotated90_270 = true
}
if t.a == 0 && t.b == -1.0 && t.c == 1.0 && t.d == 0 {
isRotated90_270 = true
}
if t.a == 1.0 && t.b == 0 && t.c == 0 && t.d == 1.0 {
isRotated90_270 = false
}
if t.a == -1.0 && t.b == 0 && t.c == 0 && t.d == -1.0 {
isRotated90_270 = false
}
return isRotated90_270
}
}
| mit |
SusanDoggie/Doggie | Sources/DoggieGraphics/ImageCodec/RawBitmap/SlowDecode/_aligned_channel.swift | 1 | 4574 | //
// _aligned_channel.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
extension Image {
@inlinable
@inline(__always)
mutating func _decode_aligned_channel<T: FixedWidthInteger, R: BinaryFloatingPoint>(_ bitmap: RawBitmap, _ channel_idx: Int, _ is_opaque: Bool, _: T.Type, _ : R.Type) {
let width = self.width
let height = self.height
guard bitmap.startsRow < height else { return }
let bytesPerPixel = bitmap.bitsPerPixel >> 3
let channel = bitmap.channels[channel_idx]
let channel_max: R = scalbn(1, T.bitWidth) - 1
let byteOffset = channel.bitRange.lowerBound >> 3
self.withUnsafeMutableTypePunnedBufferPointer(to: R.self) {
guard var dest = $0.baseAddress else { return }
let row = Pixel.numberOfComponents * width
dest += bitmap.startsRow * row
var data = bitmap.data
for _ in bitmap.startsRow..<height {
let _length = min(bitmap.bytesPerRow, data.count)
guard _length != 0 else { return }
data.popFirst(bitmap.bytesPerRow).withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
guard var source = bytes.baseAddress else { return }
var destination = dest
let source_end = source + _length
var predictor_record: T = 0
for _ in 0..<width {
guard source + bytesPerPixel <= source_end else { return }
let _destination = destination + channel.index
let _source = source + byteOffset
let _s: T
let _d: T
switch channel.endianness {
case .big: _s = T(bigEndian: _source.bindMemory(to: T.self, capacity: 1).pointee)
case .little: _s = T(littleEndian: _source.bindMemory(to: T.self, capacity: 1).pointee)
}
switch bitmap.predictor {
case .none: _d = _s
case .subtract: _d = _s &+ predictor_record
}
if T.isSigned {
_destination.pointee = Image._denormalized(channel.index, R(UInt64(bitPattern: Int64(_d) &- Int64(T.min))) / channel_max)
} else {
_destination.pointee = Image._denormalized(channel.index, R(_d) / channel_max)
}
predictor_record = _d
source += bytesPerPixel
if is_opaque {
destination[Pixel.numberOfComponents - 1] = 1
}
destination += Pixel.numberOfComponents
}
dest += row
}
}
}
}
}
| mit |
jeanpimentel/Honour | HonourTests/Library/Rules/ContainsTest.swift | 2 | 1129 | //
// ContainsTest.swift
// Honour
//
// Created by Jean Pimentel on 4/30/15.
// Copyright (c) 2015 Honour. All rights reserved.
//
import XCTest
import Honour
class ContainsTest: XCTestCase {
func testContains() {
XCTAssertTrue(Contains(value: "").validate(""))
XCTAssertTrue(Contains(value: "").validate("foobarbaz"))
XCTAssertTrue(Contains(value: "foo").validate("foobarbaz"))
XCTAssertTrue(Contains(value: "foo").validate("barfoobaz"))
XCTAssertTrue(Contains(value: "foo").validate("barbazfoo"))
XCTAssertTrue(Contains(value: "foo", caseSensitive: true).validate("foobarbaz"))
XCTAssertTrue(Contains(value: "foo", caseSensitive: false).validate("FOObarbaz"))
XCTAssertTrue(Contains("").validate(""))
XCTAssertTrue(Contains("foo", caseSensitive: true).validate("foobarbaz"))
}
func testNonContains() {
XCTAssertFalse(Contains(value: "foo").validate(""))
XCTAssertFalse(Contains(value: "foo").validate("faaborboz"))
XCTAssertFalse(Contains(value: "foo", caseSensitive: true).validate("FOObarbaz"))
}
}
| mit |
IvanVorobei/TwitterLaunchAnimation | TwitterLaunchAnimation - project/TwitterLaucnhAnimation/sparrow/ui/views/views/SPIconView.swift | 1 | 1206 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei (hello@ivanvorobei.by)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
class SPIconView: UIView {
}
| mit |
garynewby/GLNPianoView | Example/Example/FasciaView.swift | 1 | 807 | //
// FasciaView.swift
// Example
//
// Created by Gary Newby on 14/08/2020.
//
import UIKit
class FasciaView: UIView {
private lazy var fasciaLayer: CAGradientLayer = {
let layer = CAGradientLayer()
layer.frame = bounds
layer.colors = [UIColor.darkGray.cgColor, UIColor.lightGray.cgColor, UIColor.black.cgColor]
layer.startPoint = CGPoint(x: 0.0, y: 0.92)
layer.endPoint = CGPoint(x: 0.0, y: 1.0)
return layer
}()
override init(frame: CGRect) {
super.init(frame: frame)
layer.insertSublayer(fasciaLayer, at: 0)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
layer.insertSublayer(fasciaLayer, at: 0)
}
override func layoutSubviews() {
fasciaLayer.frame = bounds
}
}
| mit |
Zewo/SQL | Sources/SQL/Query/Insert.swift | 2 | 702 | public struct Insert {
public let valuesByField: [QualifiedField: Value?]
public let tableName: String
public init(_ tableName: String, values: [QualifiedField: Value?]) {
self.tableName = tableName
self.valuesByField = values
}
public init(_ tableName: String, values: [QualifiedField: ValueConvertible?]) {
var transformed = [QualifiedField: Value?]()
for (key, value) in values {
transformed[key] = value?.sqlValue
}
self.init(tableName, values: transformed)
}
}
extension Insert: StatementParameterListConvertible {
public var sqlParameters: [Value?] {
return Array(valuesByField.values)
}
}
| mit |
peterdruska/GPSwift | GPSwiftTests/GPSwiftTests.swift | 1 | 901 | //
// GPSwiftTests.swift
// GPSwiftTests
//
// Created by Peter Druska on 11.3.2015.
// Copyright (c) 2015 Become.sk. All rights reserved.
//
import UIKit
import XCTest
class GPSwiftTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| gpl-2.0 |
Lugia123/XMIDI | Source/XMidi/AppDelegate.swift | 1 | 2134 | //
// AppDelegate.swift
// XMidi
//
// Created by Lugia on 15/3/14.
// Copyright (c) 2015年 Freedom. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
vicentearana/Como_Doro | Como_Doro/Como_Doro/Trabajar.swift | 1 | 839 | //
// Trabajar.swift
// Como_Doro
//
// Created by on 7/1/16.
// Copyright © 2016 Egibide. All rights reserved.
//
import UIKit
class Trabajar: UIViewController {
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: - 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.
}
*/
}
| gpl-2.0 |
FengDeng/SwiftNet | SwiftNetDemo/SwiftNetDemo/AppDelegate.swift | 1 | 2142 | //
// AppDelegate.swift
// SwiftNetDemo
//
// Created by 邓锋 on 16/2/29.
// Copyright © 2016年 fengdeng. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
february29/Learning | swift/Fch_Contact/Pods/RxCocoa/RxCocoa/iOS/UIStepper+Rx.swift | 8 | 600 | //
// UIStepper+Rx.swift
// RxCocoa
//
// Created by Yuta ToKoRo on 9/1/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS)
import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif
extension Reactive where Base: UIStepper {
/// Reactive wrapper for `value` property.
public var value: ControlProperty<Double> {
return base.rx.controlPropertyWithDefaultEvents(
getter: { stepper in
stepper.value
}, setter: { stepper, value in
stepper.value = value
}
)
}
}
#endif
| mit |
eCrowdMedia/MooApi | Sources/model/StoreModel/StoreFooter.swift | 1 | 402 | //
// StoreFooter.swift
// TestAPI
//
// Created by Apple on 2017/11/22.
// Copyright © 2017年 Apple. All rights reserved.
//
import Foundation
import Foundation
public struct StoreFooter: Codable, StoreDataProtocal {
public enum CodingKeys: String, CodingKey {
case title = "title"
case page = "page"
}
public let title: String
public let page: StoreDataBasePageItem
}
| mit |
vincentherrmann/multilinear-math | Package.swift | 1 | 150 | import PackageDescription
let package = Package(name: "MultilinearMath",
targets: [],
dependencies: [])
| apache-2.0 |
cweatureapps/SwiftScraper | Pods/Observable-Swift/Observable-Swift/OwningEventReference.swift | 2 | 1674 | //
// OwningEventReference.swift
// Observable-Swift
//
// Created by Leszek Ślażyński on 28/06/14.
// Copyright (c) 2014 Leszek Ślażyński. All rights reserved.
//
/// A subclass of event reference allowing it to own other object[s].
/// Additionally, the reference makes added events own itself.
/// This retain cycle allows owned objects to live as long as valid subscriptions exist.
public class OwningEventReference<T>: EventReference<T> {
internal var owned: AnyObject? = nil
public override func add(_ subscription: SubscriptionType) -> SubscriptionType {
let subscr = super.add(subscription)
if owned != nil {
subscr.addOwnedObject(self)
}
return subscr
}
public override func add(_ handler: @escaping (T) -> ()) -> EventSubscription<T> {
let subscr = super.add(handler)
if owned != nil {
subscr.addOwnedObject(self)
}
return subscr
}
public override func remove(_ subscription: SubscriptionType) {
subscription.removeOwnedObject(self)
super.remove(subscription)
}
public override func removeAll() {
for subscription in event.subscriptions {
subscription.removeOwnedObject(self)
}
super.removeAll()
}
public override func add(owner: AnyObject, _ handler: @escaping HandlerType) -> SubscriptionType {
let subscr = super.add(owner: owner, handler)
if owned != nil {
subscr.addOwnedObject(self)
}
return subscr
}
public override init(event: Event<T>) {
super.init(event: event)
}
}
| mit |
natmark/ProcessingKit | ProcessingKit/ProcessingView+Core/ProcessingView+Image.swift | 1 | 918 | //
// ProcessingView+Image.swift
// ProcessingKit
//
// Created by AtsuyaSato on 2018/09/09.
// Copyright © 2018年 Atsuya Sato. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
#elseif os(OSX)
import Cocoa
#endif
extension ProcessingView: ImageModelContract {
#if os(iOS)
public func image(_ img: UIImage, _ x: CGFloat, _ y: CGFloat) {
self.imageModel.image(img, x, y)
}
public func image(_ img: UIImage, _ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) {
self.imageModel.image(img, x, y, width, height)
}
#elseif os(OSX)
public func drawImage(_ img: NSImage, _ x: CGFloat, _ y: CGFloat) {
self.imageModel.drawImage(img, x, y)
}
public func drawImage(_ img: NSImage, _ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) {
self.imageModel.drawImage(img, x, y, width, height)
}
#endif
}
| mit |
CaiMiao/CGSSGuide | DereGuide/Extension/UIColorExtension.swift | 1 | 3064 | //
// UIColorExtension.swift
// DereGuide
//
// Created by zzk on 2017/1/4.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
import DynamicColor
extension UIColor {
static let border = UIColor.lightGray
static let background = UIColor(hexString: "E2E2E2")
static let vocal = UIColor(red: 1.0 * 236 / 255, green: 1.0 * 87 / 255, blue: 1.0 * 105 / 255, alpha: 1)
static let dance = UIColor(red: 1.0 * 89 / 255, green: 1.0 * 187 / 255, blue: 1.0 * 219 / 255, alpha: 1)
static let visual = UIColor(red: 1.0 * 254 / 255, green: 1.0 * 154 / 255, blue: 1.0 * 66 / 255, alpha: 1)
static let life = UIColor(red: 1.0 * 75 / 255, green: 1.0 * 202 / 255, blue: 1.0 * 137 / 255, alpha: 1)
static let debut = UIColor(red: 1.0 * 138 / 255, green: 1.0 * 206 / 255, blue: 1.0 * 233 / 255, alpha: 1)
static let regular = UIColor(red: 1.0 * 253 / 255, green: 1.0 * 164 / 255, blue: 1.0 * 40 / 255, alpha: 1)
static let pro = UIColor(red: 1.0 * 254 / 255, green: 1.0 * 183 / 255, blue: 1.0 * 194 / 255, alpha: 1)
static let master = UIColor.init(red: 1.0 * 147 / 255, green: 1.0 * 236 / 255, blue: 1.0 * 148 / 255, alpha: 1)
static let masterPlus = UIColor(red: 1.0 * 255 / 255, green: 1.0 * 253 / 255, blue: 1.0 * 114 / 255, alpha: 1)
static let legacyMasterPlus = UIColor.masterPlus.lighter()
static let light = UIColor(hexString: "E1F3A6")
static let trick = UIColor(hexString: "E1B9F7")
static let cute = UIColor(red: 1.0 * 248 / 255, green: 1.0 * 24 / 255, blue: 1.0 * 117 / 255, alpha: 1)
static let cool = UIColor(red: 1.0 * 42 / 255, green: 1.0 * 113 / 255, blue: 1.0 * 247 / 255, alpha: 1)
static let passion = UIColor(red: 1.0 * 250 / 255, green: 1.0 * 168 / 255, blue: 1.0 * 57 / 255, alpha: 1)
static let parade = UIColor(red: 1.0 * 22 / 255, green: 1.0 * 87 / 255, blue: 1.0 * 250 / 255, alpha: 1)
static let kyalapon = UIColor(red: 1.0 * 252 / 255, green: 1.0 * 60 / 255, blue: 1.0 * 169 / 255, alpha: 1)
static let groove = UIColor(red: 1.0 * 238 / 255, green: 1.0 * 175 / 255, blue: 1.0 * 50 / 255, alpha: 1)
static let party = UIColor(red: 1.0 * 89 / 255, green: 1.0 * 192 / 255, blue: 1.0 * 50 / 255, alpha: 1)
static let tradition = UIColor(red: 1.0 * 113 / 255, green: 1.0 * 80 / 255, blue: 1.0 * 69 / 255, alpha: 1)
static let rail = UIColor(hexString: "81CD46")
static let normal = UIColor(red: 1.0 * 253 / 255, green: 1.0 * 186 / 255, blue: 1.0 * 80 / 255, alpha: 1)
static let limited = UIColor(red: 1.0 * 236 / 255, green: 1.0 * 103 / 255, blue: 1.0 * 105 / 255, alpha: 1)
static let cinfes = UIColor(red: 1.0 * 25 / 255, green: 1.0 * 154 / 255, blue: 1.0 * 218 / 255, alpha: 1)
static let flick4 = UIColor(hexString: "3568D5")
static let flick3 = UIColor(hexString: "7CD8AA")
static let slide = UIColor(hexString: "A544D9")
static let tap = UIColor(hexString: "EC6279")
static let hold = UIColor(hexString: "F7CD72")
static let allType = UIColor.darkGray
}
| mit |
Nimbow/Client-iOS | client/client/SmsType.swift | 1 | 203 | //
// SmsType.swift
// client
//
// Created by Awesome Developer on 17/01/16.
// Copyright © 2015 Nimbow. All rights reserved.
//
enum SmsType : String {
case
Gsm,
Unicode,
Binary
} | mit |
AlesTsurko/DNMKit | DNM_iOS/DNMModel_iOSTests/DNMModel_iOSTests.swift | 1 | 993 | //
// DNMModel_iOSTests.swift
// DNMModel_iOSTests
//
// Created by James Bean on 11/21/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import XCTest
@testable import DNMModel_iOS
class DNMModel_iOSTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| gpl-2.0 |
LeeCenY/iRent | Sources/iRent/Model/Room.swift | 1 | 2009 | //
// Room.swift
// iRentPackageDescription
//
// Created by nil on 2018/3/3.
//
import Foundation
struct Room: Codable {
let id: UUID
let state: Bool //是否退房
let room_no: String? //房间号
let rent_money: Int? //租金
let deposit: Int? //押金
let lease_term: Int? //租期
let rent_date: String? //收租日期
let network: Int? //网络
let trash_fee: Int? //垃圾费
let water_max: Int? //水表阈值
let electricity_max: Int? //电表阈值
let create_at: String //创建时间
let updated_at: String //更新时间
let payments: [Payment]?
let tenants: [Tenant]?
public init(state: Bool, room_no: String?, rent_money: Int?, deposit: Int?, lease_term: Int?, rent_date: String?, network: Int?, trash_fee: Int?) {
self.init(state: state, room_no: room_no, rent_money: rent_money, deposit: deposit, lease_term: lease_term, rent_date: rent_date, network: network, trash_fee: trash_fee, water_max: nil, electricity_max: nil)
}
public init(state: Bool, room_no: String?, rent_money: Int?, deposit: Int?, lease_term: Int?, rent_date: String?, network: Int?, trash_fee: Int?, water_max: Int?, electricity_max: Int?) {
self.id = UUID()
self.state = state
self.room_no = room_no
self.rent_money = rent_money
self.deposit = deposit
self.lease_term = lease_term
self.rent_date = rent_date
self.network = network
self.trash_fee = trash_fee
self.water_max = water_max
self.electricity_max = electricity_max
self.create_at = Date().iso8601()
self.updated_at = Date().iso8601()
self.payments = nil
self.tenants = nil
}
}
| mit |
huonw/swift | benchmark/Package.swift | 4 | 2979 | // swift-tools-version:4.0
import PackageDescription
import Foundation
// This is a stop gap hack so we can edit benchmarks in Xcode.
let singleSourceLibraries: [String] = {
let f = FileManager.`default`
let dirURL = URL(fileURLWithPath: "single-source").absoluteURL
let fileURLs = try! f.contentsOfDirectory(at: dirURL,
includingPropertiesForKeys: nil)
return fileURLs.flatMap { (path: URL) -> String? in
let c = path.lastPathComponent.split(separator: ".")
// Too many components. Must be a gyb file.
if c.count > 2 {
return nil
}
if c[1] != "swift" {
return nil
}
// We do not support this test.
if c[0] == "ObjectiveCNoBridgingStubs" {
return nil
}
assert(c[0] != "PrimsSplit")
return String(c[0])
}
}()
let multiSourceLibraries: [String] = {
let f = FileManager.`default`
let dirURL = URL(fileURLWithPath: "multi-source").absoluteURL
let fileURLs = try! f.contentsOfDirectory(at: dirURL,
includingPropertiesForKeys: nil)
return fileURLs.map { (path: URL) -> String in
return path.lastPathComponent
}
}()
let p = Package(
name: "swiftbench",
products: [
.library(name: "TestsUtils", type: .static, targets: ["TestsUtils"]),
.library(name: "DriverUtils", type: .static, targets: ["DriverUtils"]),
.library(name: "ObjectiveCTests", type: .static, targets: ["ObjectiveCTests"]),
.executable(name: "SwiftBench", targets: ["SwiftBench"]),
.library(name: "PrimsSplit", type: .static, targets: ["PrimsSplit"])
] + singleSourceLibraries.map { .library(name: $0, type: .static, targets: [$0]) }
+ multiSourceLibraries.map { .library(name: $0, type: .static, targets: [$0]) },
targets: [
.target(name: "TestsUtils",
path: "utils",
sources: ["TestsUtils.swift"]),
.target(name: "DriverUtils",
dependencies: [.target(name: "TestsUtils")],
path: "utils",
sources: ["DriverUtils.swift", "ArgParse.swift"]),
.target(name: "SwiftBench",
dependencies: [
.target(name: "TestsUtils"),
.target(name: "ObjectiveCTests"),
.target(name: "DriverUtils"),
] + singleSourceLibraries.map { .target(name: $0) }
+ multiSourceLibraries.map { .target(name: $0) },
path: "utils",
sources: ["main.swift"]),
.target(name: "ObjectiveCTests",
path: "utils/ObjectiveCTests",
publicHeadersPath: "."),
] + singleSourceLibraries.map { x in
return .target(name: x,
dependencies: [
.target(name: "TestsUtils"),
.target(name: "ObjectiveCTests"),
],
path: "single-source",
sources: ["\(x).swift"])
} + multiSourceLibraries.map { x in
return .target(name: x,
dependencies: [
.target(name: "TestsUtils")
],
path: "multi-source/\(x)")
},
swiftLanguageVersions: [4]
)
| apache-2.0 |
iosyoujian/Swift-DeviceType | DeviceTypeSample/DeviceTypeSample/ViewController.swift | 2 | 867 | //
// ViewController.swift
// DeviceTypeSample
//
// Created by Ian Hirschfeld on 3/6/15.
// Copyright (c) 2015 Ian Hirschfeld. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
println("UIDevice.currentDevice().deviceType: \(UIDevice.currentDevice().deviceType)")
println("UIDevice.currentDevice().isIPhone: \(UIDevice.currentDevice().isIPhone)")
println("UIDevice.currentDevice().isIPad: \(UIDevice.currentDevice().isIPad)")
println("UIDevice.currentDevice().isSimulator: \(UIDevice.currentDevice().isSimulator)")
println("==========")
println("self.isIPhone6PlusSize: \(self.isIPhone6PlusSize)")
println("self.isIPhone6Size: \(self.isIPhone6Size)")
println("self.isIPhone5sSize: \(self.isIPhone5sSize)")
}
}
| mit |
samwyndham/DictateSRS | DictateSRS/Shared/Attributes.swift | 1 | 2025 | //
// Attributes.swift
// DictateSRS
//
// Created by Sam Wyndham on 23/02/2017.
// Copyright © 2017 Sam Wyndham. All rights reserved.
//
import UIKit
/// A container of `Character Attributes` that can be applied to an
/// `NSAttributedString`.
struct Attributes {
private var textStyle: UIFontTextStyle?
private var _dictionary: [String: Any] = [
NSFontAttributeName: UIFont.systemFont(ofSize: 12),
NSForegroundColorAttributeName: UIColor.black
]
/// Returns a copy of `self` with `NSFontAttributeName` set to `font`.
@discardableResult func settingFont(_ font: UIFont) -> Attributes {
var attributes = self
attributes.textStyle = nil
attributes._dictionary[NSFontAttributeName] = font
return attributes
}
/// Returns a copy of `self` with `NSFontAttributeName` set to the preferred
/// font for `style`.
@discardableResult func settingFont(style: UIFontTextStyle) -> Attributes {
var attributes = self
attributes.textStyle = style
return attributes
}
/// Returns a copy of `self` with `NSForegroundColorAttributeName` set to
/// `color`.
@discardableResult func settingColor(_ color: UIColor) -> Attributes {
var attributes = self
attributes._dictionary[NSForegroundColorAttributeName] = color
return attributes
}
/// A `Dictionary` of all `Character Attributes`.
var dictionary: [String: Any] {
if let textStyle = textStyle {
var attributes = _dictionary
attributes[NSFontAttributeName] = UIFont.preferredFont(forTextStyle: textStyle)
return attributes
} else {
return _dictionary
}
}
/// The font for `NSFontAttributeName`.
var font: UIFont {
if let textStyle = textStyle {
return UIFont.preferredFont(forTextStyle: textStyle)
} else {
return _dictionary[NSFontAttributeName] as! UIFont
}
}
}
| mit |
Jnosh/swift | validation-test/compiler_crashers_fixed/01448-resolvetypedecl.swift | 65 | 462 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class A<T where k.h : a!.c {
}
if true {
protocol b {
func b: A
| apache-2.0 |
StYaphet/firefox-ios | Client/Frontend/Settings/AppSettingsTableViewController.swift | 2 | 7466 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Account
/// App Settings Screen (triggered by tapping the 'Gear' in the Tab Tray Controller)
class AppSettingsTableViewController: SettingsTableViewController {
var showContentBlockerSetting = false
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = NSLocalizedString("Settings", comment: "Title in the settings view controller title bar")
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: NSLocalizedString("Done", comment: "Done button on left side of the Settings view controller title bar"),
style: .done,
target: navigationController, action: #selector((navigationController as! ThemedNavigationController).done))
navigationItem.rightBarButtonItem?.accessibilityIdentifier = "AppSettingsTableViewController.navigationItem.leftBarButtonItem"
tableView.accessibilityIdentifier = "AppSettingsTableViewController.tableView"
// Refresh the user's FxA profile upon viewing settings. This will update their avatar,
// display name, etc.
////profile.rustAccount.refreshProfile()
if showContentBlockerSetting {
let viewController = ContentBlockerSettingViewController(prefs: profile.prefs)
viewController.profile = profile
viewController.tabManager = tabManager
navigationController?.pushViewController(viewController, animated: false)
// Add a done button from this view
viewController.navigationItem.rightBarButtonItem = navigationItem.rightBarButtonItem
}
}
override func generateSettings() -> [SettingSection] {
var settings = [SettingSection]()
let privacyTitle = NSLocalizedString("Privacy", comment: "Privacy section title")
let prefs = profile.prefs
var generalSettings: [Setting] = [
SearchSetting(settings: self),
NewTabPageSetting(settings: self),
HomeSetting(settings: self),
OpenWithSetting(settings: self),
ThemeSetting(settings: self),
BoolSetting(prefs: prefs, prefKey: PrefsKeys.KeyBlockPopups, defaultValue: true,
titleText: NSLocalizedString("Block Pop-up Windows", comment: "Block pop-up windows setting")),
]
if #available(iOS 12.0, *) {
generalSettings.insert(SiriPageSetting(settings: self), at: 5)
}
if AppConstants.MOZ_DOCUMENT_SERVICES {
generalSettings.insert(TranslationSetting(settings: self), at: 6)
}
let accountChinaSyncSetting: [Setting]
if !AppInfo.isChinaEdition {
accountChinaSyncSetting = []
} else {
accountChinaSyncSetting = [
// Show China sync service setting:
ChinaSyncServiceSetting(settings: self)
]
}
// There is nothing to show in the Customize section if we don't include the compact tab layout
// setting on iPad. When more options are added that work on both device types, this logic can
// be changed.
generalSettings += [
BoolSetting(prefs: prefs, prefKey: "showClipboardBar", defaultValue: false,
titleText: Strings.SettingsOfferClipboardBarTitle,
statusText: Strings.SettingsOfferClipboardBarStatus),
BoolSetting(prefs: prefs, prefKey: PrefsKeys.ContextMenuShowLinkPreviews, defaultValue: true,
titleText: Strings.SettingsShowLinkPreviewsTitle,
statusText: Strings.SettingsShowLinkPreviewsStatus)
]
let accountSectionTitle = NSAttributedString(string: Strings.FxAFirefoxAccount)
let footerText = !profile.hasAccount() ? NSAttributedString(string: Strings.FxASyncUsageDetails) : nil
settings += [
SettingSection(title: accountSectionTitle, footerTitle: footerText, children: [
// Without a Firefox Account:
ConnectSetting(settings: self),
AdvancedAccountSetting(settings: self),
// With a Firefox Account:
AccountStatusSetting(settings: self),
SyncNowSetting(settings: self)
] + accountChinaSyncSetting )]
settings += [ SettingSection(title: NSAttributedString(string: Strings.SettingsGeneralSectionTitle), children: generalSettings)]
var privacySettings = [Setting]()
privacySettings.append(LoginsSetting(settings: self, delegate: settingsDelegate))
privacySettings.append(TouchIDPasscodeSetting(settings: self))
privacySettings.append(ClearPrivateDataSetting(settings: self))
privacySettings += [
BoolSetting(prefs: prefs,
prefKey: "settings.closePrivateTabs",
defaultValue: false,
titleText: NSLocalizedString("Close Private Tabs", tableName: "PrivateBrowsing", comment: "Setting for closing private tabs"),
statusText: NSLocalizedString("When Leaving Private Browsing", tableName: "PrivateBrowsing", comment: "Will be displayed in Settings under 'Close Private Tabs'"))
]
privacySettings.append(ContentBlockerSetting(settings: self))
privacySettings += [
PrivacyPolicySetting()
]
settings += [
SettingSection(title: NSAttributedString(string: privacyTitle), children: privacySettings),
SettingSection(title: NSAttributedString(string: NSLocalizedString("Support", comment: "Support section title")), children: [
ShowIntroductionSetting(settings: self),
SendFeedbackSetting(),
SendAnonymousUsageDataSetting(prefs: prefs, delegate: settingsDelegate),
OpenSupportPageSetting(delegate: settingsDelegate),
]),
SettingSection(title: NSAttributedString(string: NSLocalizedString("About", comment: "About settings section title")), children: [
VersionSetting(settings: self),
LicenseAndAcknowledgementsSetting(),
YourRightsSetting(),
ExportBrowserDataSetting(settings: self),
ExportLogDataSetting(settings: self),
DeleteExportedDataSetting(settings: self),
ForceCrashSetting(settings: self),
SlowTheDatabase(settings: self),
ForgetSyncAuthStateDebugSetting(settings: self),
SentryIDSetting(settings: self),
ChangeToChinaSetting(settings: self),
ToggleOnboarding(settings: self),
LeanplumStatus(settings: self),
ShowEtpCoverSheet(settings: self),
ToggleOnboarding(settings: self),
LeanplumStatus(settings: self),
ClearOnboardingABVariables(settings: self)
])]
return settings
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = super.tableView(tableView, viewForHeaderInSection: section) as! ThemedTableSectionHeaderFooterView
return headerView
}
}
| mpl-2.0 |
izeni-team/retrolux | Retrolux/MultipartEncodeable.swift | 1 | 284 | //
// MultipartEncodeable.swift
// Retrolux
//
// Created by Bryan Henderson on 1/26/17.
// Copyright © 2017 Bryan. All rights reserved.
//
import Foundation
public protocol MultipartEncodeable {
static func encode(with arg: BuilderArg, using encoder: MultipartFormData)
}
| mit |
linkedin/LayoutKit | ExampleLayouts/CircleImagePileLayout.swift | 1 | 2090 | // Copyright 2016 LinkedIn Corp.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import UIKit
import LayoutKit
/// Displays a pile of overlapping circular images.
open class CircleImagePileLayout: StackLayout<CircleImagePileView> {
public enum Mode {
case leadingOnTop, trailingOnTop
}
public let mode: Mode
public init(imageNames: [String], mode: Mode = .trailingOnTop, alignment: Alignment = .topLeading, viewReuseId: String? = nil) {
self.mode = mode
let sublayouts: [Layout] = imageNames.map { imageName in
return SizeLayout<UIImageView>(width: 50, height: 50, config: { imageView in
imageView.image = UIImage(named: imageName)
imageView.layer.cornerRadius = 25
imageView.layer.masksToBounds = true
imageView.layer.borderColor = UIColor.white.cgColor
imageView.layer.borderWidth = 2
})
}
super.init(
axis: .horizontal,
spacing: -25,
distribution: .leading,
alignment: alignment,
flexibility: .inflexible,
viewReuseId: viewReuseId,
sublayouts: sublayouts)
}
open override var needsView: Bool {
return super.needsView || mode == .leadingOnTop
}
}
open class CircleImagePileView: UIView {
open override func addSubview(_ view: UIView) {
// Make sure views are inserted below existing views so that the first image in the face pile is on top.
if let lastSubview = subviews.last {
insertSubview(view, belowSubview: lastSubview)
} else {
super.addSubview(view)
}
}
}
| apache-2.0 |
Trevi-Swift/Trevi | Sources/OutgoingMessage.swift | 1 | 810 | //
// HttpStream.swift
// Trevi
//
// Created by LeeYoseob on 2016. 3. 3..
// Copyright © 2016 Trevi Community. All rights reserved.
//
import Foundation
// To be class parents who have the data for processing of response.
public class OutgoingMessage {
public var socket: Socket!
public var connection: Socket!
public var header: [String: String]!
public var shouldKeepAlive = false
public var chunkEncoding = false
public init(socket: AnyObject){
header = [String: String]()
}
deinit{
socket = nil
connection = nil
}
public func _end(data: NSData, encoding: Any! = nil){
self.socket.write(data, handle: self.socket.handle)
if shouldKeepAlive == false {
self.socket.close()
}
}
}
| apache-2.0 |
rain2540/RGAppTools | Sources/RATError.swift | 1 | 199 | //
// RATError.swift
// RGAppTools
//
// Created by RAIN on 2021/7/26.
// Copyright © 2021 Smartech. All rights reserved.
//
import Foundation
public enum RATError: Error {
case initNil
}
| mpl-2.0 |
Rypac/hn | hn/Firebase.swift | 1 | 836 | import Foundation
enum Firebase {
case topStories
case newStories
case bestStories
case showHN
case askHN
case jobs
case updates
case item(Int)
case user(String)
private static let baseURL = URL(string: "https://hacker-news.firebaseio.com/v0")!
var url: URL {
return Firebase.baseURL.appendingPathComponent(path)
}
private var path: String {
switch self {
case .topStories: return "/topstories.json"
case .newStories: return "/newstories.json"
case .bestStories: return "/beststories.json"
case .showHN: return "/showstories.json"
case .askHN: return "/askstories.json"
case .jobs: return "/jobstories.json"
case .updates: return "/updates.json"
case .item(let id): return "/item/\(id).json"
case .user(let username): return "/user/\(username).json"
}
}
}
| mit |
a2/Simon | Simon WatchKit App Extension/HighScoresInterfaceController.swift | 1 | 1205 | import Foundation
import WatchKit
class HighScoresInterfaceController: WKInterfaceController {
let dateFormatter: NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .ShortStyle
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.timeStyle = .NoStyle
return dateFormatter
}()
var scores: [HighScore]!
// MARK: - IBOutlets
@IBOutlet weak var table: WKInterfaceTable!
// MARK: View Life Cycle
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
let box = context as! Box<[HighScore]>
scores = box.value
table.setNumberOfRows(scores.count, withRowType: "highScore")
for (i, highScore) in scores.enumerate() {
let rowController = table.rowControllerAtIndex(i) as! HighScoreController
rowController.scoreLabel.setText(String.localizedStringWithFormat(NSLocalizedString("%d pts.", comment: "Score in points; {score} is replaced with the number of completed rounds"), highScore.score))
rowController.dateLabel.setText(dateFormatter.stringFromDate(highScore.date))
}
}
}
| mit |
omaralbeik/SwifterSwift | Tests/FoundationTests/DateExtensionsTests.swift | 1 | 35661 | //
// DateExtensionsTests.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/27/16.
// Copyright © 2016 SwifterSwift
//
import XCTest
@testable import SwifterSwift
#if canImport(Foundation)
import Foundation
// swiftlint:disable next type_body_length
final class DateExtensionsTests: XCTestCase {
override func setUp() {
super.setUp()
NSTimeZone.default = TimeZone(abbreviation: "UTC")!
}
// swiftlint:disable next cyclomatic_complexity
func testCalendar() {
switch Calendar.current.identifier {
case .buddhist:
XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .buddhist).identifier)
case .chinese:
XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .chinese).identifier)
case .coptic:
XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .coptic).identifier)
case .ethiopicAmeteAlem:
XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .ethiopicAmeteAlem).identifier)
case .ethiopicAmeteMihret:
XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .ethiopicAmeteMihret).identifier)
case .gregorian:
XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .gregorian).identifier)
case .hebrew:
XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .hebrew).identifier)
case .indian:
XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .indian).identifier)
case .islamic:
XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .islamic).identifier)
case .islamicCivil:
XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .islamicCivil).identifier)
case .islamicTabular:
XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .islamicTabular).identifier)
case .islamicUmmAlQura:
XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .islamicUmmAlQura).identifier)
case .iso8601:
XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .iso8601).identifier)
case .japanese:
XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .japanese).identifier)
case .persian:
XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .persian).identifier)
case .republicOfChina:
XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .republicOfChina).identifier)
}
}
func testEra() {
let date = Date(timeIntervalSince1970: 0)
XCTAssertEqual(date.era, 1)
}
func testQuarter() {
let date1 = Date(timeIntervalSince1970: 0)
XCTAssertEqual(date1.quarter, 1)
let date2 = Calendar.current.date(byAdding: .month, value: 4, to: date1)
XCTAssertEqual(date2?.quarter, 2)
let date3 = Calendar.current.date(byAdding: .month, value: 8, to: date1)
XCTAssertEqual(date3?.quarter, 3)
let date4 = Calendar.current.date(byAdding: .month, value: 11, to: date1)
XCTAssertEqual(date4?.quarter, 4)
}
func testWeekOfYear() {
let date = Date(timeIntervalSince1970: 0)
XCTAssertEqual(date.weekOfYear, 1)
let dateAfter7Days = Calendar.current.date(byAdding: .day, value: 7, to: date)
XCTAssertEqual(dateAfter7Days?.weekOfYear, 2)
let originalDate = Calendar.current.date(byAdding: .day, value: -7, to: dateAfter7Days!)
XCTAssertEqual(originalDate?.weekOfYear, 1)
}
func testWeekOfMonth() {
let date = Date(timeIntervalSince1970: 0)
XCTAssertEqual(date.weekOfMonth, 1)
let dateAfter7Days = Calendar.current.date(byAdding: .day, value: 7, to: date)
XCTAssertEqual(dateAfter7Days?.weekOfMonth, 2)
let originalDate = Calendar.current.date(byAdding: .day, value: -7, to: dateAfter7Days!)
XCTAssertEqual(originalDate?.weekOfMonth, 1)
}
func testYear() {
var date = Date(timeIntervalSince1970: 100000.123450040)
XCTAssertEqual(date.year, 1970)
var isLowerComponentsValid: Bool {
guard date.month == 1 else { return false }
guard date.day == 2 else { return false }
guard date.hour == 3 else { return false }
guard date.minute == 46 else { return false }
guard date.second == 40 else { return false }
guard date.nanosecond == 123450040 else { return false }
return true
}
date.year = 2000
XCTAssertEqual(date.year, 2000)
XCTAssert(isLowerComponentsValid)
date.year = 2017
XCTAssertEqual(date.year, 2017)
XCTAssert(isLowerComponentsValid)
date.year = 1988
XCTAssertEqual(date.year, 1988)
XCTAssert(isLowerComponentsValid)
date.year = -100
XCTAssertEqual(date.year, 1988)
XCTAssert(isLowerComponentsValid)
date.year = 0
XCTAssertEqual(date.year, 1988)
XCTAssert(isLowerComponentsValid)
}
func testMonth() {
var date = Date(timeIntervalSince1970: 100000.123450040)
XCTAssertEqual(date.month, 1)
var isLowerComponentsValid: Bool {
guard date.day == 2 else { return false }
guard date.hour == 3 else { return false }
guard date.minute == 46 else { return false }
guard date.second == 40 else { return false }
guard date.nanosecond == 123450040 else { return false }
return true
}
date.month = 2
XCTAssert(isLowerComponentsValid)
date.month = 14
XCTAssertEqual(date.month, 2)
XCTAssert(isLowerComponentsValid)
date.month = 1
XCTAssertEqual(date.month, 1)
XCTAssert(isLowerComponentsValid)
date.month = 0
XCTAssertEqual(date.month, 1)
XCTAssert(isLowerComponentsValid)
date.month = -3
XCTAssertEqual(date.month, 1)
XCTAssert(isLowerComponentsValid)
}
func testDay() {
var date = Date(timeIntervalSince1970: 100000.123450040)
XCTAssertEqual(date.day, 2)
var isLowerComponentsValid: Bool {
guard date.hour == 3 else { return false }
guard date.minute == 46 else { return false }
guard date.second == 40 else { return false }
guard date.nanosecond == 123450040 else { return false }
return true
}
date.day = 4
XCTAssertEqual(date.day, 4)
XCTAssert(isLowerComponentsValid)
date.day = 1
XCTAssertEqual(date.day, 1)
XCTAssert(isLowerComponentsValid)
date.day = 0
XCTAssertEqual(date.day, 1)
XCTAssert(isLowerComponentsValid)
date.day = -3
XCTAssertEqual(date.day, 1)
XCTAssert(isLowerComponentsValid)
date.day = 45
XCTAssertEqual(date.day, 1)
XCTAssert(isLowerComponentsValid)
}
func testWeekday() {
let date = Date(timeIntervalSince1970: 100000)
XCTAssertEqual(date.weekday, 6)
}
func testHour() {
var date = Date(timeIntervalSince1970: 100000.123450040)
XCTAssertEqual(date.hour, 3)
var isLowerComponentsValid: Bool {
guard date.minute == 46 else { return false }
guard date.second == 40 else { return false }
guard date.nanosecond == 123450040 else { return false }
return true
}
date.hour = -3
XCTAssertEqual(date.hour, 3)
XCTAssert(isLowerComponentsValid)
date.hour = 25
XCTAssertEqual(date.hour, 3)
XCTAssert(isLowerComponentsValid)
date.hour = 4
XCTAssertEqual(date.hour, 4)
XCTAssert(isLowerComponentsValid)
date.hour = 1
XCTAssertEqual(date.hour, 1)
XCTAssert(isLowerComponentsValid)
}
func testMinute() {
var date = Date(timeIntervalSince1970: 100000.123450040)
XCTAssertEqual(date.minute, 46)
var isLowerComponentsValid: Bool {
guard date.second == 40 else { return false }
guard date.nanosecond == 123450040 else { return false }
return true
}
date.minute = -3
XCTAssertEqual(date.minute, 46)
XCTAssert(isLowerComponentsValid)
date.minute = 71
XCTAssertEqual(date.minute, 46)
XCTAssert(isLowerComponentsValid)
date.minute = 4
XCTAssertEqual(date.minute, 4)
XCTAssert(isLowerComponentsValid)
date.minute = 1
XCTAssertEqual(date.minute, 1)
XCTAssert(isLowerComponentsValid)
}
func testSecond() {
var date = Date(timeIntervalSince1970: 100000.123450040)
XCTAssertEqual(date.second, 40)
var isLowerComponentsValid: Bool {
guard date.nanosecond == 123450040 else { return false }
return true
}
date.second = -3
XCTAssertEqual(date.second, 40)
XCTAssert(isLowerComponentsValid)
date.second = 71
XCTAssertEqual(date.second, 40)
XCTAssert(isLowerComponentsValid)
date.second = 12
XCTAssertEqual(date.second, 12)
XCTAssert(isLowerComponentsValid)
date.second = 1
XCTAssertEqual(date.second, 1)
XCTAssert(isLowerComponentsValid)
}
func testNanosecond() {
var date = Date(timeIntervalSince1970: 100000.123450040)
XCTAssertEqual(date.nanosecond, 123450040)
date.nanosecond = -3
XCTAssertEqual(date.nanosecond, 123450040)
date.nanosecond = 10000
XCTAssert(date.nanosecond >= 1000)
XCTAssert(date.nanosecond <= 100000)
}
func testMillisecond() {
var date = Date(timeIntervalSince1970: 0)
XCTAssertEqual(date.millisecond, 0)
date.millisecond = -3
XCTAssertEqual(date.millisecond, 0)
date.millisecond = 10
XCTAssert(date.millisecond >= 9)
XCTAssert(date.millisecond <= 11)
date.millisecond = 3
XCTAssert(date.millisecond >= 2)
XCTAssert(date.millisecond <= 4)
}
func testIsInFuture() {
let oldDate = Date(timeIntervalSince1970: 512) // 1970-01-01T00:08:32.000Z
let futureDate = Date(timeIntervalSinceNow: 512)
XCTAssert(futureDate.isInFuture)
XCTAssertFalse(oldDate.isInFuture)
}
func testIsInPast() {
let oldDate = Date(timeIntervalSince1970: 512) // 1970-01-01T00:08:32.000Z
let futureDate = Date(timeIntervalSinceNow: 512)
XCTAssert(oldDate.isInPast)
XCTAssertFalse(futureDate.isInPast)
}
func testIsInToday() {
XCTAssert(Date().isInToday)
let tomorrow = Date().adding(.day, value: 1)
XCTAssertFalse(tomorrow.isInToday)
let yesterday = Date().adding(.day, value: -1)
XCTAssertFalse(yesterday.isInToday)
}
func testIsInYesterday() {
XCTAssertFalse(Date().isInYesterday)
let tomorrow = Date().adding(.day, value: 1)
XCTAssertFalse(tomorrow.isInYesterday)
let yesterday = Date().adding(.day, value: -1)
XCTAssert(yesterday.isInYesterday)
}
func testIsInTomorrow() {
XCTAssertFalse(Date().isInTomorrow)
let tomorrow = Date().adding(.day, value: 1)
XCTAssert(tomorrow.isInTomorrow)
let yesterday = Date().adding(.day, value: -1)
XCTAssertFalse(yesterday.isInTomorrow)
}
func testIsInWeekend() {
let date = Date()
XCTAssertEqual(date.isInWeekend, Calendar.current.isDateInWeekend(date))
}
func testIsWorkday() {
let date = Date()
XCTAssertEqual(date.isWorkday, !Calendar.current.isDateInWeekend(date))
}
func testIsInCurrentWeek() {
let date = Date()
XCTAssert(date.isInCurrentWeek)
let dateOneYearFromNow = date.adding(.year, value: 1)
XCTAssertFalse(dateOneYearFromNow.isInCurrentWeek)
}
func testIsInCurrentMonth() {
let date = Date()
XCTAssert(date.isInCurrentMonth)
let dateOneYearFromNow = date.adding(.year, value: 1)
XCTAssertFalse(dateOneYearFromNow.isInCurrentMonth)
}
func testIsInCurrentYear() {
let date = Date()
XCTAssert(date.isInCurrentYear)
let dateOneYearFromNow = date.adding(.year, value: 1)
XCTAssertFalse(dateOneYearFromNow.isInCurrentYear)
}
func testIso8601String() {
let date = Date(timeIntervalSince1970: 512) // 1970-01-01T00:08:32.000Z
XCTAssertEqual(date.iso8601String, "1970-01-01T00:08:32.000Z")
}
func testNearestFiveMinutes() {
let date = Date(timeIntervalSince1970: 0)
XCTAssertEqual(date.nearestFiveMinutes, date)
let date2 = date.adding(.minute, value: 4) // adding 4 minutes
XCTAssertNotEqual(date2.nearestFiveMinutes, date2)
XCTAssertEqual(date2.nearestFiveMinutes, date2.adding(.minute, value: 1))
let date3 = date.adding(.minute, value: 7) // adding 7 minutes
XCTAssertEqual(date3.nearestFiveMinutes, date3.adding(.minute, value: -2))
let date4 = date.adding(.hour, value: 1).adding(.minute, value: 2) // adding 1 hour and 2 minutes
XCTAssertEqual(date4.nearestFiveMinutes, date.adding(.hour, value: 1))
}
func testNearestTenMinutes() {
let date = Date(timeIntervalSince1970: 0)
XCTAssertEqual(date.nearestTenMinutes, date)
let date2 = date.adding(.minute, value: 4) // adding 4 minutes
XCTAssertEqual(date2.nearestTenMinutes, date)
let date3 = date.adding(.minute, value: 7) // adding 7 minutes
XCTAssertEqual(date3.nearestTenMinutes, date.adding(.minute, value: 10))
let date4 = date.adding(.hour, value: 1).adding(.minute, value: 2) // adding 1 hour and 2 minutes
XCTAssertEqual(date4.nearestTenMinutes, date.adding(.hour, value: 1))
}
func testNearestQuarterHour() {
let date = Date(timeIntervalSince1970: 0)
XCTAssertEqual(date.nearestQuarterHour, date)
let date2 = date.adding(.minute, value: 4) // adding 4 minutes
XCTAssertEqual(date2.nearestQuarterHour, date)
let date3 = date.adding(.minute, value: 12) // adding 12 minutes
XCTAssertEqual(date3.nearestQuarterHour, date.adding(.minute, value: 15))
let date4 = date.adding(.hour, value: 1).adding(.minute, value: 2) // adding 1 hour and 2 minutes
XCTAssertEqual(date4.nearestQuarterHour, date.adding(.hour, value: 1))
}
func testNearestHalfHour() {
let date = Date(timeIntervalSince1970: 0)
XCTAssertEqual(date.nearestHalfHour, date)
let date2 = date.adding(.minute, value: 4) // adding 4 minutes
XCTAssertEqual(date2.nearestHalfHour, date)
let date3 = date.adding(.minute, value: 19) // adding 19 minutes
XCTAssertEqual(date3.nearestHalfHour, date.adding(.minute, value: 30))
let date4 = date.adding(.hour, value: 1).adding(.minute, value: 2) // adding 1 hour and 2 minutes
XCTAssertEqual(date4.nearestHalfHour, date.adding(.hour, value: 1))
}
func testNearestHour() {
let date = Date(timeIntervalSince1970: 0)
XCTAssertEqual(date.nearestHour, date)
let date2 = date.adding(.minute, value: 4) // adding 4 minutes
XCTAssertEqual(date2.nearestHour, date)
let date3 = date.adding(.minute, value: 34) // adding 34 minutes
XCTAssertEqual(date3.nearestHour, date.adding(.hour, value: 1))
}
func testUnixTimestamp() {
let date = Date()
XCTAssertEqual(date.unixTimestamp, date.timeIntervalSince1970)
let date2 = Date(timeIntervalSince1970: 100)
XCTAssertEqual(date2.unixTimestamp, 100)
}
func testAdding() {
let date = Date(timeIntervalSince1970: 3610) // Jan 1, 1970, 3:00:10 AM
XCTAssertEqual(date.adding(.second, value: 0), date)
let date1 = date.adding(.second, value: 10)
XCTAssertEqual(date1.second, date.second + 10)
XCTAssertEqual(date1.adding(.second, value: -10), date)
XCTAssertEqual(date.adding(.minute, value: 0), date)
let date2 = date.adding(.minute, value: 10)
XCTAssertEqual(date2.minute, date.minute + 10)
XCTAssertEqual(date2.adding(.minute, value: -10), date)
XCTAssertEqual(date.adding(.hour, value: 0), date)
let date3 = date.adding(.hour, value: 2)
XCTAssertEqual(date3.hour, date.hour + 2)
XCTAssertEqual(date3.adding(.hour, value: -2), date)
XCTAssertEqual(date.adding(.day, value: 0), date)
let date4 = date.adding(.day, value: 2)
XCTAssertEqual(date4.day, date.day + 2)
XCTAssertEqual(date4.adding(.day, value: -2), date)
XCTAssertEqual(date.adding(.weekOfYear, value: 0), date)
let date5 = date.adding(.weekOfYear, value: 1)
XCTAssertEqual(date5.day, date.day + 7)
XCTAssertEqual(date5.adding(.weekOfYear, value: -1), date)
XCTAssertEqual(date.adding(.weekOfMonth, value: 0), date)
let date6 = date.adding(.weekOfMonth, value: 1)
XCTAssertEqual(date6.day, date.day + 7)
XCTAssertEqual(date6.adding(.weekOfMonth, value: -1), date)
XCTAssertEqual(date.adding(.month, value: 0), date)
let date7 = date.adding(.month, value: 2)
XCTAssertEqual(date7.month, date.month + 2)
XCTAssertEqual(date7.adding(.month, value: -2), date)
XCTAssertEqual(date.adding(.year, value: 0), date)
let date8 = date.adding(.year, value: 4)
XCTAssertEqual(date8.year, date.year + 4)
XCTAssertEqual(date8.adding(.year, value: -4), date)
}
// swiftlint:disable next function_body_length
func testAdd() {
var date = Date(timeIntervalSince1970: 0)
date.second = 10
date.add(.second, value: -1)
XCTAssertEqual(date.second, 9)
date.add(.second, value: 0)
XCTAssertEqual(date.second, 9)
date.add(.second, value: 1)
XCTAssertEqual(date.second, 10)
date.minute = 10
date.add(.minute, value: -1)
XCTAssertEqual(date.minute, 9)
date.add(.minute, value: 0)
XCTAssertEqual(date.minute, 9)
date.add(.minute, value: 1)
XCTAssertEqual(date.minute, 10)
date.hour = 10
date.add(.hour, value: -1)
XCTAssertEqual(date.hour, 9)
date.add(.hour, value: 0)
XCTAssertEqual(date.hour, 9)
date.add(.hour, value: 1)
XCTAssertEqual(date.hour, 10)
date.day = 10
date.add(.day, value: -1)
XCTAssertEqual(date.day, 9)
date.add(.day, value: 0)
XCTAssertEqual(date.day, 9)
date.add(.day, value: 1)
XCTAssertEqual(date.day, 10)
date.month = 10
date.add(.month, value: -1)
XCTAssertEqual(date.month, 9)
date.add(.month, value: 0)
XCTAssertEqual(date.month, 9)
date.add(.month, value: 1)
XCTAssertEqual(date.month, 10)
date = Date(timeIntervalSince1970: 1514764800)
date.add(.year, value: -1)
XCTAssertEqual(date.year, 2017)
date.add(.year, value: 0)
XCTAssertEqual(date.year, 2017)
date.add(.year, value: 1)
XCTAssertEqual(date.year, 2018)
}
func testChanging() {
let date = Date(timeIntervalSince1970: 0)
XCTAssertNil(date.changing(.nanosecond, value: -10))
XCTAssertNotNil(date.changing(.nanosecond, value: 123450040))
XCTAssertEqual(date.changing(.nanosecond, value: 123450040)?.nanosecond, 123450040)
XCTAssertNil(date.changing(.second, value: -10))
XCTAssertNil(date.changing(.second, value: 70))
XCTAssertNotNil(date.changing(.second, value: 20))
XCTAssertEqual(date.changing(.second, value: 20)?.second, 20)
XCTAssertNil(date.changing(.minute, value: -10))
XCTAssertNil(date.changing(.minute, value: 70))
XCTAssertNotNil(date.changing(.minute, value: 20))
XCTAssertEqual(date.changing(.minute, value: 20)?.minute, 20)
XCTAssertNil(date.changing(.hour, value: -2))
XCTAssertNil(date.changing(.hour, value: 25))
XCTAssertNotNil(date.changing(.hour, value: 6))
XCTAssertEqual(date.changing(.hour, value: 6)?.hour, 6)
XCTAssertNil(date.changing(.day, value: -2))
XCTAssertNil(date.changing(.day, value: 35))
XCTAssertNotNil(date.changing(.day, value: 6))
XCTAssertEqual(date.changing(.day, value: 6)?.day, 6)
XCTAssertNil(date.changing(.month, value: -2))
XCTAssertNil(date.changing(.month, value: 13))
XCTAssertNotNil(date.changing(.month, value: 6))
XCTAssertEqual(date.changing(.month, value: 6)?.month, 6)
XCTAssertNil(date.changing(.year, value: -2))
XCTAssertNil(date.changing(.year, value: 0))
XCTAssertNotNil(date.changing(.year, value: 2015))
XCTAssertEqual(date.changing(.year, value: 2015)?.year, 2015)
let date1 = Date()
let date2 = date1.changing(.weekOfYear, value: 10)
XCTAssertEqual(date2, Calendar.current.date(bySetting: .weekOfYear, value: 10, of: date1))
}
func testBeginning() {
let date = Date()
XCTAssertNotNil(date.beginning(of: .second))
XCTAssertEqual(date.beginning(of: .second)?.nanosecond, 0)
XCTAssertNotNil(date.beginning(of: .minute))
XCTAssertEqual(date.beginning(of: .minute)?.second, 0)
XCTAssertNotNil(date.beginning(of: .hour))
XCTAssertEqual(date.beginning(of: .hour)?.minute, 0)
XCTAssertNotNil(date.beginning(of: .day))
XCTAssertEqual(date.beginning(of: .day)?.hour, 0)
XCTAssertEqual(date.beginning(of: .day)?.isInToday, true)
let comps = Calendar.current.dateComponents([.yearForWeekOfYear, .weekOfYear], from: date)
let beginningOfWeek = Calendar.current.date(from: comps)
XCTAssertNotNil(date.beginning(of: .weekOfMonth))
XCTAssertNotNil(beginningOfWeek)
XCTAssertEqual(date.beginning(of: .weekOfMonth)?.day, beginningOfWeek?.day)
let beginningOfMonth = Date(year: 2016, month: 8, day: 1, hour: 5)
XCTAssertNotNil(date.beginning(of: .month))
XCTAssertNotNil(beginningOfMonth)
XCTAssertEqual(date.beginning(of: .month)?.day, beginningOfMonth?.day)
let beginningOfYear = Date(year: 2016, month: 1, day: 1, hour: 5)
XCTAssertNotNil(date.beginning(of: .year))
XCTAssertNotNil(beginningOfYear)
XCTAssertEqual(date.beginning(of: .year)?.day, beginningOfYear?.day)
XCTAssertNil(date.beginning(of: .quarter))
}
func testEnd() {
let date = Date(timeIntervalSince1970: 512) // January 1, 1970 at 2:08:32 AM GMT+2
XCTAssertEqual(date.end(of: .second)?.second, 32)
XCTAssertEqual(date.end(of: .hour)?.minute, 59)
XCTAssertEqual(date.end(of: .minute)?.second, 59)
XCTAssertEqual(date.end(of: .day)?.hour, 23)
XCTAssertEqual(date.end(of: .day)?.minute, 59)
XCTAssertEqual(date.end(of: .day)?.second, 59)
var endOfWeek = date.beginning(of: .weekOfYear)
endOfWeek?.add(.day, value: 7)
endOfWeek?.add(.second, value: -1)
XCTAssertEqual(date.end(of: .weekOfYear), endOfWeek)
XCTAssertEqual(date.end(of: .month)?.day, 31)
XCTAssertEqual(date.end(of: .month)?.hour, 23)
XCTAssertEqual(date.end(of: .month)?.minute, 59)
XCTAssertEqual(date.end(of: .month)?.second, 59)
XCTAssertEqual(date.end(of: .year)?.month, 12)
XCTAssertEqual(date.end(of: .year)?.day, 31)
XCTAssertEqual(date.end(of: .year)?.hour, 23)
XCTAssertEqual(date.end(of: .year)?.minute, 59)
XCTAssertEqual(date.end(of: .year)?.second, 59)
XCTAssertNil(date.end(of: .quarter))
}
func testDateString() {
let date = Date(timeIntervalSince1970: 512)
let formatter = DateFormatter()
formatter.timeStyle = .none
formatter.dateStyle = .short
XCTAssertEqual(date.dateString(ofStyle: .short), formatter.string(from: date))
formatter.dateStyle = .medium
XCTAssertEqual(date.dateString(ofStyle: .medium), formatter.string(from: date))
formatter.dateStyle = .long
XCTAssertEqual(date.dateString(ofStyle: .long), formatter.string(from: date))
formatter.dateStyle = .full
XCTAssertEqual(date.dateString(ofStyle: .full), formatter.string(from: date))
formatter.dateStyle = .none
formatter.dateFormat = "dd/MM/yyyy"
XCTAssertEqual(date.string(withFormat: "dd/MM/yyyy"), formatter.string(from: date))
formatter.dateFormat = "HH:mm"
XCTAssertEqual(date.string(withFormat: "HH:mm"), formatter.string(from: date))
formatter.dateFormat = "dd/MM/yyyy HH:mm"
XCTAssertEqual(date.string(withFormat: "dd/MM/yyyy HH:mm"), formatter.string(from: date))
formatter.dateFormat = "iiiii"
XCTAssertEqual(date.string(withFormat: "iiiii"), formatter.string(from: date))
}
func testDateTimeString() {
let date = Date(timeIntervalSince1970: 512)
let formatter = DateFormatter()
formatter.timeStyle = .short
formatter.dateStyle = .short
XCTAssertEqual(date.dateTimeString(ofStyle: .short), formatter.string(from: date))
formatter.timeStyle = .medium
formatter.dateStyle = .medium
XCTAssertEqual(date.dateTimeString(ofStyle: .medium), formatter.string(from: date))
formatter.timeStyle = .long
formatter.dateStyle = .long
XCTAssertEqual(date.dateTimeString(ofStyle: .long), formatter.string(from: date))
formatter.timeStyle = .full
formatter.dateStyle = .full
XCTAssertEqual(date.dateTimeString(ofStyle: .full), formatter.string(from: date))
}
func testIsInCurrent() {
let date = Date()
let oldDate = Date(timeIntervalSince1970: 512) // 1970-01-01T00:08:32.000Z
XCTAssert(date.isInCurrent(.second))
XCTAssertFalse(oldDate.isInCurrent(.second))
XCTAssert(date.isInCurrent(.minute))
XCTAssertFalse(oldDate.isInCurrent(.minute))
XCTAssert(date.isInCurrent(.hour))
XCTAssertFalse(oldDate.isInCurrent(.hour))
XCTAssert(date.isInCurrent(.day))
XCTAssertFalse(oldDate.isInCurrent(.day))
XCTAssert(date.isInCurrent(.weekOfMonth))
XCTAssertFalse(oldDate.isInCurrent(.weekOfMonth))
XCTAssert(date.isInCurrent(.month))
XCTAssertFalse(oldDate.isInCurrent(.month))
XCTAssert(date.isInCurrent(.year))
XCTAssertFalse(oldDate.isInCurrent(.year))
XCTAssert(date.isInCurrent(.era))
}
func testTimeString() {
let date = Date(timeIntervalSince1970: 512)
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
XCTAssertEqual(date.timeString(ofStyle: .short), formatter.string(from: date))
formatter.timeStyle = .medium
XCTAssertEqual(date.timeString(ofStyle: .medium), formatter.string(from: date))
formatter.timeStyle = .long
XCTAssertEqual(date.timeString(ofStyle: .long), formatter.string(from: date))
formatter.timeStyle = .full
XCTAssertEqual(date.timeString(ofStyle: .full), formatter.string(from: date))
}
func testDayName() {
let date = Date(timeIntervalSince1970: 1486121165)
XCTAssertEqual(date.dayName(ofStyle: .full), "Friday")
XCTAssertEqual(date.dayName(ofStyle: .threeLetters), "Fri")
XCTAssertEqual(date.dayName(ofStyle: .oneLetter), "F")
}
func testMonthName() {
let date = Date(timeIntervalSince1970: 1486121165)
XCTAssertEqual(date.monthName(ofStyle: .full), "February")
XCTAssertEqual(date.monthName(ofStyle: .threeLetters), "Feb")
XCTAssertEqual(date.monthName(ofStyle: .oneLetter), "F")
}
func testSecondsSince() {
let date1 = Date(timeIntervalSince1970: 100)
let date2 = Date(timeIntervalSince1970: 180)
XCTAssertEqual(date2.secondsSince(date1), 80)
XCTAssertEqual(date1.secondsSince(date2), -80)
}
func testMinutesSince() {
let date1 = Date(timeIntervalSince1970: 120)
let date2 = Date(timeIntervalSince1970: 180)
XCTAssertEqual(date2.minutesSince(date1), 1)
XCTAssertEqual(date1.minutesSince(date2), -1)
}
func testHoursSince() {
let date1 = Date(timeIntervalSince1970: 3600)
let date2 = Date(timeIntervalSince1970: 7200)
XCTAssertEqual(date2.hoursSince(date1), 1)
XCTAssertEqual(date1.hoursSince(date2), -1)
}
func testDaysSince() {
let date1 = Date(timeIntervalSince1970: 0)
let date2 = Date(timeIntervalSince1970: 86400)
XCTAssertEqual(date2.daysSince(date1), 1)
XCTAssertEqual(date1.daysSince(date2), -1)
}
func testIsBetween() {
let date1 = Date(timeIntervalSince1970: 0)
let date2 = date1.addingTimeInterval(60)
let date3 = date2.addingTimeInterval(60)
XCTAssert(date2.isBetween(date1, date3))
XCTAssertFalse(date1.isBetween(date2, date3))
XCTAssert(date1.isBetween(date1, date2, includeBounds: true))
XCTAssertFalse(date1.isBetween(date1, date2))
}
func testIsWithin() {
let date1 = Date(timeIntervalSince1970: 60 * 60 * 24) // 1970-01-01T00:00:00.000Z
let date2 = date1.addingTimeInterval(60 * 60) // 1970-01-01T00:01:00.000Z, one hour later than date1
// The regular
XCTAssertFalse(date1.isWithin(1, .second, of: date2))
XCTAssertFalse(date1.isWithin(1, .minute, of: date2))
XCTAssert(date1.isWithin(1, .hour, of: date2))
XCTAssert(date1.isWithin(1, .day, of: date2))
// The other way around
XCTAssertFalse(date2.isWithin(1, .second, of: date1))
XCTAssertFalse(date2.isWithin(1, .minute, of: date1))
XCTAssert(date2.isWithin(1, .hour, of: date1))
XCTAssert(date2.isWithin(1, .day, of: date1))
// With itself
XCTAssert(date1.isWithin(1, .second, of: date1))
XCTAssert(date1.isWithin(1, .minute, of: date1))
XCTAssert(date1.isWithin(1, .hour, of: date1))
XCTAssert(date1.isWithin(1, .day, of: date1))
// Invalid
XCTAssertFalse(Date().isWithin(1, .calendar, of: Date()))
}
func testNewDateFromComponenets() {
let date = Date(calendar: Date().calendar, timeZone: NSTimeZone.default, era: Date().era, year: Date().year, month: Date().month, day: Date().day, hour: Date().hour, minute: Date().minute, second: Date().second, nanosecond: Date().nanosecond)
XCTAssertNotNil(date)
let date1 = Date(timeIntervalSince1970: date!.timeIntervalSince1970)
XCTAssertEqual(date?.timeIntervalSince1970, date1.timeIntervalSince1970)
let date2 = Date(calendar: nil, timeZone: NSTimeZone.default, era: Date().era, year: nil, month: nil, day: Date().day, hour: Date().hour, minute: Date().minute, second: Date().second, nanosecond: Date().nanosecond)
XCTAssertNil(date2)
}
func testNewDateFromIso8601String() {
let date = Date(timeIntervalSince1970: 512) // 1970-01-01T00:08:32.000Z
let dateFromIso8601 = Date(iso8601String: "1970-01-01T00:08:32.000Z")
XCTAssertEqual(date, dateFromIso8601)
XCTAssertNil(Date(iso8601String: "hello"))
}
func testNewDateFromUnixTimestamp() {
let date = Date(timeIntervalSince1970: 512) // 1970-01-01T00:08:32.000Z
let dateFromUnixTimestamp = Date(unixTimestamp: 512)
XCTAssertEqual(date, dateFromUnixTimestamp)
}
func testNewDateFromIntegerLiteral() {
let date = Date(integerLiteral: 2017_12_25)
XCTAssertNotNil(date)
if let date = date {
XCTAssertEqual(String(describing: date), "2017-12-25 00:00:00 +0000")
}
XCTAssertNil(Date(integerLiteral: 222))
}
func testRandomRange() {
var sinceDate = Date(timeIntervalSinceReferenceDate: 0)
var toDate = Date(timeIntervalSinceReferenceDate: 10000)
XCTAssert(Date.random(in: sinceDate..<toDate).isBetween(sinceDate, toDate, includeBounds: false))
sinceDate = Date(timeIntervalSince1970: -10000)
toDate = Date(timeIntervalSince1970: -10)
XCTAssert(Date.random(in: sinceDate..<toDate).isBetween(sinceDate, toDate, includeBounds: false))
sinceDate = Date(timeIntervalSinceReferenceDate: -1000)
toDate = Date(timeIntervalSinceReferenceDate: 10000)
XCTAssert(Date.random(in: sinceDate..<toDate).isBetween(sinceDate, toDate, includeBounds: false))
sinceDate = Date.distantPast
toDate = Date.distantFuture
XCTAssert(Date.random(in: sinceDate..<toDate).isBetween(sinceDate, toDate, includeBounds: false))
}
func testRandomClosedRange() {
var sinceDate = Date(timeIntervalSinceReferenceDate: 0)
var toDate = Date(timeIntervalSinceReferenceDate: 10000)
XCTAssert(Date.random(in: sinceDate...toDate).isBetween(sinceDate, toDate, includeBounds: true))
sinceDate = Date(timeIntervalSince1970: -10000)
toDate = Date(timeIntervalSince1970: -10)
XCTAssert(Date.random(in: sinceDate...toDate).isBetween(sinceDate, toDate, includeBounds: true))
sinceDate = Date(timeIntervalSinceReferenceDate: -1000)
toDate = Date(timeIntervalSinceReferenceDate: 10000)
XCTAssert(Date.random(in: sinceDate...toDate).isBetween(sinceDate, toDate, includeBounds: true))
sinceDate = Date.distantPast
toDate = Date.distantFuture
XCTAssert(Date.random(in: sinceDate...toDate).isBetween(sinceDate, toDate, includeBounds: true))
let singleDate = Date(timeIntervalSinceReferenceDate: 0)
XCTAssertFalse(Date.random(in: singleDate...singleDate).isBetween(singleDate, singleDate, includeBounds: false))
XCTAssert(Date.random(in: singleDate...singleDate).isBetween(singleDate, singleDate, includeBounds: true))
}
func testRandomRangeWithGenerator() {
var generator = SystemRandomNumberGenerator()
let sinceDate = Date.distantPast
let toDate = Date.distantFuture
XCTAssert(Date.random(in: sinceDate..<toDate, using: &generator).isBetween(sinceDate, toDate, includeBounds: false))
}
func testRandomClosedRangeWithGenerator() {
var generator = SystemRandomNumberGenerator()
let sinceDate = Date.distantPast
let toDate = Date.distantFuture
XCTAssert(Date.random(in: sinceDate...toDate, using: &generator).isBetween(sinceDate, toDate, includeBounds: true))
let singleDate = Date(timeIntervalSinceReferenceDate: 0)
XCTAssertFalse(Date.random(in: singleDate...singleDate, using: &generator).isBetween(singleDate, singleDate, includeBounds: false))
XCTAssert(Date.random(in: singleDate...singleDate, using: &generator).isBetween(singleDate, singleDate, includeBounds: true))
}
func testYesterday() {
let date = Date()
XCTAssertEqual(date.yesterday.timeIntervalSince(date), -86400.0)
}
func testTomorrow() {
let date = Date()
XCTAssertEqual(date.tomorrow.timeIntervalSince(date), 86400.0)
}
}
#endif
| mit |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Base/BBConstants.swift | 1 | 6464 | //
// BBConstants.swift
// bitboylabs-ios-base
//
// Created by 조백근 on 2016. 10. 18..
// Copyright © 2016년 BitBoy Labs. All rights reserved.
//
import Foundation
import UIKit
import XCGLogger
import SwiftyUserDefaults
import AlamofireImage
import SwiftHEXColors
//for log
let log = XCGLogger.default
/// for test !!!
let itunes_api_url: String = "https://itunes.apple.com/search"
let itunes_param_base: [String: AnyObject] = [
"country": "US" as AnyObject,
"lang": "en_us" as AnyObject,
"media": "music" as AnyObject,
"entity": "album" as AnyObject,
"limit": 100 as AnyObject
]
let empty: AnyObject = [:] as AnyObject
//잘은 모르지만 BBNetworkManager에서 사용하는 상수
let BBProjectName = "bitboylabs.project"
let SLV_URL = "http://api.selluv.com:3000"
//let SLV_URL = "http://52.79.81.3:3000"
//
let dnHost = "http://image.selluv.com:80/"
let dnAvatar = "\(dnHost)avatars/" //사용자 프로필 사진 및 배경 이미지, SNS 공유
let dnProduct = "\(dnHost)photos/" //상품 사진
let dnStyle = "\(dnHost)styles/" //스타일 사진
let dnDamage = "\(dnHost)damages/" //상품 하지 사진
let dnAccessory = "\(dnHost)accessories/" //상품 부속품 사진
let dnSign = "\(dnHost)signatures/" //서명 사진
let dnImage = "\(dnHost)images/" // Admin에서 업로드한 사진(배너, 이벤트 등)
let POST_REQUEST_KEY = "9815915a42c227fdc1483404447777"//우체국 open api 키
let KEY_IAMPORT_RESTAPI = "3966461868589664"
let KEY_IAMPORT_RESTAPI_SECRET = "mZaECL4VHGAajM1WEBKydn2pKNi5TjmfjwTViYR0ErbYecUTOEs22urMiJSc3frmMli5j95YBgWPtRJi"
public extension DefaultsKeys {
// App Token
static let isRegisterRemoteTokenKey = DefaultsKey<Bool?>("isRegisterRemoteTokenKey")
static let remoteTokenKey = DefaultsKey<String?>("remoteTokenKey")
static let permissionForCameraKey = DefaultsKey<Bool?>("permissionForCameraKey")
// 사이즈표 세팅여부
static let isClothingSizeConvetingInfoSetupKey = DefaultsKey<Bool?>("isClothingSizeConvetingInfoSetupKey")
//API서버와 통신에 사용
static let appTokenKey = DefaultsKey<String?>("appTokenKey")
static let appUserNameKey = DefaultsKey<String?>("appUserNameKey")
static let isAppAccessedServerKey = DefaultsKey<Bool?>("isAppAccessedServerKey")
//임시저장목록
static let inputDataSaveListKey = DefaultsKey<String?>("inputDataSaveListKey")
}
//MARK : 화면제어에 필요한 수치상수
internal let Noti = NotificationCenter.default
internal let App = UIApplication.shared
let appDelegate = App.delegate as! AppDelegate
let tabController = appDelegate.window?.rootViewController as! SLVTabBarController
let tabHeight = tabController.tabBar.frame.size.height //하단 공통 탭바 높이(아마도 49?)
//MARK : 컨텐츠 제어에 필요한 상수
var categoryTree: TreeNode<Category>?
let SIZE_KR = "KR"
let SIZE_EU = "EU"
let SIZE_US_UK = "US/UK"
let SIZE_ROMAN_123 = "I/II/III"
let SIZE_IT = "IT"
let SIZE_INCH = "Inch"
let SIZE_US = "US"
let SIZE_UK = "UK"
let SIZE_KOR = "KOR"
let SIZE_AGE = "연령"
let SIZE_MM = "mm"
//MARK : 사진관련
let SLV_SELL_PHOTO_DIR = "SelluvSellItemPhoto"
let DEFAULT_PHOTO_SIZE = CGSize(width: 720, height: 1280)
//MARK: 행정자치부 도로명주소 안내 오픈 api 키
let JUSO_API_SEARCH_ADDRESS_KEY = "U01TX0FVVEgyMDE3MDEwMzE3NDkyNDE3OTMz"
//MARK: NAVER 로그인
let NaverClientId = "Khgw7OI4mtNP47Hv9Jwq"
let NaverClientSecret = "K94EMljc5Q"
let NaverScheme = "com.selluv.ios"
//MARK: 텍스트 컬러
let text_color_bl51 = UIColor(colorLiteralRed: 51/255, green: 51/255, blue: 51/255, alpha: 1.0)
let text_color_g85 = UIColor(colorLiteralRed: 85/255, green: 85/255, blue: 85/255, alpha: 1.0)
let text_color_g204 = UIColor(colorLiteralRed: 204/255, green: 204/255, blue: 204/255, alpha: 1.0)
let text_color_g153 = UIColor(colorLiteralRed: 153/255, green: 153/255, blue: 153/255, alpha: 1.0)
let text_color_blue = UIColor(colorLiteralRed: 57/255, green: 90/255, blue: 128/255, alpha: 1.0)
let text_color_gold = UIColor(colorLiteralRed: 204/255, green: 177/255, blue: 119/255, alpha: 1.0)
let text_color_g181 = UIColor(colorLiteralRed: 181/255, green: 181/255, blue: 185/255, alpha: 1.0)
//MARK: 배경색
let bg_color_g245 = UIColor(colorLiteralRed: 245/255, green: 245/255, blue: 250/255, alpha: 1.0)
let bg_color_brass = UIColor(colorLiteralRed: 204/255, green: 177/255, blue: 119/255, alpha: 1.0)
let bg_color_step = UIColor(colorLiteralRed: 194/255, green: 233/255, blue: 254/255, alpha: 1.0)
let bg_color_blue = UIColor(colorLiteralRed: 45/255, green: 129/255, blue: 255/255, alpha: 1.0)
let bg_color_gline = UIColor(colorLiteralRed: 183/255, green: 188/255, blue: 203/255, alpha: 1.0)
let bg_color_pink = UIColor(colorLiteralRed: 236/255, green: 95/255, blue: 120/255, alpha: 1.0)//핑크
//MARK: Degree for rotate Animation
let d90 = CGFloat(0)
let d180 = CGFloat(M_PI)
let d360 = CGFloat(M_PI * 2)
//MARK: 판매 단계 스텝 값
//0.03, 0.12, 0.25, 0.36, 0.48
let sell_step_1_value = 0.03
let sell_step_2_value = 0.13
let sell_step_3_value = 0.25
let sell_step_4_value = 0.36
let sell_step_5_value = 0.48
//MARK: 판매 추가입력 컬러값
let additional_select_color_black = UIColor(hexString:"000000")//블랙
let additional_select_color_gray = UIColor(hexString:"c2c2c2")//그레이
let additional_select_color_white = UIColor(hexString:"ffffff")//화이트
let additional_select_color_white_border = UIColor(hexString:"555555")//화이트 보더라인
let additional_select_color_beige = UIColor(hexString:"ece7b7")//베이지
let additional_select_color_red = UIColor(hexString:"ed1232")//레드
let additional_select_color_pink = UIColor(hexString:"ff6ba3")//핑크
let additional_select_color_blue = UIColor(hexString:"4e92e0")//블루
let additional_select_color_green = UIColor(hexString:"81d235")//그린
let additional_select_color_yellow = UIColor(hexString:"f8e73b")//-- 옐로우
let additional_select_color_orange = UIColor(hexString:"f4a536")// 오렌지
let additional_select_color_purple = UIColor(hexString:"ba55d3")//퍼플
let additional_select_color_brown = UIColor(hexString:"87532b")//브라운
let additional_select_color_gold = UIColor(hexString:"e5ce61")// 골드
//MARK: JPEG 압축시 손실율.
let CompressionQuality: CGFloat = 1.0
//MARK
public enum GenderType {
case men
case women
case kid
}
| mit |
YoungGary/DYTV | DouyuTV/DouyuTV/Class/Tools/UIColor+Ext.swift | 1 | 302 | //
// UIColor+Ext.swift
// DouyuTV
//
// Created by YOUNG on 2017/3/10.
// Copyright © 2017年 Young. All rights reserved.
//
import UIKit
extension UIColor {
convenience init( r: CGFloat,g:CGFloat,b:CGFloat){
self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1)
}
}
| mit |
austinzheng/swift-compiler-crashes | fixed/27602-swift-inflightdiagnostic.swift | 4 | 292 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class a
let f {
a{
}{
let t:a {
struct Q{protocol A {
struct S {
class a{let
class b{
protocol A {
enum S {func a{
for b=b
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/03189-swift-sourcemanager-getmessage.swift | 11 | 339 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
func f<T {
enum b : a {
class b> {
return "[1)
}
case c,
var b { func f
init<T {
var b {
func b> {
enum b : B<T where T: A<A<1 {
}
class
case c,
protocol c : P
| mit |
IMcD23/Proton | Example/Proton/AppDelegate-OSX.swift | 1 | 636 | //
// AppDelegate-OSX.swift
// Proton
//
// Created by McDowell, Ian J [ITACD] on 4/13/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Proton
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var window: UIWindow!
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
self.window = Proton(rootPage: HomePage(), frame: CGRectMake(0, 0, 600, 600))
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
| mit |
dhoepfl/DHLocalizedString | DHLocalizedStringTests/DHLocalizedStringFunctionTests.swift | 1 | 3037 | //
// DHLocalizedStringFunctionTests.swift
// DHLocalizedString
//
// Created by Daniel Höpfl on 02.11.15.
// Copyright © 2015 Daniel Höpfl. All rights reserved.
//
import XCTest
@testable import DHLocalizedString
class DHLocalizedStringFunctionTests: XCTestCase {
let x = "String1"
let y = "String2"
let z = 42
var alternativeBundle: NSBundle = NSBundle.mainBundle()
override func setUp() {
super.setUp()
DHLocalizedStringStore.mainBundle = NSBundle(forClass: DHLocalizedStringFunctionTests.self);
let path = DHLocalizedStringStore.mainBundle.resourcePath!
alternativeBundle = NSBundle(path: path + "/DHLocalizedStringAlternative.bundle")!
}
func testSimpleExampleFromAlternativeFile() {
let result = DHLocalizedString("Simple String", tableName: "Alternative")
print(" Input: DHLocalizedString(\"Simple String\", tableName: \"Alternative\")")
print("Expected: Translation of simple string (alternative file)")
print(" Result: \(result)")
print("")
XCTAssertEqual("Translation of simple string (alternative file)",
result)
}
func testSimpleExampleFromAlternativeBundle() {
let result = DHLocalizedString("Simple String", bundle: alternativeBundle)
print(" Input: DHLocalizedString(\"Simple String\", bundle: alternativeBundle)")
print("Expected: Translation in Alternative Bundle")
print(" Result: \(result)")
print("")
XCTAssertEqual("Translation in Alternative Bundle",
result)
}
func testSimpleExampleFromAlternativeFileAndBundle() {
let result = DHLocalizedString("Simple String", tableName: "Alternative", bundle: alternativeBundle)
print(" Input: DHLocalizedString(\"Simple String\", tableName: \"Alternative\", bundle: alternativeBundle))")
print("Expected: Translation in Alternative Bundle, Alternative file")
print(" Result: \(result)")
print("")
XCTAssertEqual("Translation in Alternative Bundle, Alternative file",
result)
}
func testSimpleExampleFromMainFileAndBundle() {
let result = DHLocalizedString("Simple String")
print(" Input: \"Simple String\" |~ ()")
print("Expected: This is a translation of a simple string")
print(" Result: \(result)")
print("")
XCTAssertEqual("This is a translation of a simple string",
result)
}
func testArgumentsExampleFromAlternativeFile() {
let result = DHLocalizedString("With sorting \(x), \(y), and \(z).", tableName: "Alternative")
print(" Input: \"With sorting \\(x), \\(y), and \\(z).\" |~ \"Alternative\"")
print(" Key: With sorting %1$@, %2$@, and %3$@.")
print("Expected: end: 42, mid: String2, start: String1")
print(" Result: \(result)")
print("")
XCTAssertEqual("end: 42, mid: String2, start: String1",
result)
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/06462-swift-modulefile-maybereadgenericparams.swift | 11 | 385 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
b let c {
if true {
b let d<j : a {
}
let c {
protocol A {
protocol c {
}
func f
protocol c {
let g: C {
class B<U : A")
}
protocol A : f { func f: NSObject {
let d<H : A")
}
func f: d where f: B
class d<j : e, f: A
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/20166-no-stacktrace.swift | 11 | 223 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
return ( ) {
case
{
deinit {
func a( ) {
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/09188-swift-sourcemanager-getmessage.swift | 11 | 239 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A {
{
}
let f = ( ) {
case
var {
func g {
for in {
class
case ,
| mit |
svachmic/Authenticator | AuthenticatorExample/ExampleViewController.swift | 1 | 1598 | //
// ViewController.swift
// AuthenticatorExample
//
// Created by Michal Švácha on 19/03/15.
// Copyright (c) 2015 Michal Švácha. All rights reserved.
//
import UIKit
class ExampleViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func setupButtonPressed(sender: AnyObject) {
Authenticator.setUpPIN(self.navigationController!, completionClosure: { () -> Void in
println("All is good")
}, failureClosure: { (error) -> Void in
println(error.localizedDescription)
})
}
@IBAction func resetButtonPressed(sender: AnyObject) {
Authenticator.resetPIN(self.navigationController!, completionClosure: { () -> Void in
println("All is good")
}, failureClosure: { (error) -> Void in
println(error.localizedDescription)
})
}
@IBAction func authenticateButtonPressed(sender: AnyObject) {
Authenticator.authenticateUser(self.navigationController!, completionClosure: { () -> Void in
println("Multipass!")
}, failureClosure: { (error) -> Void in
println(error.localizedDescription)
})
}
@IBAction func deletePINButtonPressed(sender: AnyObject) {
Authenticator.deletePIN({ () -> Void in
println("Successfully deleted.")
}, failureClosure: { (error) -> Void in
println(error.localizedDescription)
})
}
}
| mit |
JakubMazur/Mobilization2017 | Mobilization2017macDemo/ViewController.swift | 1 | 474 | //
// ViewController.swift
// Mobilization2017macDemo
//
// Created by Jakub Mazur on 20/10/2017.
// Copyright © 2017 Jakub Mazur. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
| mit |
KlubJagiellonski/pola-ios | BuyPolish/PolaUITests/PageObjects/BasePage.swift | 1 | 1097 | import XCTest
class BasePage {
let app: XCUIApplication
var waitForExistanceTimeout = TimeInterval(10)
var pasteboard: String? {
get {
UIPasteboard.general.strings?.first
}
set {
UIPasteboard.general.strings = newValue != nil ? [newValue!] : []
}
}
init(app: XCUIApplication) {
self.app = app
}
func done() {}
func setPasteboard(_ pasteboard: String?) -> Self {
self.pasteboard = pasteboard
return self
}
func waitForPasteboardInfoDissappear(file: StaticString = #file, line: UInt = #line) -> Self {
let elements = [
"Pola pasted from PolaUITests-Runner",
"CoreSimulatorBridge pasted from Pola",
].map { app.staticTexts[$0] }
if !elements.waitForDisappear(timeout: waitForExistanceTimeout) {
XCTFail("Pasteboard info still visible", file: file, line: line)
}
return self
}
func wait(time: TimeInterval) -> Self {
Thread.sleep(forTimeInterval: time)
return self
}
}
| gpl-2.0 |
brave/browser-ios | AlertPopupView.swift | 1 | 3734 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
class AlertPopupView: PopupView {
fileprivate var dialogImage: UIImageView?
fileprivate var titleLabel: UILabel!
fileprivate var messageLabel: UILabel!
fileprivate var containerView: UIView!
fileprivate let kAlertPopupScreenFraction: CGFloat = 0.8
fileprivate let kPadding: CGFloat = 20.0
init(image: UIImage?, title: String, message: String) {
super.init(frame: CGRect.zero)
overlayDismisses = false
defaultShowType = .normal
defaultDismissType = .noAnimation
presentsOverWindow = true
containerView = UIView(frame: CGRect.zero)
containerView.autoresizingMask = [.flexibleWidth]
if let image = image {
let di = UIImageView(image: image)
containerView.addSubview(di)
dialogImage = di
}
titleLabel = UILabel(frame: CGRect.zero)
titleLabel.textColor = UIColor.black
titleLabel.textAlignment = .center
titleLabel.font = UIFont.systemFont(ofSize: 24, weight: UIFont.Weight.bold)
titleLabel.text = title
titleLabel.numberOfLines = 0
containerView.addSubview(titleLabel)
messageLabel = UILabel(frame: CGRect.zero)
messageLabel.textColor = UIColor(rgb: 0x696969)
messageLabel.textAlignment = .center
messageLabel.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.regular)
messageLabel.text = message
messageLabel.numberOfLines = 0
containerView.addSubview(messageLabel)
updateSubviews()
setPopupContentView(view: containerView)
setStyle(popupStyle: .dialog)
setDialogColor(color: BraveUX.PopupDialogColorLight)
}
func updateSubviews() {
let width: CGFloat = dialogWidth
var imageFrame: CGRect = dialogImage?.frame ?? CGRect.zero
if let dialogImage = dialogImage {
imageFrame.origin.x = (width - imageFrame.width) / 2.0
imageFrame.origin.y = kPadding * 2.0
dialogImage.frame = imageFrame
}
let titleLabelSize: CGSize = titleLabel.sizeThatFits(CGSize(width: width - kPadding * 4.0, height: CGFloat.greatestFiniteMagnitude))
var titleLabelFrame: CGRect = titleLabel.frame
titleLabelFrame.size = titleLabelSize
titleLabelFrame.origin.x = rint((width - titleLabelSize.width) / 2.0)
titleLabelFrame.origin.y = imageFrame.maxY + kPadding
titleLabel.frame = titleLabelFrame
let messageLabelSize: CGSize = messageLabel.sizeThatFits(CGSize(width: width - kPadding * 4.0, height: CGFloat.greatestFiniteMagnitude))
var messageLabelFrame: CGRect = messageLabel.frame
messageLabelFrame.size = messageLabelSize
messageLabelFrame.origin.x = rint((width - messageLabelSize.width) / 2.0)
messageLabelFrame.origin.y = rint(titleLabelFrame.maxY + kPadding / 2.0)
messageLabel.frame = messageLabelFrame
var containerViewFrame: CGRect = containerView.frame
containerViewFrame.size.width = width
containerViewFrame.size.height = messageLabelFrame.maxY + kPadding
containerView.frame = containerViewFrame
}
override func layoutSubviews() {
super.layoutSubviews()
updateSubviews()
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mpl-2.0 |
AndrejJurkin/nova-osx | Nova/support/Schedulers.swift | 1 | 1267 | //
// Copyright 2017 Andrej Jurkin.
//
// 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.
//
//
// Schedulers.swift
// Nova
//
// Created by Andrej Jurkin on 9/22/17.
//
import Foundation
import RxSwift
class Schedulers {
static var main: MainScheduler {
return MainScheduler.instance
}
static var backgroundInteractive: ConcurrentDispatchQueueScheduler {
return ConcurrentDispatchQueueScheduler(qos: .userInteractive)
}
static var background: ConcurrentDispatchQueueScheduler {
return ConcurrentDispatchQueueScheduler(qos: .background)
}
static var backgroundDefault: ConcurrentDispatchQueueScheduler {
return ConcurrentDispatchQueueScheduler(qos: .default)
}
}
| apache-2.0 |
brave/browser-ios | ThirdParty/SQLiteSwift/Sources/SQLite/Typed/Query.swift | 9 | 36689 | //
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// 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 protocol QueryType : Expressible {
var clauses: QueryClauses { get set }
init(_ name: String, database: String?)
}
public protocol SchemaType : QueryType {
static var identifier: String { get }
}
extension SchemaType {
/// Builds a copy of the query with the `SELECT` clause applied.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
/// let email = Expression<String>("email")
///
/// users.select(id, email)
/// // SELECT "id", "email" FROM "users"
///
/// - Parameter all: A list of expressions to select.
///
/// - Returns: A query with the given `SELECT` clause applied.
public func select(_ column1: Expressible, _ more: Expressible...) -> Self {
return select(false, [column1] + more)
}
/// Builds a copy of the query with the `SELECT DISTINCT` clause applied.
///
/// let users = Table("users")
/// let email = Expression<String>("email")
///
/// users.select(distinct: email)
/// // SELECT DISTINCT "email" FROM "users"
///
/// - Parameter columns: A list of expressions to select.
///
/// - Returns: A query with the given `SELECT DISTINCT` clause applied.
public func select(distinct column1: Expressible, _ more: Expressible...) -> Self {
return select(true, [column1] + more)
}
/// Builds a copy of the query with the `SELECT` clause applied.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
/// let email = Expression<String>("email")
///
/// users.select([id, email])
/// // SELECT "id", "email" FROM "users"
///
/// - Parameter all: A list of expressions to select.
///
/// - Returns: A query with the given `SELECT` clause applied.
public func select(_ all: [Expressible]) -> Self {
return select(false, all)
}
/// Builds a copy of the query with the `SELECT DISTINCT` clause applied.
///
/// let users = Table("users")
/// let email = Expression<String>("email")
///
/// users.select(distinct: [email])
/// // SELECT DISTINCT "email" FROM "users"
///
/// - Parameter columns: A list of expressions to select.
///
/// - Returns: A query with the given `SELECT DISTINCT` clause applied.
public func select(distinct columns: [Expressible]) -> Self {
return select(true, columns)
}
/// Builds a copy of the query with the `SELECT *` clause applied.
///
/// let users = Table("users")
///
/// users.select(*)
/// // SELECT * FROM "users"
///
/// - Parameter star: A star literal.
///
/// - Returns: A query with the given `SELECT *` clause applied.
public func select(_ star: Star) -> Self {
return select([star(nil, nil)])
}
/// Builds a copy of the query with the `SELECT DISTINCT *` clause applied.
///
/// let users = Table("users")
///
/// users.select(distinct: *)
/// // SELECT DISTINCT * FROM "users"
///
/// - Parameter star: A star literal.
///
/// - Returns: A query with the given `SELECT DISTINCT *` clause applied.
public func select(distinct star: Star) -> Self {
return select(distinct: [star(nil, nil)])
}
/// Builds a scalar copy of the query with the `SELECT` clause applied.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
///
/// users.select(id)
/// // SELECT "id" FROM "users"
///
/// - Parameter all: A list of expressions to select.
///
/// - Returns: A query with the given `SELECT` clause applied.
public func select<V : Value>(_ column: Expression<V>) -> ScalarQuery<V> {
return select(false, [column])
}
public func select<V : Value>(_ column: Expression<V?>) -> ScalarQuery<V?> {
return select(false, [column])
}
/// Builds a scalar copy of the query with the `SELECT DISTINCT` clause
/// applied.
///
/// let users = Table("users")
/// let email = Expression<String>("email")
///
/// users.select(distinct: email)
/// // SELECT DISTINCT "email" FROM "users"
///
/// - Parameter column: A list of expressions to select.
///
/// - Returns: A query with the given `SELECT DISTINCT` clause applied.
public func select<V : Value>(distinct column: Expression<V>) -> ScalarQuery<V> {
return select(true, [column])
}
public func select<V : Value>(distinct column: Expression<V?>) -> ScalarQuery<V?> {
return select(true, [column])
}
public var count: ScalarQuery<Int> {
return select(Expression.count(*))
}
}
extension QueryType {
fileprivate func select<Q : QueryType>(_ distinct: Bool, _ columns: [Expressible]) -> Q {
var query = Q.init(clauses.from.name, database: clauses.from.database)
query.clauses = clauses
query.clauses.select = (distinct, columns)
return query
}
// MARK: UNION
/// Adds a `UNION` clause to the query.
///
/// let users = Table("users")
/// let email = Expression<String>("email")
///
/// users.filter(email == "alice@example.com").union(users.filter(email == "sally@example.com"))
/// // SELECT * FROM "users" WHERE email = 'alice@example.com' UNION SELECT * FROM "users" WHERE email = 'sally@example.com'
///
/// - Parameters:
///
/// - table: A query representing the other table.
///
/// - Returns: A query with the given `UNION` clause applied.
public func union(_ table: QueryType) -> Self {
var query = self
query.clauses.union.append(table)
return query
}
// MARK: JOIN
/// Adds a `JOIN` clause to the query.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
/// let posts = Table("posts")
/// let userId = Expression<Int64>("user_id")
///
/// users.join(posts, on: posts[userId] == users[id])
/// // SELECT * FROM "users" INNER JOIN "posts" ON ("posts"."user_id" = "users"."id")
///
/// - Parameters:
///
/// - table: A query representing the other table.
///
/// - condition: A boolean expression describing the join condition.
///
/// - Returns: A query with the given `JOIN` clause applied.
public func join(_ table: QueryType, on condition: Expression<Bool>) -> Self {
return join(table, on: Expression<Bool?>(condition))
}
/// Adds a `JOIN` clause to the query.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
/// let posts = Table("posts")
/// let userId = Expression<Int64?>("user_id")
///
/// users.join(posts, on: posts[userId] == users[id])
/// // SELECT * FROM "users" INNER JOIN "posts" ON ("posts"."user_id" = "users"."id")
///
/// - Parameters:
///
/// - table: A query representing the other table.
///
/// - condition: A boolean expression describing the join condition.
///
/// - Returns: A query with the given `JOIN` clause applied.
public func join(_ table: QueryType, on condition: Expression<Bool?>) -> Self {
return join(.inner, table, on: condition)
}
/// Adds a `JOIN` clause to the query.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
/// let posts = Table("posts")
/// let userId = Expression<Int64>("user_id")
///
/// users.join(.LeftOuter, posts, on: posts[userId] == users[id])
/// // SELECT * FROM "users" LEFT OUTER JOIN "posts" ON ("posts"."user_id" = "users"."id")
///
/// - Parameters:
///
/// - type: The `JOIN` operator.
///
/// - table: A query representing the other table.
///
/// - condition: A boolean expression describing the join condition.
///
/// - Returns: A query with the given `JOIN` clause applied.
public func join(_ type: JoinType, _ table: QueryType, on condition: Expression<Bool>) -> Self {
return join(type, table, on: Expression<Bool?>(condition))
}
/// Adds a `JOIN` clause to the query.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
/// let posts = Table("posts")
/// let userId = Expression<Int64?>("user_id")
///
/// users.join(.LeftOuter, posts, on: posts[userId] == users[id])
/// // SELECT * FROM "users" LEFT OUTER JOIN "posts" ON ("posts"."user_id" = "users"."id")
///
/// - Parameters:
///
/// - type: The `JOIN` operator.
///
/// - table: A query representing the other table.
///
/// - condition: A boolean expression describing the join condition.
///
/// - Returns: A query with the given `JOIN` clause applied.
public func join(_ type: JoinType, _ table: QueryType, on condition: Expression<Bool?>) -> Self {
var query = self
query.clauses.join.append((type: type, query: table, condition: table.clauses.filters.map { condition && $0 } ?? condition as Expressible))
return query
}
// MARK: WHERE
/// Adds a condition to the query’s `WHERE` clause.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
///
/// users.filter(id == 1)
/// // SELECT * FROM "users" WHERE ("id" = 1)
///
/// - Parameter condition: A boolean expression to filter on.
///
/// - Returns: A query with the given `WHERE` clause applied.
public func filter(_ predicate: Expression<Bool>) -> Self {
return filter(Expression<Bool?>(predicate))
}
/// Adds a condition to the query’s `WHERE` clause.
///
/// let users = Table("users")
/// let age = Expression<Int?>("age")
///
/// users.filter(age >= 35)
/// // SELECT * FROM "users" WHERE ("age" >= 35)
///
/// - Parameter condition: A boolean expression to filter on.
///
/// - Returns: A query with the given `WHERE` clause applied.
public func filter(_ predicate: Expression<Bool?>) -> Self {
var query = self
query.clauses.filters = query.clauses.filters.map { $0 && predicate } ?? predicate
return query
}
/// Adds a condition to the query’s `WHERE` clause.
/// This is an alias for `filter(predicate)`
public func `where`(_ predicate: Expression<Bool>) -> Self {
return `where`(Expression<Bool?>(predicate))
}
/// Adds a condition to the query’s `WHERE` clause.
/// This is an alias for `filter(predicate)`
public func `where`(_ predicate: Expression<Bool?>) -> Self {
return filter(predicate)
}
// MARK: GROUP BY
/// Sets a `GROUP BY` clause on the query.
///
/// - Parameter by: A list of columns to group by.
///
/// - Returns: A query with the given `GROUP BY` clause applied.
public func group(_ by: Expressible...) -> Self {
return group(by)
}
/// Sets a `GROUP BY` clause on the query.
///
/// - Parameter by: A list of columns to group by.
///
/// - Returns: A query with the given `GROUP BY` clause applied.
public func group(_ by: [Expressible]) -> Self {
return group(by, nil)
}
/// Sets a `GROUP BY`-`HAVING` clause on the query.
///
/// - Parameters:
///
/// - by: A column to group by.
///
/// - having: A condition determining which groups are returned.
///
/// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied.
public func group(_ by: Expressible, having: Expression<Bool>) -> Self {
return group([by], having: having)
}
/// Sets a `GROUP BY`-`HAVING` clause on the query.
///
/// - Parameters:
///
/// - by: A column to group by.
///
/// - having: A condition determining which groups are returned.
///
/// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied.
public func group(_ by: Expressible, having: Expression<Bool?>) -> Self {
return group([by], having: having)
}
/// Sets a `GROUP BY`-`HAVING` clause on the query.
///
/// - Parameters:
///
/// - by: A list of columns to group by.
///
/// - having: A condition determining which groups are returned.
///
/// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied.
public func group(_ by: [Expressible], having: Expression<Bool>) -> Self {
return group(by, Expression<Bool?>(having))
}
/// Sets a `GROUP BY`-`HAVING` clause on the query.
///
/// - Parameters:
///
/// - by: A list of columns to group by.
///
/// - having: A condition determining which groups are returned.
///
/// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied.
public func group(_ by: [Expressible], having: Expression<Bool?>) -> Self {
return group(by, having)
}
fileprivate func group(_ by: [Expressible], _ having: Expression<Bool?>?) -> Self {
var query = self
query.clauses.group = (by, having)
return query
}
// MARK: ORDER BY
/// Sets an `ORDER BY` clause on the query.
///
/// let users = Table("users")
/// let email = Expression<String>("email")
/// let name = Expression<String?>("name")
///
/// users.order(email.desc, name.asc)
/// // SELECT * FROM "users" ORDER BY "email" DESC, "name" ASC
///
/// - Parameter by: An ordered list of columns and directions to sort by.
///
/// - Returns: A query with the given `ORDER BY` clause applied.
public func order(_ by: Expressible...) -> Self {
return order(by)
}
/// Sets an `ORDER BY` clause on the query.
///
/// let users = Table("users")
/// let email = Expression<String>("email")
/// let name = Expression<String?>("name")
///
/// users.order([email.desc, name.asc])
/// // SELECT * FROM "users" ORDER BY "email" DESC, "name" ASC
///
/// - Parameter by: An ordered list of columns and directions to sort by.
///
/// - Returns: A query with the given `ORDER BY` clause applied.
public func order(_ by: [Expressible]) -> Self {
var query = self
query.clauses.order = by
return query
}
// MARK: LIMIT/OFFSET
/// Sets the LIMIT clause (and resets any OFFSET clause) on the query.
///
/// let users = Table("users")
///
/// users.limit(20)
/// // SELECT * FROM "users" LIMIT 20
///
/// - Parameter length: The maximum number of rows to return (or `nil` to
/// return unlimited rows).
///
/// - Returns: A query with the given LIMIT clause applied.
public func limit(_ length: Int?) -> Self {
return limit(length, nil)
}
/// Sets LIMIT and OFFSET clauses on the query.
///
/// let users = Table("users")
///
/// users.limit(20, offset: 20)
/// // SELECT * FROM "users" LIMIT 20 OFFSET 20
///
/// - Parameters:
///
/// - length: The maximum number of rows to return.
///
/// - offset: The number of rows to skip.
///
/// - Returns: A query with the given LIMIT and OFFSET clauses applied.
public func limit(_ length: Int, offset: Int) -> Self {
return limit(length, offset)
}
// prevents limit(nil, offset: 5)
fileprivate func limit(_ length: Int?, _ offset: Int?) -> Self {
var query = self
query.clauses.limit = length.map { ($0, offset) }
return query
}
// MARK: - Clauses
//
// MARK: SELECT
// MARK: -
fileprivate var selectClause: Expressible {
return " ".join([
Expression<Void>(literal: clauses.select.distinct ? "SELECT DISTINCT" : "SELECT"),
", ".join(clauses.select.columns),
Expression<Void>(literal: "FROM"),
tableName(alias: true)
])
}
fileprivate var joinClause: Expressible? {
guard !clauses.join.isEmpty else {
return nil
}
return " ".join(clauses.join.map { arg in
let (type, query, condition) = arg
return " ".join([
Expression<Void>(literal: "\(type.rawValue) JOIN"),
query.tableName(alias: true),
Expression<Void>(literal: "ON"),
condition
])
})
}
fileprivate var whereClause: Expressible? {
guard let filters = clauses.filters else {
return nil
}
return " ".join([
Expression<Void>(literal: "WHERE"),
filters
])
}
fileprivate var groupByClause: Expressible? {
guard let group = clauses.group else {
return nil
}
let groupByClause = " ".join([
Expression<Void>(literal: "GROUP BY"),
", ".join(group.by)
])
guard let having = group.having else {
return groupByClause
}
return " ".join([
groupByClause,
" ".join([
Expression<Void>(literal: "HAVING"),
having
])
])
}
fileprivate var orderClause: Expressible? {
guard !clauses.order.isEmpty else {
return nil
}
return " ".join([
Expression<Void>(literal: "ORDER BY"),
", ".join(clauses.order)
])
}
fileprivate var limitOffsetClause: Expressible? {
guard let limit = clauses.limit else {
return nil
}
let limitClause = Expression<Void>(literal: "LIMIT \(limit.length)")
guard let offset = limit.offset else {
return limitClause
}
return " ".join([
limitClause,
Expression<Void>(literal: "OFFSET \(offset)")
])
}
fileprivate var unionClause: Expressible? {
guard !clauses.union.isEmpty else {
return nil
}
return " ".join(clauses.union.map { query in
" ".join([
Expression<Void>(literal: "UNION"),
query
])
})
}
// MARK: -
public func alias(_ aliasName: String) -> Self {
var query = self
query.clauses.from = (clauses.from.name, aliasName, clauses.from.database)
return query
}
// MARK: - Operations
//
// MARK: INSERT
public func insert(_ value: Setter, _ more: Setter...) -> Insert {
return insert([value] + more)
}
public func insert(_ values: [Setter]) -> Insert {
return insert(nil, values)
}
public func insert(or onConflict: OnConflict, _ values: Setter...) -> Insert {
return insert(or: onConflict, values)
}
public func insert(or onConflict: OnConflict, _ values: [Setter]) -> Insert {
return insert(onConflict, values)
}
fileprivate func insert(_ or: OnConflict?, _ values: [Setter]) -> Insert {
let insert = values.reduce((columns: [Expressible](), values: [Expressible]())) { insert, setter in
(insert.columns + [setter.column], insert.values + [setter.value])
}
let clauses: [Expressible?] = [
Expression<Void>(literal: "INSERT"),
or.map { Expression<Void>(literal: "OR \($0.rawValue)") },
Expression<Void>(literal: "INTO"),
tableName(),
"".wrap(insert.columns) as Expression<Void>,
Expression<Void>(literal: "VALUES"),
"".wrap(insert.values) as Expression<Void>,
whereClause
]
return Insert(" ".join(clauses.compactMap { $0 }).expression)
}
/// Runs an `INSERT` statement against the query with `DEFAULT VALUES`.
public func insert() -> Insert {
return Insert(" ".join([
Expression<Void>(literal: "INSERT INTO"),
tableName(),
Expression<Void>(literal: "DEFAULT VALUES")
]).expression)
}
/// Runs an `INSERT` statement against the query with the results of another
/// query.
///
/// - Parameter query: A query to `SELECT` results from.
///
/// - Returns: The number of updated rows and statement.
public func insert(_ query: QueryType) -> Update {
return Update(" ".join([
Expression<Void>(literal: "INSERT INTO"),
tableName(),
query.expression
]).expression)
}
// MARK: UPDATE
public func update(_ values: Setter...) -> Update {
return update(values)
}
public func update(_ values: [Setter]) -> Update {
let clauses: [Expressible?] = [
Expression<Void>(literal: "UPDATE"),
tableName(),
Expression<Void>(literal: "SET"),
", ".join(values.map { " = ".join([$0.column, $0.value]) }),
whereClause,
orderClause,
limitOffsetClause
]
return Update(" ".join(clauses.compactMap { $0 }).expression)
}
// MARK: DELETE
public func delete() -> Delete {
let clauses: [Expressible?] = [
Expression<Void>(literal: "DELETE FROM"),
tableName(),
whereClause,
orderClause,
limitOffsetClause
]
return Delete(" ".join(clauses.compactMap { $0 }).expression)
}
// MARK: EXISTS
public var exists: Select<Bool> {
return Select(" ".join([
Expression<Void>(literal: "SELECT EXISTS"),
"".wrap(expression) as Expression<Void>
]).expression)
}
// MARK: -
/// Prefixes a column expression with the query’s table name or alias.
///
/// - Parameter column: A column expression.
///
/// - Returns: A column expression namespaced with the query’s table name or
/// alias.
public func namespace<V>(_ column: Expression<V>) -> Expression<V> {
return Expression(".".join([tableName(), column]).expression)
}
public subscript<T>(column: Expression<T>) -> Expression<T> {
return namespace(column)
}
public subscript<T>(column: Expression<T?>) -> Expression<T?> {
return namespace(column)
}
/// Prefixes a star with the query’s table name or alias.
///
/// - Parameter star: A literal `*`.
///
/// - Returns: A `*` expression namespaced with the query’s table name or
/// alias.
public subscript(star: Star) -> Expression<Void> {
return namespace(star(nil, nil))
}
// MARK: -
// TODO: alias support
func tableName(alias aliased: Bool = false) -> Expressible {
guard let alias = clauses.from.alias , aliased else {
return database(namespace: clauses.from.alias ?? clauses.from.name)
}
return " ".join([
database(namespace: clauses.from.name),
Expression<Void>(literal: "AS"),
Expression<Void>(alias)
])
}
func tableName(qualified: Bool) -> Expressible {
if qualified {
return tableName()
}
return Expression<Void>(clauses.from.alias ?? clauses.from.name)
}
func database(namespace name: String) -> Expressible {
let name = Expression<Void>(name)
guard let database = clauses.from.database else {
return name
}
return ".".join([Expression<Void>(database), name])
}
public var expression: Expression<Void> {
let clauses: [Expressible?] = [
selectClause,
joinClause,
whereClause,
groupByClause,
unionClause,
orderClause,
limitOffsetClause
]
return " ".join(clauses.compactMap { $0 }).expression
}
}
// TODO: decide: simplify the below with a boxed type instead
/// Queries a collection of chainable helper functions and expressions to build
/// executable SQL statements.
public struct Table : SchemaType {
public static let identifier = "TABLE"
public var clauses: QueryClauses
public init(_ name: String, database: String? = nil) {
clauses = QueryClauses(name, alias: nil, database: database)
}
}
public struct View : SchemaType {
public static let identifier = "VIEW"
public var clauses: QueryClauses
public init(_ name: String, database: String? = nil) {
clauses = QueryClauses(name, alias: nil, database: database)
}
}
public struct VirtualTable : SchemaType {
public static let identifier = "VIRTUAL TABLE"
public var clauses: QueryClauses
public init(_ name: String, database: String? = nil) {
clauses = QueryClauses(name, alias: nil, database: database)
}
}
// TODO: make `ScalarQuery` work in `QueryType.select()`, `.filter()`, etc.
public struct ScalarQuery<V> : QueryType {
public var clauses: QueryClauses
public init(_ name: String, database: String? = nil) {
clauses = QueryClauses(name, alias: nil, database: database)
}
}
// TODO: decide: simplify the below with a boxed type instead
public struct Select<T> : ExpressionType {
public var template: String
public var bindings: [Binding?]
public init(_ template: String, _ bindings: [Binding?]) {
self.template = template
self.bindings = bindings
}
}
public struct Insert : ExpressionType {
public var template: String
public var bindings: [Binding?]
public init(_ template: String, _ bindings: [Binding?]) {
self.template = template
self.bindings = bindings
}
}
public struct Update : ExpressionType {
public var template: String
public var bindings: [Binding?]
public init(_ template: String, _ bindings: [Binding?]) {
self.template = template
self.bindings = bindings
}
}
public struct Delete : ExpressionType {
public var template: String
public var bindings: [Binding?]
public init(_ template: String, _ bindings: [Binding?]) {
self.template = template
self.bindings = bindings
}
}
public struct RowIterator: FailableIterator {
public typealias Element = Row
let statement: Statement
let columnNames: [String: Int]
public func failableNext() throws -> Row? {
return try statement.failableNext().flatMap { Row(columnNames, $0) }
}
public func map<T>(_ transform: (Element) throws -> T) throws -> [T] {
var elements = [T]()
while let row = try failableNext() {
elements.append(try transform(row))
}
return elements
}
}
extension Connection {
public func prepare(_ query: QueryType) throws -> AnySequence<Row> {
let expression = query.expression
let statement = try prepare(expression.template, expression.bindings)
let columnNames = try columnNamesForQuery(query)
return AnySequence {
AnyIterator { statement.next().map { Row(columnNames, $0) } }
}
}
public func prepareRowIterator(_ query: QueryType) throws -> RowIterator {
let expression = query.expression
let statement = try prepare(expression.template, expression.bindings)
return RowIterator(statement: statement, columnNames: try columnNamesForQuery(query))
}
private func columnNamesForQuery(_ query: QueryType) throws -> [String: Int] {
var (columnNames, idx) = ([String: Int](), 0)
column: for each in query.clauses.select.columns {
var names = each.expression.template.split { $0 == "." }.map(String.init)
let column = names.removeLast()
let namespace = names.joined(separator: ".")
func expandGlob(_ namespace: Bool) -> ((QueryType) throws -> Void) {
return { (query: QueryType) throws -> (Void) in
var q = type(of: query).init(query.clauses.from.name, database: query.clauses.from.database)
q.clauses.select = query.clauses.select
let e = q.expression
var names = try self.prepare(e.template, e.bindings).columnNames.map { $0.quote() }
if namespace { names = names.map { "\(query.tableName().expression.template).\($0)" } }
for name in names { columnNames[name] = idx; idx += 1 }
}
}
if column == "*" {
var select = query
select.clauses.select = (false, [Expression<Void>(literal: "*") as Expressible])
let queries = [select] + query.clauses.join.map { $0.query }
if !namespace.isEmpty {
for q in queries {
if q.tableName().expression.template == namespace {
try expandGlob(true)(q)
continue column
}
throw QueryError.noSuchTable(name: namespace)
}
throw QueryError.noSuchTable(name: namespace)
}
for q in queries {
try expandGlob(query.clauses.join.count > 0)(q)
}
continue
}
columnNames[each.expression.template] = idx
idx += 1
}
return columnNames
}
public func scalar<V : Value>(_ query: ScalarQuery<V>) throws -> V {
let expression = query.expression
return value(try scalar(expression.template, expression.bindings))
}
public func scalar<V : Value>(_ query: ScalarQuery<V?>) throws -> V.ValueType? {
let expression = query.expression
guard let value = try scalar(expression.template, expression.bindings) as? V.Datatype else { return nil }
return V.fromDatatypeValue(value)
}
public func scalar<V : Value>(_ query: Select<V>) throws -> V {
let expression = query.expression
return value(try scalar(expression.template, expression.bindings))
}
public func scalar<V : Value>(_ query: Select<V?>) throws -> V.ValueType? {
let expression = query.expression
guard let value = try scalar(expression.template, expression.bindings) as? V.Datatype else { return nil }
return V.fromDatatypeValue(value)
}
public func pluck(_ query: QueryType) throws -> Row? {
return try prepareRowIterator(query.limit(1, query.clauses.limit?.offset)).failableNext()
}
/// Runs an `Insert` query.
///
/// - SeeAlso: `QueryType.insert(value:_:)`
/// - SeeAlso: `QueryType.insert(values:)`
/// - SeeAlso: `QueryType.insert(or:_:)`
/// - SeeAlso: `QueryType.insert()`
///
/// - Parameter query: An insert query.
///
/// - Returns: The insert’s rowid.
@discardableResult public func run(_ query: Insert) throws -> Int64 {
let expression = query.expression
return try sync {
try self.run(expression.template, expression.bindings)
return self.lastInsertRowid
}
}
/// Runs an `Update` query.
///
/// - SeeAlso: `QueryType.insert(query:)`
/// - SeeAlso: `QueryType.update(values:)`
///
/// - Parameter query: An update query.
///
/// - Returns: The number of updated rows.
@discardableResult public func run(_ query: Update) throws -> Int {
let expression = query.expression
return try sync {
try self.run(expression.template, expression.bindings)
return self.changes
}
}
/// Runs a `Delete` query.
///
/// - SeeAlso: `QueryType.delete()`
///
/// - Parameter query: A delete query.
///
/// - Returns: The number of deleted rows.
@discardableResult public func run(_ query: Delete) throws -> Int {
let expression = query.expression
return try sync {
try self.run(expression.template, expression.bindings)
return self.changes
}
}
}
public struct Row {
let columnNames: [String: Int]
fileprivate let values: [Binding?]
internal init(_ columnNames: [String: Int], _ values: [Binding?]) {
self.columnNames = columnNames
self.values = values
}
func hasValue(for column: String) -> Bool {
guard let idx = columnNames[column.quote()] else {
return false
}
return values[idx] != nil
}
/// Returns a row’s value for the given column.
///
/// - Parameter column: An expression representing a column selected in a Query.
///
/// - Returns: The value for the given column.
public func get<V: Value>(_ column: Expression<V>) throws -> V {
if let value = try get(Expression<V?>(column)) {
return value
} else {
throw QueryError.unexpectedNullValue(name: column.template)
}
}
public func get<V: Value>(_ column: Expression<V?>) throws -> V? {
func valueAtIndex(_ idx: Int) -> V? {
guard let value = values[idx] as? V.Datatype else { return nil }
return V.fromDatatypeValue(value) as? V
}
guard let idx = columnNames[column.template] else {
let similar = Array(columnNames.keys).filter { $0.hasSuffix(".\(column.template)") }
switch similar.count {
case 0:
throw QueryError.noSuchColumn(name: column.template, columns: columnNames.keys.sorted())
case 1:
return valueAtIndex(columnNames[similar[0]]!)
default:
throw QueryError.ambiguousColumn(name: column.template, similar: similar)
}
}
return valueAtIndex(idx)
}
public subscript<T : Value>(column: Expression<T>) -> T {
return try! get(column)
}
public subscript<T : Value>(column: Expression<T?>) -> T? {
return try! get(column)
}
}
/// Determines the join operator for a query’s `JOIN` clause.
public enum JoinType : String {
/// A `CROSS` join.
case cross = "CROSS"
/// An `INNER` join.
case inner = "INNER"
/// A `LEFT OUTER` join.
case leftOuter = "LEFT OUTER"
}
/// ON CONFLICT resolutions.
public enum OnConflict: String {
case replace = "REPLACE"
case rollback = "ROLLBACK"
case abort = "ABORT"
case fail = "FAIL"
case ignore = "IGNORE"
}
// MARK: - Private
public struct QueryClauses {
var select = (distinct: false, columns: [Expression<Void>(literal: "*") as Expressible])
var from: (name: String, alias: String?, database: String?)
var join = [(type: JoinType, query: QueryType, condition: Expressible)]()
var filters: Expression<Bool?>?
var group: (by: [Expressible], having: Expression<Bool?>?)?
var order = [Expressible]()
var limit: (length: Int, offset: Int?)?
var union = [QueryType]()
fileprivate init(_ name: String, alias: String?, database: String?) {
self.from = (name, alias, database)
}
}
| mpl-2.0 |
lauracpierre/FA_UISplitViewController | Example/DetailViewController.swift | 1 | 1092 | //
// DetailViewController.swift
// test
//
// Created by Pierre Laurac on 5/17/16.
// Copyright © 2016 Pierre Laurac. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var detailDescriptionLabel: UILabel!
var detailItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail = self.detailItem {
if let label = self.detailDescriptionLabel {
label.text = detail.description
}
}
}
deinit {
NSLog("deinit DetailViewcontroller")
}
@IBAction func showNext(_ sender: AnyObject) {
self.performSegue(withIdentifier: "show", sender: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
bordplate/sociabl | Sources/App/Models/User.swift | 1 | 9619 | //
// User.swift
// sociabl
//
// Created by Vetle Økland on 16/03/2017.
//
//
import Foundation
import Vapor
import Fluent
import Auth
import Random
/// Social network user.
final class User: Model {
enum Error: Swift.Error {
case invalidCredentials
case usernameTaken
case emailUsed
case postExceedsMaxLength
case alreadyFollowing
case notFollowing
case cantFollowSelf
}
var id: Node?
var email: String
var username: String
var password: String
var salt: String
var displayName: String
var profileDescription: String
var profileImgUrl: String
var joinDate: Date
var exists: Bool = false
init(email: String, username: String, password: String, salt: String, displayName: String, profileDescription: String, profileImgUrl: String, joinDate: Date) {
self.email = email
self.username = username
self.password = password
self.salt = salt
self.displayName = displayName
self.profileDescription = profileDescription
self.profileImgUrl = profileImgUrl
self.joinDate = joinDate
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
email = try node.extract("email")
username = try node.extract("username")
password = try node.extract("password")
salt = try node.extract("salt")
displayName = try node.extract("display_name")
profileDescription = try node.extract("profile_description")
profileImgUrl = try node.extract("profile_img_url")
// Database stores the date as Unix-style timestamp, so we convert that to a `Date`
joinDate = try node.extract("join_date") { (timestamp: Int) throws -> Date in
return Date(timeIntervalSince1970: TimeInterval(timestamp))
}
}
/**
## Discussion
It feels dangerous to return the password here,
even though it's hashed.
*/
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"email": email,
"username": username,
"password": password,
"salt": salt,
"display_name": displayName,
"profile_description": profileDescription,
"profile_img_url": profileImgUrl,
"join_date": joinDate.timeIntervalSince1970 // Convert Date to Unix timestamp
])
}
/// Use this for when making a Node that should be displayed as a profile.
func makeProfileNode() throws -> Node {
return try Node(node: [
"id": id,
"username": username,
"display_name": displayName,
"profile_description": profileDescription,
"profile_img_url": profileImgUrl,
"join_date": joinDate.timeIntervalSince1970,
"post_count": try self.postCount(),
"like_count": try self.likeCount(),
"following_count": try self.followingCount(),
"follower_count": try self.followerCount(),
"posts": try self.posts().makeNode(context: ["public": true])
])
}
/// For when a user should be embedded in e.g. a post.
func makeEmbedNode() throws -> Node {
return try Node(node: [
"id": id,
"username": username,
"display_name": displayName,
"profile_img_url": profileImgUrl
])
}
/// Returns the timeline for the user.
func timeline() throws -> Node? {
if let id = self.id {
if var subjects = try Follower.subjects(for: id)?.nodeArray {
if let id = self.id { subjects += id } // To see your own posts in the timeline as well.
return try Post.posts(for: subjects).makeNode(context: ["public": true])
}
}
return nil
}
}
// - Interactions with other users
extension User {
/**
Follows provided subject given valid credentials.
## Discusion
This probably should have some sort of check to see that the subject
does not have a private profile, if that ever becomes a thing.
- parameters:
- subject: The user of the user to follow.
*/
public func follow(user subject: User) throws {
if subject.id == self.id {
throw Error.cantFollowSelf
}
if try self.isFollowing(user: subject) {
throw Error.alreadyFollowing
}
var followerRelationship = Follower(owner: self.id, subject: subject.id)
try followerRelationship.save()
}
public func unfollow(user subject: User) throws {
if subject.id == self.id {
throw Error.cantFollowSelf
}
guard let subjectId = subject.id else {
throw Abort.badRequest
}
if let relation = try self.children("owner", Follower.self).filter("subject", subjectId).first() {
try relation.delete()
} else {
throw Error.notFollowing
}
}
public func submit(post content: String) throws {
if content.count > Configuration.maxPostLength {
throw Error.postExceedsMaxLength
}
var post = Post(content: content, date: Date(), user: self)
try post.save()
}
public func isFollowing(user subject: User) throws -> Bool {
guard let subjectId = subject.id else {
throw Abort.badRequest
}
if try self.children("owner", Follower.self).filter("subject", subjectId).count() > 0 {
return true
}
return false
}
}
extension User {
public func postCount() throws -> Int {
return try self.children(nil, Post.self).count()
}
public func likeCount() throws -> Int {
return 0
}
public func followingCount() throws -> Int {
return try self.children("owner", Follower.self).count()
}
public func followerCount() throws -> Int {
return try self.children("subject", Follower.self).count()
}
public func posts() throws -> [Post] {
return try self.children(nil, Post.self).sort("date", .descending).all()
}
}
extension User: Preparation {
/// Mostly useful when setting up app on new system
public static func prepare(_ database: Database) throws {
try database.create("users") { user in
user.id()
user.string("email")
user.string("username")
user.string("password")
user.string("salt")
user.string("display_name")
user.string("profile_description")
user.string("profile_img_url")
user.int("join_date")
}
}
/// Called when you do a `vapor <something> revert` from a terminal.
public static func revert(_ database: Database) throws {
try database.delete("users");
}
}
extension User: Auth.User {
// TODO: Erh... Should salt and pepper passwords...
static func authenticate(credentials: Credentials) throws -> Auth.User {
var user: User?
switch credentials {
case let creds as UserPassword:
let passwordHash = try drop.hash.make(creds.password)
user = try User.query().filter("username", creds.username).filter("password", passwordHash).first()
case let id as Identifier:
user = try User.find(id.id)
default:
throw Abort.custom(status: .badRequest, message: "Malformed request")
}
guard let u = user else {
throw Error.invalidCredentials
}
return u
}
static func register(credentials: Credentials) throws -> Auth.User {
guard let registration = credentials as? RegistrationCredentials else {
throw Error.invalidCredentials
}
if try User.query().filter("username", registration.username.value).count() > 0 {
throw Error.usernameTaken
}
if try User.query().filter("email", registration.email.value).count() > 0 {
throw Error.emailUsed
}
let password = try drop.hash.make(registration.password)
let salt = "Totally random salt" //try URandom.bytes(count: 24).string()
var user = User(email: registration.email.value,
username: registration.username.value,
password: password,
salt: salt,
displayName: registration.username.value,
profileDescription: "",
profileImgUrl: "",
joinDate: Date())
try user.save()
return user
}
}
class UserPassword: Credentials {
public let username: String
public let password: String
public init(username: String, password: String) {
self.username = username
self.password = password
}
}
// TODO: Validation for password as well.
class RegistrationCredentials: Credentials {
public let email: Valid<Email>
public let username: Valid<OnlyAlphanumeric>
public let password: String
public init(email: Valid<Email>, username: Valid<OnlyAlphanumeric>, password: String) {
self.email = email
self.username = username
self.password = password
}
}
| mit |
Carthage/Commandant | Sources/Commandant/Argument.swift | 2 | 3858 | //
// Argument.swift
// Commandant
//
// Created by Syo Ikeda on 12/14/15.
// Copyright (c) 2015 Carthage. All rights reserved.
//
/// Describes an argument that can be provided on the command line.
public struct Argument<T> {
/// The default value for this argument. This is the value that will be used
/// if the argument is never explicitly specified on the command line.
///
/// If this is nil, this argument is always required.
public let defaultValue: T?
/// A human-readable string describing the purpose of this argument. This will
/// be shown in help messages.
public let usage: String
/// A human-readable string that describes this argument as a paramater shown
/// in the list of possible parameters in help messages (e.g. for "paths", the
/// user would see <paths…>).
public let usageParameter: String?
public init(defaultValue: T? = nil, usage: String, usageParameter: String? = nil) {
self.defaultValue = defaultValue
self.usage = usage
self.usageParameter = usageParameter
}
fileprivate func invalidUsageError<ClientError>(_ value: String) -> CommandantError<ClientError> {
let description = "Invalid value for '\(self.usageParameterDescription)': \(value)"
return .usageError(description: description)
}
}
extension Argument {
/// A string describing this argument as a parameter in help messages. This falls back
/// to `"\(self)"` if `usageParameter` is `nil`
internal var usageParameterDescription: String {
return self.usageParameter.map { "<\($0)>" } ?? "\(self)"
}
}
extension Argument where T: Sequence {
/// A string describing this argument as a parameter in help messages. This falls back
/// to `"\(self)"` if `usageParameter` is `nil`
internal var usageParameterDescription: String {
return self.usageParameter.map { "<\($0)…>" } ?? "\(self)"
}
}
// MARK: - Operators
extension CommandMode {
/// Evaluates the given argument in the given mode.
///
/// If parsing command line arguments, and no value was specified on the command
/// line, the argument's `defaultValue` is used.
public static func <| <T: ArgumentProtocol, ClientError>(mode: CommandMode, argument: Argument<T>) -> Result<T, CommandantError<ClientError>> {
switch mode {
case let .arguments(arguments):
guard let stringValue = arguments.consumePositionalArgument() else {
if let defaultValue = argument.defaultValue {
return .success(defaultValue)
} else {
return .failure(missingArgumentError(argument.usage))
}
}
if let value = T.from(string: stringValue) {
return .success(value)
} else {
return .failure(argument.invalidUsageError(stringValue))
}
case .usage:
return .failure(informativeUsageError(argument))
}
}
/// Evaluates the given argument list in the given mode.
///
/// If parsing command line arguments, and no value was specified on the command
/// line, the argument's `defaultValue` is used.
public static func <| <T: ArgumentProtocol, ClientError>(mode: CommandMode, argument: Argument<[T]>) -> Result<[T], CommandantError<ClientError>> {
switch mode {
case let .arguments(arguments):
guard let firstValue = arguments.consumePositionalArgument() else {
if let defaultValue = argument.defaultValue {
return .success(defaultValue)
} else {
return .failure(missingArgumentError(argument.usage))
}
}
var values = [T]()
guard let value = T.from(string: firstValue) else {
return .failure(argument.invalidUsageError(firstValue))
}
values.append(value)
while let nextValue = arguments.consumePositionalArgument() {
guard let value = T.from(string: nextValue) else {
return .failure(argument.invalidUsageError(nextValue))
}
values.append(value)
}
return .success(values)
case .usage:
return .failure(informativeUsageError(argument))
}
}
}
| mit |
ben-ng/swift | validation-test/compiler_crashers_fixed/00756-llvm-ondiskchainedhashtable-swift-modulefile-decltableinfo-find.swift | 1 | 539 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class func b<T>(b(#object1, object2)
protocol A : A: e: A? = F>? = c, AnyObject) -> {
protocol d {
}
return ""\(n: I.c : B) {
}
enum A : T.h
| apache-2.0 |
codefellows/sea-b19-ios | Projects/FlappyBirdSwift/FlappyBirdSwiftTests/FlappyBirdSwiftTests.swift | 1 | 926 | //
// FlappyBirdSwiftTests.swift
// FlappyBirdSwiftTests
//
// Created by Bradley Johnson on 9/1/14.
// Copyright (c) 2014 learnswift. All rights reserved.
//
import UIKit
import XCTest
class FlappyBirdSwiftTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| gpl-2.0 |
TristanBurnside/ChocolateDemo | ChocolatePuppiesTests/ChocolatePuppiesTests.swift | 1 | 1023 | //
// ChocolatePuppiesTests.swift
// ChocolatePuppiesTests
//
// Created by Tristan Burnside on 31/10/2015.
// Copyright © 2015 Tristan Burnside. All rights reserved.
//
import XCTest
@testable import ChocolatePuppies
class ChocolatePuppiesTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| apache-2.0 |
fgulan/letter-ml | project/LetterML/Frameworks/framework/Source/Operations/FalseColor.swift | 9 | 518 | public class FalseColor: BasicOperation {
public var firstColor:Color = Color(red:0.0, green:0.0, blue:0.5, alpha:1.0) { didSet { uniformSettings["firstColor"] = firstColor } }
public var secondColor:Color = Color.red { didSet { uniformSettings["secondColor"] = secondColor } }
public init() {
super.init(fragmentShader:FalseColorFragmentShader, numberOfInputs:1)
({firstColor = Color(red:0.0, green:0.0, blue:0.5, alpha:1.0)})()
({secondColor = Color.red})()
}
}
| mit |
FengDeng/RXGitHub | RxGitHubAPI/YYCommitAPI.swift | 1 | 1564 | //
// YYCommitAPI.swift
// RxGitHub
//
// Created by 邓锋 on 16/1/26.
// Copyright © 2016年 fengdeng. All rights reserved.
//
import Foundation
import RxSwift
import Moya
enum YYCommitAPI{
//List commits on a repository
case Commits(owner:String,repo:String,page:Int,sha:String,path:String,author:String,since:String,until:String)
//Get a single commit
case Commit(owner:String,repo:String,sha:String)
//Compare two commits
case CompareTwoCommits(owner:String,repo:String,base:String,head:String)
}
extension YYCommitAPI : TargetType{
var baseURL: NSURL {
return NSURL(string: "https://api.github.com")!
}
var path: String {
switch self {
case .Commits(let owner,let repo,let page,let sha,let path,let author,let since,let until):
return "/repos/\(owner)/\(repo)/commits?sha=\(sha)&path=\(path)&author=\(author)&since=\(since)&until=\(until)&page=\(page)"
case .Commit(let owner,let repo,let sha):
return "/repos/\(owner)/\(repo)/commits/\(sha)"
case .CompareTwoCommits(let owner,let repo,let base,let head):
return "/repos/\(owner)/\(repo)/compare/\(base)...\(head)"
}
}
var method: Moya.Method {
switch self {
default:
return .GET
}
}
var parameters: [String: AnyObject]? {
switch self {
default:
return nil
}
}
var sampleData: NSData {
return "No response".dataUsingEncoding(NSUTF8StringEncoding)!
}
}
| mit |
rhx/gir2swift | Sources/libgir2swift/emitting/CodeBuilder.swift | 1 | 3062 | import Foundation
/// Code Builder is a ResultBuilder class which provides easier-to-read way of composing string with indentation and new lines. Element of the DSL generated by this class is `String`. As for now, only if-else statements are available. At the time of implementation, for-in statement was not widely available.
/// - Note: ResultBuilder is merged in Swift 5.4 and available since Swift 5.1
#if swift(>=5.4)
@resultBuilder class CodeBuilder {}
#else
@_functionBuilder class CodeBuilder {}
#endif
extension CodeBuilder {
/// Ignoring sequence is introduced in order to prevent superfulous line breaks in conditions
static let unused: String = "<%IGN%>"
/// Following static methods are documented in https://github.com/apple/swift-evolution/blob/main/proposals/0289-result-builders.md
static func buildBlock( _ segments: String...) -> String {
segments.filter { $0 != CodeBuilder.unused } .joined(separator: "\n")
}
static func buildEither(first: String) -> String { first }
static func buildEither(second: String) -> String { second }
static func buildOptional(_ component: String?) -> String { component ?? CodeBuilder.unused }
static func buildIf(_ segment: String?) -> String { buildOptional(segment) }
}
/// Convenience class for using CodeBuilder DSL. This class was introduced to shorten calls. As for now, this class compensates for some missing DSL features like for-in loops.
class Code {
static var defaultCodeIndentation: String = " "
/// Code in builder block of this function will have additional indentation passed in the first argument.
/// - Parameter indentation: Intendation added on top of existing indentation. Default value is value of static property `defaultCodeIndentation`. Pass `nil` or "" to ommit indentation.
static func block(indentation: String? = defaultCodeIndentation, @CodeBuilder builder: ()->String) -> String {
let code = builder()
if let indentation = indentation {
return indentation + (code.replacingOccurrences(of: "\n", with: "\n" + indentation))
}
return builder()
}
/// Strings inside of this builder have all occurances of `\n` removed.
static func line(@CodeBuilder builder: ()->String) -> String {
builder().components(separatedBy: "\n").joined()
}
/// Loop provided as a replacement for missing for-in loop. This function will be removed in the future. For Enumerated variant use `loopEnumerated(over:builder:)`
static func loop<T>(over items: [T], @CodeBuilder builder: (T)->String) -> String {
!items.isEmpty ? items.map(builder).joined(separator: "\n") : CodeBuilder.unused
}
/// Loop provided as a replacement for missing for-in loop. Array is returned as enumerated.
static func loopEnumerated<T>(over items: [T], @CodeBuilder builder: (Int, T)->String) -> String {
!items.isEmpty ? items.enumerated().map(builder).joined(separator: "\n") : CodeBuilder.unused
}
}
| bsd-2-clause |
abelsanchezali/ViewBuilder | Source/Document/Options/FactoryOptions.swift | 1 | 235 | //
// FactoryOptions.swift
// ViewBuilder
//
// Created by Abel Sanchez on 7/10/16.
// Copyright © 2016 Abel Sanchez. All rights reserved.
//
import Foundation
open class FactoryOptions: NSObject {
open var verbose = true
}
| mit |
tilltue/TLPhotoPicker | Example/TLPhotoPicker/PreviewView.swift | 1 | 3279 | /*
See LICENSE.txt for this sample’s licensing information.
Sample code project: AVCam-iOS: Using AVFoundation to Capture Images and Movies
Version: 7.1
IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2017 Apple Inc. All Rights Reserved.
Abstract:
Application preview view.
*/
import UIKit
import AVFoundation
class PreviewView: UIView {
var videoPreviewLayer: AVCaptureVideoPreviewLayer {
guard let layer = layer as? AVCaptureVideoPreviewLayer else {
fatalError("Expected `AVCaptureVideoPreviewLayer` type for layer. Check PreviewView.layerClass implementation.")
}
layer.videoGravity = .resizeAspectFill
return layer
}
var session: AVCaptureSession? {
get {
return videoPreviewLayer.session
}
set {
videoPreviewLayer.session = newValue
}
}
// MARK: UIView
override class var layerClass: AnyClass {
return AVCaptureVideoPreviewLayer.self
}
}
| mit |
melling/ios_topics | ShapeLayer/ShapeLayer/AppDelegate.swift | 1 | 2122 | //
// AppDelegate.swift
// ShapeLayer
//
// Created by Michael Mellinger on 3/19/16.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| cc0-1.0 |
kenwilcox/Petitions | Petitions/AppDelegate.swift | 1 | 3637 | //
// AppDelegate.swift
// Petitions
//
// Created by Kenneth Wilcox on 11/11/15.
// Copyright © 2015 Kenneth Wilcox. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
let tabBarController = splitViewController.viewControllers[0] as! UITabBarController
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("NavController") as! UINavigationController
vc.tabBarItem = UITabBarItem(tabBarSystemItem: .TopRated, tag: 1)
tabBarController.viewControllers?.append(vc)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
| mit |
ahmetkgunay/AKGPushAnimator | Examples/AKGPushAnimatorDemo/AKGPushAnimator/BaseViewController.swift | 2 | 1284 | //
// BaseViewController.swift
// AKGPushAnimator
//
// Created by AHMET KAZIM GUNAY on 30/04/2017.
// Copyright © 2017 AHMET KAZIM GUNAY. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController, UINavigationControllerDelegate {
let pushAnimator = AKGPushAnimator()
let interactionAnimator = AKGInteractionAnimator()
override func viewDidLoad() {
super.viewDidLoad()
}
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if operation == .push {
interactionAnimator.attachToViewController(toVC)
}
pushAnimator.isReverseTransition = operation == .pop
return pushAnimator
}
func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactionAnimator.transitionInProgress ? interactionAnimator : nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit |
sabirvirtuoso/Kraken | Example/Trigger/ServiceBImpl.swift | 1 | 1529 | //
// Kraken
//
// Copyright (c) 2016 Syed Sabir Salman-Al-Musawi <sabirvirtuoso@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Kraken
class ServiceBImpl: ServiceB {
weak var serviceA: ServiceA?
var serviceC: ServiceC = inject(ServiceC.self)
var serviceBImplDataSource: GenericDataSource<ServiceBImpl> = inject(GenericDataSource<ServiceBImpl>.self)
required init() {
}
func myCompanyB() -> String {
return "therapB"
}
}
| mit |
jessesquires/swift-proposal-analyzer | swift-proposal-analyzer.playground/Pages/SE-0072.xcplaygroundpage/Contents.swift | 1 | 4633 | /*:
# Fully eliminate implicit bridging conversions from Swift
* Proposal: [SE-0072](0072-eliminate-implicit-bridging-conversions.md)
* Author: [Joe Pamer](https://github.com/jopamer)
* Review Manager: [Chris Lattner](https://github.com/lattner)
* Status: **Implemented (Swift 3)**
* Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2016-May/000137.html)
* Implementation: [apple/swift#2419](https://github.com/apple/swift/pull/2419)
## Introduction
In Swift 1.2, we attempted to remove all implicit bridging conversions from the language. Unfortunately, problems with how the v1.2 compiler imported various un-annotated Objective-C APIs caused us to scale back on our ambitions.
In the interest of further simplifying our type system and our user model, we would like to complete this work and fully remove implicit bridging conversions from the language in Swift 3.
This was discussed in [this swift-evolution thread.](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160418/015238.html)
## Motivation
Prior to Swift 1.2, conversions between bridged Swift value types and their associated Objective-C types could be implicitly inferred in both directions. For example, you could pass an NSString object to a function expecting a String value, and vice versa.
In time we found this model to be less than perfect for a variety of reasons:
* Allowing implicit conversions between types that lack a subtype relationship felt wrong in the context of our type system.
* Importing Foundation would lead to subtle changes in how seemingly simple bodies of code were type checked.
* The specific rules implemented by the compiler to support implicit bridging conversions were complex and ad-hoc.
* Looking at the Swift code that had been written up until 1.2, these kinds of implicit conversions did not appear terribly common. (And where they were present, it wasn’t clear if users actually knew they were taking place.)
In short, these conversions generally lead to a more confusing and unpredictable user model. So, for Swift 1.2, we sought to eliminate implicit bridging conversions entirely, and instead direct users to use explicit bridging casts in their place. (E.g., “```nsStrObj as String```”.)
Unfortunately, when it came time to roll out these changes, we noticed that some native Objective-C APIs were now more difficult to work with in Swift 1.2. Specifically, because global Objective-C ```NSString*``` constants are imported into Swift as having type String, APIs that relied on string-constant lookups into dictionaries imported as ```[NSObject : AnyObject]``` failed to compile.
For example:
```swift
var s : NSAttributedString
let SomeNSFontAttributeName : String // As per the importer.
let attrs = s.attributesAtIndex(0, effectiveRange:nil) // In Swift 2, ‘attrs’ has type [NSObject : AnyObject]
let fontName = attrs[SomeNSFontAttributeName] // This will fail to compile without an implicit conversion from String to NSString.
```
For this reason, we decided to make a compromise. We would require explicit bridging casts when converting from a bridged Objective-C type to its associated Swift value type (E.g., ```NSString -> String```), but not the other way around. This would improve the status quo somewhat, and would also avoid breaking user code in a needless/painful fashion until we could get better API annotations in place.
With the introduction of Objective-C generics last year, along with all of the awesome improvements to API importing happening for Swift 3, I think it’s time that we take another look at completing this work. Taking a look back at last year’s “problematic” APIs, all of them now surface richer type information when imported into Swift 3. As a result, the remaining implicit bridging conversions now feel far less necessary, since Objective-C APIs are now more commonly exposed in terms of their appropriate bridged Swift value types. (For instance, in Swift 3, the above reference to attrs will import as ```[String : AnyObject]```.)
## Proposed solution
I propose that we fully eliminate implicit bridging conversions in Swift 3. This would mean that some users might have to introduce more explicit casts in their code, but we would remove another special case from Swift's type system and be able to further simplify the compiler.
## Impact on existing code
Code that previously relied on implicit conversions between Swift value types and their associated bridged Objective-C type will now require a manual coercion via an ```as``` cast.
----------
[Previous](@previous) | [Next](@next)
*/
| mit |
cdmx/MiniMancera | miniMancera/Model/Option/ReformaCrossing/Node/MOptionReformaCrossingHud.swift | 1 | 1871 | import SpriteKit
class MOptionReformaCrossingHud:MGameUpdate<MOptionReformaCrossing>
{
weak var view:VOptionReformaCrossingHud?
private var elapsedTime:TimeInterval?
private let kMaxTime:TimeInterval = 32
private let kTimeDelta:TimeInterval = 0.1
override func update(
elapsedTime:TimeInterval,
scene:ViewGameScene<MOptionReformaCrossing>)
{
if let lastElapsedTime:TimeInterval = self.elapsedTime
{
let deltaTime:TimeInterval = abs(elapsedTime - lastElapsedTime)
if deltaTime > kTimeDelta
{
self.elapsedTime = elapsedTime
let score:Int = scene.controller.model.score
updateStrings(scene:scene, score:score)
}
}
else
{
self.elapsedTime = elapsedTime
}
}
//MARK: private
private func timeOut(scene:ViewGameScene<MOptionReformaCrossing>)
{
let model:MOptionReformaCrossing = scene.controller.model
model.timeOut()
let soundFail:SKAction = model.sounds.soundFail
scene.controller.playSound(actionSound:soundFail)
}
private func updateStrings(scene:ViewGameScene<MOptionReformaCrossing>, score:Int)
{
guard
let elapsedTime:TimeInterval = self.elapsedTime
else
{
return
}
let remainTime:TimeInterval = kMaxTime - elapsedTime
let scoreString:String = "\(score)"
let time:Int
if remainTime < 0
{
timeOut(scene:scene)
time = 0
}
else
{
time = Int(remainTime)
}
let timeString:String = "\(time)"
view?.update(time:timeString, score:scoreString)
}
}
| mit |
FandyLiu/Cabin | Cabin/Extension/DispatchTimeAdd.swift | 1 | 525 | //
// DispatchTimeAdd.swift
// Cabin
//
// Created by QianTuFD on 2017/7/3.
// Copyright © 2017年 fandy. All rights reserved.
// DispatchTime 字面量表达扩展
import UIKit
extension DispatchTime: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
self = DispatchTime.now() + .seconds(value)
}
}
extension DispatchTime: ExpressibleByFloatLiteral {
public init(floatLiteral value: Double) {
self = DispatchTime.now() + .milliseconds(Int(value * 1_000))
}
}
| mit |
Lordxen/MagistralSwift | Carthage/Checkouts/CryptoSwift/CryptoSwiftTests/HashTests.swift | 2 | 7591 | //
// CryptoSwiftTests.swift
// CryptoSwiftTests
//
// Created by Marcin Krzyzanowski on 06/07/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
import XCTest
@testable import CryptoSwift
final class CryptoSwiftTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testMD5_data() {
let data = [0x31, 0x32, 0x33] as Array<UInt8> // "1", "2", "3"
XCTAssertEqual(Hash.md5(data).calculate(), [0x20,0x2c,0xb9,0x62,0xac,0x59,0x07,0x5b,0x96,0x4b,0x07,0x15,0x2d,0x23,0x4b,0x70], "MD5 calculation failed");
}
func testMD5_emptyString() {
let data:NSData = "".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
XCTAssertEqual(Hash.md5(data.arrayOfBytes()).calculate(), [0xd4,0x1d,0x8c,0xd9,0x8f,0x00,0xb2,0x04,0xe9,0x80,0x09,0x98,0xec,0xf8,0x42,0x7e], "MD5 calculation failed")
}
func testMD5_string() {
XCTAssertEqual("123".md5(), "202cb962ac59075b964b07152d234b70", "MD5 calculation failed");
XCTAssertEqual("".md5(), "d41d8cd98f00b204e9800998ecf8427e", "MD5 calculation failed")
XCTAssertEqual("a".md5(), "0cc175b9c0f1b6a831c399e269772661", "MD5 calculation failed")
XCTAssertEqual("abc".md5(), "900150983cd24fb0d6963f7d28e17f72", "MD5 calculation failed")
XCTAssertEqual("message digest".md5(), "f96b697d7cb7938d525a2f31aaf161d0", "MD5 calculation failed")
XCTAssertEqual("abcdefghijklmnopqrstuvwxyz".md5(), "c3fcd3d76192e4007dfb496cca67e13b", "MD5 calculation failed")
XCTAssertEqual("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".md5(), "d174ab98d277d9f5a5611c2c9f419d9f", "MD5 calculation failed")
XCTAssertEqual("12345678901234567890123456789012345678901234567890123456789012345678901234567890".md5(), "57edf4a22be3c955ac49da2e2107b67a", "MD5 calculation failed")
}
func testMD5PerformanceSwift() {
self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: false, forBlock: { () -> Void in
let buf = UnsafeMutablePointer<UInt8>(calloc(1024 * 1024, sizeof(UInt8)))
let data = NSData(bytes: buf, length: 1024 * 1024)
let arr = data.arrayOfBytes()
self.startMeasuring()
Hash.md5(arr).calculate()
self.stopMeasuring()
buf.dealloc(1024 * 1024)
buf.destroy()
})
}
func testMD5PerformanceCommonCrypto() {
self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: false, forBlock: { () -> Void in
let buf = UnsafeMutablePointer<UInt8>(calloc(1024 * 1024, sizeof(UInt8)))
let data = NSData(bytes: buf, length: 1024 * 1024)
let outbuf = UnsafeMutablePointer<UInt8>.alloc(Int(CC_MD5_DIGEST_LENGTH))
self.startMeasuring()
CC_MD5(data.bytes, CC_LONG(data.length), outbuf)
//let output = NSData(bytes: outbuf, length: Int(CC_MD5_DIGEST_LENGTH));
self.stopMeasuring()
outbuf.dealloc(Int(CC_MD5_DIGEST_LENGTH))
outbuf.destroy()
buf.dealloc(1024 * 1024)
buf.destroy()
})
}
func testSHA1() {
let data:NSData = NSData(bytes: [0x31, 0x32, 0x33] as Array<UInt8>, length: 3)
if let hash = data.sha1() {
XCTAssertEqual(hash.toHexString(), "40bd001563085fc35165329ea1ff5c5ecbdbbeef", "SHA1 calculation failed");
}
XCTAssertEqual("abc".sha1(), "a9993e364706816aba3e25717850c26c9cd0d89d", "SHA1 calculation failed")
XCTAssertEqual("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".sha1(), "84983e441c3bd26ebaae4aa1f95129e5e54670f1", "SHA1 calculation failed")
XCTAssertEqual("".sha1(), "da39a3ee5e6b4b0d3255bfef95601890afd80709", "SHA1 calculation failed")
}
func testSHA224() {
let data:NSData = NSData(bytes: [0x31, 0x32, 0x33] as Array<UInt8>, length: 3)
if let hash = data.sha224() {
XCTAssertEqual(hash.toHexString(), "78d8045d684abd2eece923758f3cd781489df3a48e1278982466017f", "SHA224 calculation failed");
}
}
func testSHA256() {
let data:NSData = NSData(bytes: [0x31, 0x32, 0x33] as Array<UInt8>, length: 3)
if let hash = data.sha256() {
XCTAssertEqual(hash.toHexString(), "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3", "SHA256 calculation failed");
}
XCTAssertEqual("Rosetta code".sha256(), "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf", "SHA256 calculation failed")
XCTAssertEqual("".sha256(), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "SHA256 calculation failed")
}
func testSHA384() {
let data:NSData = NSData(bytes: [49, 50, 51] as Array<UInt8>, length: 3)
if let hash = data.sha384() {
XCTAssertEqual(hash.toHexString(), "9a0a82f0c0cf31470d7affede3406cc9aa8410671520b727044eda15b4c25532a9b5cd8aaf9cec4919d76255b6bfb00f", "SHA384 calculation failed");
}
XCTAssertEqual("The quick brown fox jumps over the lazy dog.".sha384(), "ed892481d8272ca6df370bf706e4d7bc1b5739fa2177aae6c50e946678718fc67a7af2819a021c2fc34e91bdb63409d7", "SHA384 calculation failed");
XCTAssertEqual("".sha384(), "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b", "SHA384 calculation failed")
}
func testSHA512() {
let data:NSData = NSData(bytes: [49, 50, 51] as Array<UInt8>, length: 3)
if let hash = data.sha512() {
XCTAssertEqual(hash.toHexString(), "3c9909afec25354d551dae21590bb26e38d53f2173b8d3dc3eee4c047e7ab1c1eb8b85103e3be7ba613b31bb5c9c36214dc9f14a42fd7a2fdb84856bca5c44c2", "SHA512 calculation failed");
}
XCTAssertEqual("The quick brown fox jumps over the lazy dog.".sha512(), "91ea1245f20d46ae9a037a989f54f1f790f0a47607eeb8a14d12890cea77a1bbc6c7ed9cf205e67b7f2b8fd4c7dfd3a7a8617e45f3c463d481c7e586c39ac1ed", "SHA512 calculation failed");
XCTAssertEqual("".sha512(), "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", "SHA512 calculation failed")
}
func testCRC32() {
let data:NSData = NSData(bytes: [49, 50, 51] as Array<UInt8>, length: 3)
if let crc = data.crc32(nil) {
XCTAssertEqual(crc.toHexString(), "884863d2", "CRC32 calculation failed");
}
XCTAssertEqual("".crc32(nil), "00000000", "CRC32 calculation failed");
}
func testCRC32NotReflected() {
let bytes : Array<UInt8> = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39]
let data:NSData = NSData(bytes: bytes, length: bytes.count)
if let crc = data.crc32(nil, reflect: false) {
XCTAssertEqual(crc.toHexString(), "fc891918", "CRC32 (with reflection) calculation failed");
}
XCTAssertEqual("".crc32(nil, reflect: false), "00000000", "CRC32 (with reflection) calculation failed");
}
func testCRC16() {
let result = CRC().crc16([49,50,51,52,53,54,55,56,57] as Array<UInt8>)
XCTAssert(result == 0xBB3D, "CRC16 failed")
}
func testChecksum() {
let data:NSData = NSData(bytes: [49, 50, 51] as Array<UInt8>, length: 3)
XCTAssert(data.checksum() == 0x96, "Invalid checksum")
}
}
| mit |
lorentey/swift | validation-test/compiler_crashers_fixed/27650-swift-metatypetype-get.swift | 65 | 480 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
var b{
enum e{{}class c
func a{
func c<I{
protocol d{
func b
func b<T where I.c:b
| apache-2.0 |
AliSoftware/SwiftGen | Sources/SwiftGenKit/Utils/YamsSerialization.swift | 1 | 2076 | //
// SwiftGenKit
// Copyright © 2020 SwiftGen
// MIT Licence
//
import Foundation
import Yams
public enum YamsSerializationError: Error {
case unableToCast(type: String)
public var description: String {
switch self {
case .unableToCast(let type):
return "Unable to cast Objective-C type '\(type)'"
}
}
}
///
/// These extensions are needed otherwise Yams can't serialize Objective-C types
///
extension NSArray: NodeRepresentable {
public func represented() throws -> Node {
guard let array = self as? [Any] else {
throw YamsSerializationError.unableToCast(type: "NSArray")
}
return try array.represented()
}
}
extension NSDate: ScalarRepresentable {
public func represented() -> Node.Scalar {
(self as Date).represented()
}
}
extension NSDictionary: NodeRepresentable {
public func represented() throws -> Node {
guard let dictionary = self as? [AnyHashable: Any] else {
throw YamsSerializationError.unableToCast(type: "NSDictionary")
}
return try dictionary.represented()
}
}
extension NSData: ScalarRepresentable {
public func represented() -> Node.Scalar {
(self as Data).represented()
}
}
extension NSNumber: ScalarRepresentable {
public func represented() -> Node.Scalar {
if CFGetTypeID(self) == CFBooleanGetTypeID() {
return boolValue.represented()
} else {
switch CFNumberGetType(self) {
case .sInt8Type:
return int8Value.represented()
case .sInt16Type:
return int16Value.represented()
case .sInt32Type:
return int32Value.represented()
case .sInt64Type:
return int64Value.represented()
case .charType:
return uint8Value.represented()
case .intType, .longType, .longLongType, .nsIntegerType:
return intValue.represented()
case .float32Type, .floatType:
return floatValue.represented()
case .float64Type, .doubleType, .cgFloatType:
return doubleValue.represented()
default:
return Double.nan.represented()
}
}
}
}
| mit |
lorentey/swift | test/IRGen/opaque_result_type_availability.swift | 9 | 750 | // RUN: %target-swift-frontend -enable-implicit-dynamic -target x86_64-apple-macosx10.9 -Onone -emit-ir %s | %FileCheck --check-prefix=MAYBE-AVAILABLE %s
// RUN: %target-swift-frontend -enable-implicit-dynamic -target x86_64-apple-macosx10.15 -Onone -emit-ir %s | %FileCheck --check-prefix=ALWAYS-AVAILABLE %s
// REQUIRES: OS=macosx
protocol P {}
extension Int: P {}
@available(macOS 10.15, *)
func foo() -> some P {
return 1738
}
@_silgen_name("external")
func generic<T: P>(x: T, y: T)
@available(macOS 10.15, *)
public func main() {
generic(x: foo(), y: foo())
}
// MAYBE-AVAILABLE: declare{{.*}} extern_weak {{.*}} @swift_getOpaqueTypeConformance
// ALWAYS-AVAILABLE-NOT: declare{{.*}} extern_weak {{.*}} @swift_getOpaqueTypeConformance
| apache-2.0 |
realm/SwiftLint | Source/SwiftLintFramework/Rules/Idiomatic/DiscouragedNoneNameRule.swift | 1 | 6682 | import SwiftSyntax
struct DiscouragedNoneNameRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
var configuration = SeverityConfiguration(.warning)
init() {}
static var description = RuleDescription(
identifier: "discouraged_none_name",
name: "Discouraged None Name",
description: "Discourages name cases/static members `none`, which can conflict with `Optional<T>.none`.",
kind: .idiomatic,
nonTriggeringExamples: [
// Should not trigger unless exactly matches "none"
Example("""
enum MyEnum {
case nOne
}
"""),
Example("""
enum MyEnum {
case _none
}
"""),
Example("""
enum MyEnum {
case none_
}
"""),
Example("""
enum MyEnum {
case none(Any)
}
"""),
Example("""
enum MyEnum {
case nonenone
}
"""),
Example("""
class MyClass {
class var nonenone: MyClass { MyClass() }
}
"""),
Example("""
class MyClass {
static var nonenone = MyClass()
}
"""),
Example("""
class MyClass {
static let nonenone = MyClass()
}
"""),
Example("""
struct MyStruct {
static var nonenone = MyStruct()
}
"""),
Example("""
struct MyStruct {
static let nonenone = MyStruct()
}
"""),
// Should not trigger if not an enum case or static/class member
Example("""
struct MyStruct {
let none = MyStruct()
}
"""),
Example("""
struct MyStruct {
var none = MyStruct()
}
"""),
Example("""
class MyClass {
let none = MyClass()
}
"""),
Example("""
class MyClass {
var none = MyClass()
}
""")
],
triggeringExamples: [
Example("""
enum MyEnum {
case ↓none
}
"""),
Example("""
enum MyEnum {
case a, ↓none
}
"""),
Example("""
enum MyEnum {
case ↓none, b
}
"""),
Example("""
enum MyEnum {
case a, ↓none, b
}
"""),
Example("""
enum MyEnum {
case a
case ↓none
}
"""),
Example("""
enum MyEnum {
case ↓none
case b
}
"""),
Example("""
enum MyEnum {
case a
case ↓none
case b
}
"""),
Example("""
class MyClass {
↓static let none = MyClass()
}
"""),
Example("""
class MyClass {
↓static let none: MyClass = MyClass()
}
"""),
Example("""
class MyClass {
↓static var none: MyClass = MyClass()
}
"""),
Example("""
class MyClass {
↓class var none: MyClass { MyClass() }
}
"""),
Example("""
struct MyStruct {
↓static var none = MyStruct()
}
"""),
Example("""
struct MyStruct {
↓static var none: MyStruct = MyStruct()
}
"""),
Example("""
struct MyStruct {
↓static var none = MyStruct()
}
"""),
Example("""
struct MyStruct {
↓static var none: MyStruct = MyStruct()
}
"""),
Example("""
struct MyStruct {
↓static var a = MyStruct(), none = MyStruct()
}
"""),
Example("""
struct MyStruct {
↓static var none = MyStruct(), a = MyStruct()
}
""")
]
)
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
Visitor(viewMode: .sourceAccurate)
}
}
private extension DiscouragedNoneNameRule {
final class Visitor: ViolationsSyntaxVisitor {
override func visitPost(_ node: EnumCaseElementSyntax) {
let emptyParams = node.associatedValue?.parameterList.isEmpty ?? true
if emptyParams, node.identifier.isNone {
violations.append(ReasonedRuleViolation(
position: node.positionAfterSkippingLeadingTrivia,
reason: reason(type: "`case`")
))
}
}
override func visitPost(_ node: VariableDeclSyntax) {
let type: String? = {
if node.modifiers.isClass {
return "`class` member"
} else if node.modifiers.isStatic {
return "`static` member"
} else {
return nil
}
}()
guard let type = type else {
return
}
for binding in node.bindings {
guard let pattern = binding.pattern.as(IdentifierPatternSyntax.self), pattern.identifier.isNone else {
continue
}
violations.append(ReasonedRuleViolation(
position: node.positionAfterSkippingLeadingTrivia,
reason: reason(type: type)
))
return
}
}
private func reason(type: String) -> String {
let reason = "Avoid naming \(type) `none` as the compiler can think you mean `Optional<T>.none`."
let recommendation = "Consider using an Optional value instead."
return "\(reason) \(recommendation)"
}
}
}
private extension TokenSyntax {
var isNone: Bool {
tokenKind == .identifier("none") || tokenKind == .identifier("`none`")
}
}
| mit |
sunshinejr/Moya-ModelMapper | Package.swift | 1 | 2011 | // swift-tools-version:5.0
import PackageDescription
import class Foundation.ProcessInfo
let shouldTest = ProcessInfo.processInfo.environment["TEST_MM"] == "1"
func resolveDependencies() -> [Package.Dependency] {
let baseDependencies: [Package.Dependency] = [
.package(url: "https://github.com/Moya/Moya.git", .upToNextMajor(from: "14.0.0")),
.package(url: "https://github.com/lyft/mapper.git", .upToNextMajor(from: "10.0.0"))
]
if shouldTest {
let testDependencies: [Package.Dependency] = [
.package(url: "https://github.com/Quick/Quick.git", .upToNextMajor(from: "2.0.0")),
.package(url: "https://github.com/Quick/Nimble.git", .upToNextMajor(from: "8.0.0"))
]
return baseDependencies + testDependencies
} else {
return baseDependencies
}
}
func resolveTargets() -> [Target] {
let baseTargets: [Target] = [
.target(name: "Moya-ModelMapper", dependencies: ["Moya", "Mapper"]),
.target(name: "RxMoya-ModelMapper", dependencies: ["Moya-ModelMapper", "RxMoya"]),
.target(name: "ReactiveMoya-ModelMapper", dependencies: ["Moya-ModelMapper", "ReactiveMoya"])
]
if shouldTest {
let testTargets: [Target] = [
.testTarget(name: "Moya-ModelMapperTests", dependencies: ["Moya-ModelMapper", "RxMoya-ModelMapper", "ReactiveMoya-ModelMapper", "Quick", "Nimble"])
]
return baseTargets + testTargets
} else {
return baseTargets
}
}
let package = Package(
name: "Moya-ModelMapper",
platforms: [
.macOS(.v10_12),
.iOS(.v10),
.tvOS(.v10),
.watchOS(.v3)
],
products: [
.library(name: "Moya-ModelMapper", targets: ["Moya-ModelMapper"]),
.library(name: "ReactiveMoya-ModelMapper", targets: ["ReactiveMoya-ModelMapper"]),
.library(name: "RxMoya-ModelMapper", targets: ["RxMoya-ModelMapper"])
],
dependencies: resolveDependencies(),
targets: resolveTargets()
)
| mit |
mzaks/FlexBuffersSwift | FlexBuffersPerformanceTest/flatBuffersBench.swift | 1 | 43241 |
// generated with FlatBuffersSchemaEditor https://github.com/mzaks/FlatBuffersSchemaEditor
import Foundation
public enum Enum : Int16 {
case Apples, Pears, Bananas
}
public struct Foo : Scalar {
public let id : UInt64
public let count : Int16
public let prefix : Int8
public let length : UInt32
}
public func ==(v1:Foo, v2:Foo) -> Bool {
return v1.id==v2.id && v1.count==v2.count && v1.prefix==v2.prefix && v1.length==v2.length
}
public struct Bar : Scalar {
public let parent : Foo
public let time : Int32
public let ratio : Float32
public let size : UInt16
}
public func ==(v1:Bar, v2:Bar) -> Bool {
return v1.parent==v2.parent && v1.time==v2.time && v1.ratio==v2.ratio && v1.size==v2.size
}
public final class FooBar {
public var sibling : Bar? = nil
public var name : String? = nil
public var rating : Float64 = 0
public var postfix : UInt8 = 0
public init(){}
public init(sibling: Bar?, name: String?, rating: Float64, postfix: UInt8){
self.sibling = sibling
self.name = name
self.rating = rating
self.postfix = postfix
}
}
public extension FooBar {
fileprivate static func create(_ reader : FlatBuffersReader, objectOffset : Offset?) -> FooBar? {
guard let objectOffset = objectOffset else {
return nil
}
if let cache = reader.cache,
let o = cache.objectPool[objectOffset] {
return o as? FooBar
}
let _result = FooBar()
if let cache = reader.cache {
cache.objectPool[objectOffset] = _result
}
_result.sibling = reader.get(objectOffset: objectOffset, propertyIndex: 0)
_result.name = reader.stringBuffer(stringOffset: reader.offset(objectOffset: objectOffset, propertyIndex: 1))?§
_result.rating = reader.get(objectOffset: objectOffset, propertyIndex: 2, defaultValue: 0)
_result.postfix = reader.get(objectOffset: objectOffset, propertyIndex: 3, defaultValue: 0)
return _result
}
}
public struct FooBar_Direct<T : FlatBuffersReader> : Hashable, FlatBuffersDirectAccess {
fileprivate let reader : T
fileprivate let myOffset : Offset
public init?<R : FlatBuffersReader>(reader: R, myOffset: Offset?) {
guard let myOffset = myOffset, let reader = reader as? T else {
return nil
}
self.reader = reader
self.myOffset = myOffset
}
public var sibling : Bar? {
get { return reader.get(objectOffset: myOffset, propertyIndex: 0)}
}
public var name : UnsafeBufferPointer<UInt8>? { get { return reader.stringBuffer(stringOffset: reader.offset(objectOffset: myOffset, propertyIndex:1)) } }
public var rating : Float64 {
get { return reader.get(objectOffset: myOffset, propertyIndex: 2, defaultValue: 0) }
}
public var postfix : UInt8 {
get { return reader.get(objectOffset: myOffset, propertyIndex: 3, defaultValue: 0) }
}
public var hashValue: Int { return Int(myOffset) }
}
public func ==<T>(t1 : FooBar_Direct<T>, t2 : FooBar_Direct<T>) -> Bool {
return t1.reader.isEqual(other: t2.reader) && t1.myOffset == t2.myOffset
}
public extension FooBar {
fileprivate func addToByteArray(_ builder : FlatBuffersBuilder) throws -> Offset {
if builder.options.uniqueTables {
if let myOffset = builder.cache[ObjectIdentifier(self)] {
return myOffset
}
}
let offset1 = try builder.insert(value: name)
try builder.startObject(withPropertyCount: 4)
try builder.insert(value : postfix, defaultValue : 0, toStartedObjectAt: 3)
try builder.insert(value : rating, defaultValue : 0, toStartedObjectAt: 2)
try builder.insert(offset: offset1, toStartedObjectAt: 1)
if let sibling = sibling {
builder.insert(value: sibling)
try builder.insertCurrentOffsetAsProperty(toStartedObjectAt: 0)
}
let myOffset = try builder.endObject()
if builder.options.uniqueTables {
builder.cache[ObjectIdentifier(self)] = myOffset
}
return myOffset
}
}
public final class FooBarContainer {
public var list : [FooBar] = []
public var initialized : Bool = false
public var fruit : Enum? = Enum.Apples
public var location : String? = nil
public init(){}
public init(list: [FooBar], initialized: Bool, fruit: Enum?, location: String?){
self.list = list
self.initialized = initialized
self.fruit = fruit
self.location = location
}
}
public extension FooBarContainer {
fileprivate static func create(_ reader : FlatBuffersReader, objectOffset : Offset?) -> FooBarContainer? {
guard let objectOffset = objectOffset else {
return nil
}
if let cache = reader.cache,
let o = cache.objectPool[objectOffset] {
return o as? FooBarContainer
}
let _result = FooBarContainer()
if let cache = reader.cache {
cache.objectPool[objectOffset] = _result
}
let offset_list : Offset? = reader.offset(objectOffset: objectOffset, propertyIndex: 0)
let length_list = reader.vectorElementCount(vectorOffset: offset_list)
if(length_list > 0){
var index = 0
_result.list.reserveCapacity(length_list)
while index < length_list {
if let element = FooBar.create(reader, objectOffset: reader.vectorElementOffset(vectorOffset: offset_list, index: index)) {
_result.list.append(element)
}
index += 1
}
}
_result.initialized = reader.get(objectOffset: objectOffset, propertyIndex: 1, defaultValue: false)
_result.fruit = Enum(rawValue: reader.get(objectOffset: objectOffset, propertyIndex: 2, defaultValue: Enum.Apples.rawValue))
_result.location = reader.stringBuffer(stringOffset: reader.offset(objectOffset: objectOffset, propertyIndex: 3))?§
return _result
}
}
public extension FooBarContainer {
public static func makeFooBarContainer(data : Data, cache : FlatBuffersReaderCache? = FlatBuffersReaderCache()) -> FooBarContainer? {
let reader = FlatBuffersMemoryReader(data: data, cache: cache)
return makeFooBarContainer(reader: reader)
}
public static func makeFooBarContainer(reader : FlatBuffersReader) -> FooBarContainer? {
let objectOffset = reader.rootObjectOffset
return create(reader, objectOffset : objectOffset)
}
}
public extension FooBarContainer {
public func encode(withBuilder builder : FlatBuffersBuilder) throws -> Void {
let offset = try addToByteArray(builder)
try builder.finish(offset: offset, fileIdentifier: nil)
}
public func makeData(withOptions options : FlatBuffersBuilderOptions = FlatBuffersBuilderOptions()) throws -> Data {
let builder = FlatBuffersBuilder(options: options)
try encode(withBuilder: builder)
return builder.makeData
}
}
public struct FooBarContainer_Direct<T : FlatBuffersReader> : Hashable, FlatBuffersDirectAccess {
fileprivate let reader : T
fileprivate let myOffset : Offset
public init?<R : FlatBuffersReader>(reader: R, myOffset: Offset?) {
guard let myOffset = myOffset, let reader = reader as? T else {
return nil
}
self.reader = reader
self.myOffset = myOffset
}
public init?(_ reader: T) {
self.reader = reader
guard let offest = reader.rootObjectOffset else {
return nil
}
self.myOffset = offest
}
public var list : FlatBuffersTableVector<FooBar_Direct<T>, T> {
let offsetList = reader.offset(objectOffset: myOffset, propertyIndex: 0)
return FlatBuffersTableVector(reader: self.reader, myOffset: offsetList)
}
public var initialized : Bool {
get { return reader.get(objectOffset: myOffset, propertyIndex: 1, defaultValue: false) }
}
public var fruit : Enum? {
get { return Enum(rawValue: reader.get(objectOffset: myOffset, propertyIndex: 2, defaultValue: Enum.Apples.rawValue)) }
}
public var location : UnsafeBufferPointer<UInt8>? { get { return reader.stringBuffer(stringOffset: reader.offset(objectOffset: myOffset, propertyIndex:3)) } }
public var hashValue: Int { return Int(myOffset) }
}
public func ==<T>(t1 : FooBarContainer_Direct<T>, t2 : FooBarContainer_Direct<T>) -> Bool {
return t1.reader.isEqual(other: t2.reader) && t1.myOffset == t2.myOffset
}
public extension FooBarContainer {
fileprivate func addToByteArray(_ builder : FlatBuffersBuilder) throws -> Offset {
if builder.options.uniqueTables {
if let myOffset = builder.cache[ObjectIdentifier(self)] {
return myOffset
}
}
let offset3 = try builder.insert(value: location)
var offset0 = Offset(0)
if list.count > 0{
var offsets = [Offset?](repeating: nil, count: list.count)
var index = list.count - 1
while(index >= 0){
offsets[index] = try list[index].addToByteArray(builder)
index -= 1
}
try builder.startVector(count: list.count, elementSize: MemoryLayout<Offset>.stride)
index = list.count - 1
while(index >= 0){
try builder.insert(offset: offsets[index])
index -= 1
}
offset0 = builder.endVector()
}
try builder.startObject(withPropertyCount: 4)
try builder.insert(offset: offset3, toStartedObjectAt: 3)
try builder.insert(value : fruit?.rawValue ?? 0, defaultValue : 0, toStartedObjectAt: 2)
try builder.insert(value : initialized, defaultValue : false, toStartedObjectAt: 1)
if list.count > 0 {
try builder.insert(offset: offset0, toStartedObjectAt: 0)
}
let myOffset = try builder.endObject()
if builder.options.uniqueTables {
builder.cache[ObjectIdentifier(self)] = myOffset
}
return myOffset
}
}
// MARK: Reader
public protocol FlatBuffersReader {
var cache : FlatBuffersReaderCache? {get}
/**
Access a scalar value directly from the underlying reader buffer.
- parameters:
- offset: The offset to read from in the buffer
- Returns: a scalar value at a given offset from the buffer.
*/
func scalar<T : Scalar>(at offset: Int) throws -> T
/**
Access a subrange from the underlying reader buffer
- parameters:
- offset: The offset to read from in the buffer
- length: The amount of data to include from the buffer
- Returns: a direct pointer to a subrange from the underlying reader buffer.
*/
func bytes(at offset : Int, length : Int) throws -> UnsafeBufferPointer<UInt8>
func isEqual(other : FlatBuffersReader) -> Bool
}
fileprivate enum FlatBuffersReaderError : Error {
case outOfBufferBounds /// Trying to address outside of the bounds of the underlying buffer
case canNotSetProperty
}
public class FlatBuffersReaderCache {
public var objectPool : [Offset : AnyObject] = [:]
func reset(){
objectPool.removeAll(keepingCapacity: true)
}
public init(){}
}
public extension FlatBuffersReader {
/**
Retrieve the offset of a property from the vtable.
- parameters:
- objectOffset: The offset of the object
- propertyIndex: The property to extract
- Returns: the object-local offset of a given property by looking it up in the vtable
*/
private func propertyOffset(objectOffset : Offset, propertyIndex : Int) -> Int {
guard propertyIndex >= 0 else {
return 0
}
do {
let offset = Int(objectOffset)
let localOffset : Int32 = try scalar(at: offset)
let vTableOffset : Int = offset - Int(localOffset)
let vTableLength : Int16 = try scalar(at: vTableOffset)
let objectLength : Int16 = try scalar(at: vTableOffset + 2)
let positionInVTable = 4 + propertyIndex * 2
if (vTableLength<=Int16(positionInVTable)) {
return 0
}
let propertyStart = vTableOffset + positionInVTable
let propOffset : Int16 = try scalar(at: propertyStart)
if (objectLength<=propOffset) {
return 0
}
return Int(propOffset)
} catch {
return 0 // Currently don't want to propagate the error
}
}
/**
Retrieve the final offset of a property to be able to access it
- parameters:
- objectOffset: The offset of the object
- propertyIndex: The property to extract
- Returns: the final offset in the reader buffer to access a given property for a given object-offset
*/
public func offset(objectOffset : Offset, propertyIndex : Int) -> Offset? {
let propOffset = propertyOffset(objectOffset: objectOffset, propertyIndex: propertyIndex)
if propOffset == 0 {
return nil
}
let position = objectOffset + Offset(propOffset)
do {
let localObjectOffset : Int32 = try scalar(at: Int(position))
let offset = position + localObjectOffset
if localObjectOffset == 0 {
return nil
}
return offset
} catch {
return nil
}
}
/**
Retrieve the count of elements in an embedded vector
- parameters:
- vectorOffset: The offset of the vector in the buffer
- Returns: the number of elements in the vector
*/
public func vectorElementCount(vectorOffset : Offset?) -> Int {
guard let vectorOffset = vectorOffset else {
return 0
}
let vectorPosition = Int(vectorOffset)
do {
let length2 : Int32 = try scalar(at: vectorPosition)
return Int(length2)
} catch {
return 0
}
}
/**
Retrieve an element offset from a vector
- parameters:
- vectorOffset: The offset of the vector in the buffer
- index: The index of the element we want the offset for
- Returns: the offset in the buffer for a given vector element
*/
public func vectorElementOffset(vectorOffset : Offset?, index : Int) -> Offset? {
guard let vectorOffset = vectorOffset else {
return nil
}
guard index >= 0 else{
return nil
}
guard index < vectorElementCount(vectorOffset: vectorOffset) else {
return nil
}
let valueStartPosition = Int(Int(vectorOffset) + MemoryLayout<Int32>.stride + (index * MemoryLayout<Int32>.stride))
do {
let localOffset : Int32 = try scalar(at: valueStartPosition)
if(localOffset == 0){
return nil
}
return localOffset + Offset(valueStartPosition)
} catch {
return nil
}
}
/**
Retrieve a scalar value from a vector
- parameters:
- vectorOffset: The offset of the vector in the buffer
- index: The index of the element we want the offset for
- Returns: a scalar value directly from a vector for a given index
*/
public func vectorElementScalar<T : Scalar>(vectorOffset : Offset?, index : Int) -> T? {
guard let vectorOffset = vectorOffset else {
return nil
}
guard index >= 0 else{
return nil
}
guard index < vectorElementCount(vectorOffset: vectorOffset) else {
return nil
}
let valueStartPosition = Int(Int(vectorOffset) + MemoryLayout<Int32>.stride + (index * MemoryLayout<T>.stride))
do {
return try scalar(at: valueStartPosition) as T
} catch {
return nil
}
}
/**
Retrieve a scalar value or supply a default if unavailable
- parameters:
- objectOffset: The offset of the object
- propertyIndex: The property to try to extract
- defaultValue: The default value to return if the property is not in the buffer
- Returns: a scalar value directly from a vector for a given index
*/
public func get<T : Scalar>(objectOffset : Offset, propertyIndex : Int, defaultValue : T) -> T {
let propOffset = propertyOffset(objectOffset: objectOffset, propertyIndex: propertyIndex)
if propOffset == 0 {
return defaultValue
}
let position = Int(objectOffset + Offset(propOffset))
do {
return try scalar(at: position)
} catch {
return defaultValue
}
}
/**
Retrieve a scalar optional value (return nil if unavailable)
- parameters:
- objectOffset: The offset of the object
- propertyIndex: The property to try to extract
- Returns: a scalar value directly from a vector for a given index
*/
public func get<T : Scalar>(objectOffset : Offset, propertyIndex : Int) -> T? {
let propOffset = propertyOffset(objectOffset: objectOffset, propertyIndex: propertyIndex)
if propOffset == 0 {
return nil
}
let position = Int(objectOffset + Offset(propOffset))
do {
return try scalar(at: position) as T
} catch {
return nil
}
}
/**
Retrieve a stringbuffer
- parameters:
- stringOffset: The offset of the string
- Returns: a buffer pointer to the subrange of the reader buffer occupied by a string
*/
public func stringBuffer(stringOffset : Offset?) -> UnsafeBufferPointer<UInt8>? {
guard let stringOffset = stringOffset else {
return nil
}
let stringPosition = Int(stringOffset)
do {
let stringLength : Int32 = try scalar(at: stringPosition)
let stringCharactersPosition = stringPosition + MemoryLayout<Int32>.stride
return try bytes(at: stringCharactersPosition, length: Int(stringLength))
} catch {
return nil
}
}
/**
Retrieve the root object offset
- Returns: the offset for the root table object
*/
public var rootObjectOffset : Offset? {
do {
return try scalar(at: 0) as Offset
} catch {
return nil
}
}
}
/// A FlatBuffers reader subclass that by default reads directly from a memory buffer, but also supports initialization from Data objects for convenience
public final class FlatBuffersMemoryReader : FlatBuffersReader {
private let count : Int
public let cache : FlatBuffersReaderCache?
private let buffer : UnsafeRawPointer
private let originalBuffer : UnsafeMutableBufferPointer<UInt8>!
/**
Initializes the reader directly from a raw memory buffer.
- parameters:
- buffer: A raw pointer to the underlying data to be parsed
- count: The size of the data buffer
- cache: An optional cache of reader objects for reuse
- Returns: A FlatBuffers reader ready for use.
*/
public init(buffer : UnsafeRawPointer, count : Int, cache : FlatBuffersReaderCache? = FlatBuffersReaderCache()) {
self.buffer = buffer
self.count = count
self.cache = cache
self.originalBuffer = nil
}
/**
Initializes the reader from a Data object.
- parameters:
- data: A Data object holding the data to be parsed, the contents may be copied, for performance sensitive implementations,
the UnsafeRawsPointer initializer should be used.
- withoutCopy: set it to true if you want to avoid copying the buffer. This implies that you have to keep a reference to data object around.
- cache: An optional cache of reader objects for reuse
- Returns: A FlatBuffers reader ready for use.
*/
public init(data : Data, withoutCopy: Bool = false, cache : FlatBuffersReaderCache? = FlatBuffersReaderCache()) {
self.count = data.count
self.cache = cache
if withoutCopy {
var pointer : UnsafePointer<UInt8>! = nil
data.withUnsafeBytes { (u8Ptr: UnsafePointer<UInt8>) in
pointer = u8Ptr
}
self.buffer = UnsafeRawPointer(pointer)
self.originalBuffer = nil
} else {
let pointer : UnsafeMutablePointer<UInt8> = UnsafeMutablePointer.allocate(capacity: data.count)
self.originalBuffer = UnsafeMutableBufferPointer(start: pointer, count: data.count)
_ = data.copyBytes(to: originalBuffer)
self.buffer = UnsafeRawPointer(pointer)
}
}
deinit {
if let originalBuffer = originalBuffer,
let pointer = originalBuffer.baseAddress {
pointer.deinitialize(count: count)
}
}
public func scalar<T : Scalar>(at offset: Int) throws -> T {
if offset + MemoryLayout<T>.stride > count || offset < 0 {
throw FlatBuffersReaderError.outOfBufferBounds
}
return buffer.load(fromByteOffset: offset, as: T.self)
}
public func bytes(at offset : Int, length : Int) throws -> UnsafeBufferPointer<UInt8> {
if Int(offset + length) > count {
throw FlatBuffersReaderError.outOfBufferBounds
}
let pointer = buffer.advanced(by:offset).bindMemory(to: UInt8.self, capacity: length)
return UnsafeBufferPointer<UInt8>.init(start: pointer, count: Int(length))
}
public func isEqual(other: FlatBuffersReader) -> Bool{
guard let other = other as? FlatBuffersMemoryReader else {
return false
}
return self.buffer == other.buffer
}
}
/// A FlatBuffers reader subclass that reads directly from a file handle
public final class FlatBuffersFileReader : FlatBuffersReader {
private let fileSize : UInt64
private let fileHandle : FileHandle
public let cache : FlatBuffersReaderCache?
/**
Initializes the reader from a FileHandle object.
- parameters:
- fileHandle: A FileHandle object referencing the file we read from.
- cache: An optional cache of reader objects for reuse
- Returns: A FlatBuffers reader ready for use.
*/
public init(fileHandle : FileHandle, cache : FlatBuffersReaderCache? = FlatBuffersReaderCache()){
self.fileHandle = fileHandle
fileSize = fileHandle.seekToEndOfFile()
self.cache = cache
}
private struct DataCacheKey : Hashable {
let offset : Int
let lenght : Int
static func ==(a : DataCacheKey, b : DataCacheKey) -> Bool {
return a.offset == b.offset && a.lenght == b.lenght
}
var hashValue: Int {
return offset
}
}
private var dataCache : [DataCacheKey:Data] = [:]
public func clearDataCache(){
dataCache.removeAll(keepingCapacity: true)
}
public func scalar<T : Scalar>(at offset: Int) throws -> T {
let seekPosition = UInt64(offset)
let length = MemoryLayout<T>.stride
if seekPosition + UInt64(length) > fileSize {
throw FlatBuffersReaderError.outOfBufferBounds
}
let cacheKey = DataCacheKey(offset: offset, lenght: length)
let data : Data
if let _data = dataCache[cacheKey] {
data = _data
} else {
fileHandle.seek(toFileOffset: UInt64(offset))
data = fileHandle.readData(ofLength:Int(length))
dataCache[cacheKey] = data
}
return data.withUnsafeBytes { (pointer) -> T in
return pointer.pointee
}
}
public func bytes(at offset : Int, length : Int) throws -> UnsafeBufferPointer<UInt8> {
if UInt64(offset + length) > fileSize {
throw FlatBuffersReaderError.outOfBufferBounds
}
let cacheKey = DataCacheKey(offset: offset, lenght: length)
let data : Data
if let _data = dataCache[cacheKey] {
data = _data
} else {
fileHandle.seek(toFileOffset: UInt64(offset))
data = fileHandle.readData(ofLength:Int(length))
dataCache[cacheKey] = data
}
var t : UnsafeBufferPointer<UInt8>! = nil
data.withUnsafeBytes{
t = UnsafeBufferPointer(start: $0, count: length)
}
return t
}
public func isEqual(other: FlatBuffersReader) -> Bool{
guard let other = other as? FlatBuffersFileReader else {
return false
}
return self.fileHandle === other.fileHandle
}
}
postfix operator §
public postfix func §(value: UnsafeBufferPointer<UInt8>) -> String? {
guard let p = value.baseAddress else {
return nil
}
return String.init(bytesNoCopy: UnsafeMutablePointer<UInt8>(mutating: p), length: value.count, encoding: String.Encoding.utf8, freeWhenDone: false)
}
public protocol FlatBuffersDirectAccess {
init?<R : FlatBuffersReader>(reader: R, myOffset: Offset?)
}
public struct FlatBuffersTableVector<T: FlatBuffersDirectAccess, R : FlatBuffersReader> : Collection {
public let count : Int
fileprivate let reader : R
fileprivate let myOffset : Offset?
public init(reader: R, myOffset: Offset?){
self.reader = reader
self.myOffset = myOffset
self.count = reader.vectorElementCount(vectorOffset: myOffset)
}
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return count
}
public func index(after i: Int) -> Int {
return i+1
}
public subscript(i : Int) -> T? {
let offset = reader.vectorElementOffset(vectorOffset: myOffset, index: i)
return T(reader: reader, myOffset: offset)
}
}
public struct FlatBuffersScalarVector<T: Scalar, R : FlatBuffersReader> : Collection {
public let count : Int
fileprivate let reader : R
fileprivate let myOffset : Offset?
public init(reader: R, myOffset: Offset?){
self.reader = reader
self.myOffset = myOffset
self.count = reader.vectorElementCount(vectorOffset: myOffset)
}
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return count
}
public func index(after i: Int) -> Int {
return i+1
}
public subscript(i : Int) -> T? {
return reader.vectorElementScalar(vectorOffset: myOffset, index: i)
}
}
public struct FlatBuffersStringVector<R : FlatBuffersReader> : Collection {
public let count : Int
fileprivate let reader : R
fileprivate let myOffset : Offset?
public init(reader: R, myOffset: Offset?){
self.reader = reader
self.myOffset = myOffset
self.count = reader.vectorElementCount(vectorOffset: myOffset)
}
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return count
}
public func index(after i: Int) -> Int {
return i+1
}
public subscript(i : Int) -> UnsafeBufferPointer<UInt8>? {
let offset = reader.vectorElementOffset(vectorOffset: myOffset, index: i)
return reader.stringBuffer(stringOffset: offset)
}
}
// MARK: Builder
public typealias Offset = Int32
public protocol Scalar : Equatable {}
extension Bool : Scalar {}
extension Int8 : Scalar {}
extension UInt8 : Scalar {}
extension Int16 : Scalar {}
extension UInt16 : Scalar {}
extension Int32 : Scalar {}
extension UInt32 : Scalar {}
extension Int64 : Scalar {}
extension UInt64 : Scalar {}
extension Int : Scalar {}
extension UInt : Scalar {}
extension Float32 : Scalar {}
extension Float64 : Scalar {}
/// Various options for the builder
public struct FlatBuffersBuilderOptions {
public let initialCapacity : Int
public let uniqueStrings : Bool
public let uniqueTables : Bool
public let uniqueVTables : Bool
public let forceDefaults : Bool
public let nullTerminatedUTF8 : Bool
public init(initialCapacity : Int = 1, uniqueStrings : Bool = true, uniqueTables : Bool = true, uniqueVTables : Bool = true, forceDefaults : Bool = false, nullTerminatedUTF8 : Bool = false) {
self.initialCapacity = initialCapacity
self.uniqueStrings = uniqueStrings
self.uniqueTables = uniqueTables
self.uniqueVTables = uniqueVTables
self.forceDefaults = forceDefaults
self.nullTerminatedUTF8 = nullTerminatedUTF8
}
}
public enum FlatBuffersBuildError : Error {
case objectIsNotClosed
case noOpenObject
case propertyIndexIsInvalid
case offsetIsTooBig
case cursorIsInvalid
case badFileIdentifier
case unsupportedType
}
/// A FlatBuffers builder that supports the generation of flatbuffers 'wire' format from an object graph
public final class FlatBuffersBuilder {
public var options : FlatBuffersBuilderOptions
private var capacity : Int
private var _data : UnsafeMutableRawPointer
private var minalign = 1;
private var cursor = 0
private var leftCursor : Int {
return capacity - cursor
}
private var currentVTable : ContiguousArray<Int32> = []
private var objectStart : Int32 = -1
private var vectorNumElems : Int32 = -1;
private var vTableOffsets : ContiguousArray<Int32> = []
public var cache : [ObjectIdentifier : Offset] = [:]
public var inProgress : Set<ObjectIdentifier> = []
public var deferedBindings : ContiguousArray<(object:Any, cursor:Int)> = []
/**
Initializes the builder
- parameters:
- options: The options to use for this builder.
- Returns: A FlatBuffers builder ready for use.
*/
public init(options _options : FlatBuffersBuilderOptions = FlatBuffersBuilderOptions()) {
self.options = _options
self.capacity = self.options.initialCapacity
_data = UnsafeMutableRawPointer.allocate(byteCount: capacity, alignment: minalign)
}
/**
Allocates and returns a Data object initialized from the builder backing store
- Returns: A Data object initilized with the data from the builder backing store
*/
public var makeData : Data {
return Data(bytes:_data.advanced(by:leftCursor), count: cursor)
}
/**
Reserve enough space to store at a minimum size more data and resize the
underlying buffer if needed.
The data should be consumed by the builder immediately after reservation.
- parameters:
- size: The additional size that will be consumed by the builder
immedieatly after the call
*/
private func reserveAdditionalCapacity(size : Int){
guard leftCursor <= size else {
return
}
let _leftCursor = leftCursor
let _capacity = capacity
while leftCursor <= size {
capacity = capacity << 1
}
let newData = UnsafeMutableRawPointer.allocate(byteCount: capacity, alignment: minalign)
newData.advanced(by:leftCursor).copyMemory(from: _data.advanced(by: _leftCursor), byteCount: cursor)
_data.deallocate()
_data = newData
}
/**
Perform alignment for a value of a given size by performing padding in advance
of actually putting the value to the buffer.
- parameters:
- size: xxx
- additionalBytes: xxx
*/
private func align(size : Int, additionalBytes : Int){
if size > minalign {
minalign = size
}
let alignSize = ((~(cursor + additionalBytes)) + 1) & (size - 1)
reserveAdditionalCapacity(size: alignSize)
cursor += alignSize
}
/**
Add a scalar value to the buffer
- parameters:
- value: The value to add to the buffer
*/
public func insert<T : Scalar>(value : T){
let c = MemoryLayout.stride(ofValue: value)
if c > 8 {
align(size: 8, additionalBytes: c)
} else {
align(size: c, additionalBytes: 0)
}
reserveAdditionalCapacity(size: c)
_data.storeBytes(of: value, toByteOffset: leftCursor-c, as: T.self)
cursor += c
}
/**
Make offset relative and add it to the buffer
- parameters:
- offset: The offset to transform and add to the buffer
*/
@discardableResult
public func insert(offset : Offset?) throws -> Int {
guard let offset = offset else {
insert(value: Offset(0))
return cursor
}
guard offset <= Int32(cursor) else {
throw FlatBuffersBuildError.offsetIsTooBig
}
if offset == Int32(0) {
insert(value: Offset(0))
return cursor
}
align(size: 4, additionalBytes: 0)
let _offset = Offset(cursor) - offset + Offset(MemoryLayout<Int32>.stride);
insert(value: _offset)
return cursor
}
/**
Update an offset in place
- parameters:
- offset: The new offset to transform and add to the buffer
- atCursor: The position to put the new offset to
*/
public func update(offset : Offset, atCursor jumpCursor: Int) throws{
guard offset <= Int32(cursor) else {
throw FlatBuffersBuildError.offsetIsTooBig
}
guard jumpCursor <= cursor else {
throw FlatBuffersBuildError.cursorIsInvalid
}
let _offset = Int32(jumpCursor) - offset;
_data.storeBytes(of: _offset, toByteOffset: capacity - jumpCursor, as: Int32.self)
}
/**
Update a scalar in place
- parameters:
- value: The new value
- index: The position to modify
*/
private func update<T : Scalar>(value : T, at index : Int) {
_data.storeBytes(of: value, toByteOffset: index + leftCursor, as: T.self)
}
/**
Start an object construction sequence
- parameters:
- withPropertyCount: The number of properties we will update
*/
public func startObject(withPropertyCount : Int) throws {
guard objectStart == -1 && vectorNumElems == -1 else {
throw FlatBuffersBuildError.objectIsNotClosed
}
currentVTable.removeAll(keepingCapacity: true)
currentVTable.reserveCapacity(withPropertyCount)
for _ in 0..<withPropertyCount {
currentVTable.append(0)
}
objectStart = Int32(cursor)
}
/**
Add an offset into the buffer for the currently open object
- parameters:
- propertyIndex: The index of the property to update
- offset: The offsetnumber of properties we will update
- Returns: The current cursor position (Note: What is the use case of the return value?)
*/
@discardableResult
public func insert(offset : Offset, toStartedObjectAt propertyIndex : Int) throws -> Int{
guard objectStart > -1 else {
throw FlatBuffersBuildError.noOpenObject
}
guard propertyIndex >= 0 && propertyIndex < currentVTable.count else {
throw FlatBuffersBuildError.propertyIndexIsInvalid
}
_ = try insert(offset: offset)
currentVTable[propertyIndex] = Int32(cursor)
return cursor
}
/**
Add a scalar into the buffer for the currently open object
- parameters:
- propertyIndex: The index of the property to update
- value: The value to append
- defaultValue: If configured to skip default values, a value
matching this default value will not be written to the buffer.
*/
public func insert<T : Scalar>(value : T, defaultValue : T, toStartedObjectAt propertyIndex : Int) throws {
guard objectStart > -1 else {
throw FlatBuffersBuildError.noOpenObject
}
guard propertyIndex >= 0 && propertyIndex < currentVTable.count else {
throw FlatBuffersBuildError.propertyIndexIsInvalid
}
if(options.forceDefaults == false && value == defaultValue) {
return
}
insert(value: value)
currentVTable[propertyIndex] = Int32(cursor)
}
/**
Add the current cursor position into the buffer for the currently open object
- parameters:
- propertyIndex: The index of the property to update
*/
public func insertCurrentOffsetAsProperty(toStartedObjectAt propertyIndex : Int) throws {
guard objectStart > -1 else {
throw FlatBuffersBuildError.noOpenObject
}
guard propertyIndex >= 0 && propertyIndex < currentVTable.count else {
throw FlatBuffersBuildError.propertyIndexIsInvalid
}
currentVTable[propertyIndex] = Int32(cursor)
}
/**
Close the current open object.
*/
public func endObject() throws -> Offset {
guard objectStart > -1 else {
throw FlatBuffersBuildError.noOpenObject
}
align(size: 4, additionalBytes: 0)
reserveAdditionalCapacity(size: 4)
cursor += 4 // Will be set to vtable offset afterwards
let vtableloc = cursor
// vtable is stored as relative offset for object data
var index = currentVTable.count - 1
while(index>=0) {
// Offset relative to the start of the table.
let off = Int16(currentVTable[index] != 0 ? Int32(vtableloc) - currentVTable[index] : Int32(0));
insert(value: off);
index -= 1
}
let numberOfstandardFields = 2
insert(value: Int16(Int32(vtableloc) - objectStart)); // standard field 1: lenght of the object data
insert(value: Int16((currentVTable.count + numberOfstandardFields) * MemoryLayout<Int16>.stride)); // standard field 2: length of vtable and standard fields them selves
// search if we already have same vtable
let vtableDataLength = cursor - vtableloc
var foundVTableOffset = vtableDataLength
if options.uniqueVTables{
for otherVTableOffset in vTableOffsets {
let start = cursor - Int(otherVTableOffset)
var found = true
for i in 0 ..< vtableDataLength {
let a = _data.advanced(by:leftCursor + i).assumingMemoryBound(to: UInt8.self).pointee
let b = _data.advanced(by:leftCursor + i + start).assumingMemoryBound(to: UInt8.self).pointee
if a != b {
found = false
break;
}
}
if found == true {
foundVTableOffset = Int(otherVTableOffset) - vtableloc
break
}
}
if foundVTableOffset != vtableDataLength {
cursor -= vtableDataLength
} else {
vTableOffsets.append(Int32(cursor))
}
}
let indexLocation = cursor - vtableloc
update(value: Int32(foundVTableOffset), at: indexLocation)
objectStart = -1
return Offset(vtableloc)
}
/**
Start a vector update operation
- parameters:
- count: The number of elements in the vector
- elementSize: The size of the vector elements
*/
public func startVector(count : Int, elementSize : Int) throws{
align(size: 4, additionalBytes: count * elementSize)
guard objectStart == -1 && vectorNumElems == -1 else {
throw FlatBuffersBuildError.objectIsNotClosed
}
vectorNumElems = Int32(count)
}
/**
Finish vector update operation
*/
public func endVector() -> Offset {
insert(value: vectorNumElems)
vectorNumElems = -1
return Int32(cursor)
}
private var stringCache : [String:Offset] = [:]
/**
Add a string to the buffer
- parameters:
- value: The string to add to the buffer
- Returns: The current cursor position (Note: What is the use case of the return value?)
*/
public func insert(value : String?) throws -> Offset {
guard objectStart == -1 && vectorNumElems == -1 else {
throw FlatBuffersBuildError.objectIsNotClosed
}
guard let value = value else {
return 0
}
if options.uniqueStrings{
if let o = stringCache[value]{
return o
}
}
// TODO: Performance Test
if options.nullTerminatedUTF8 {
let utf8View = value.utf8CString
let length = utf8View.count
align(size: 4, additionalBytes: length)
reserveAdditionalCapacity(size: length)
for c in utf8View.lazy.reversed() {
insert(value: c)
}
insert(value: Int32(length - 1))
} else {
let utf8View = value.utf8
let length = utf8View.count
align(size: 4, additionalBytes: length)
reserveAdditionalCapacity(size: length)
for c in utf8View.lazy.reversed() {
insert(value: c)
}
insert(value: Int32(length))
}
let o = Offset(cursor)
if options.uniqueStrings {
stringCache[value] = o
}
return o
}
public func finish(offset : Offset, fileIdentifier : String?) throws -> Void {
guard offset <= Int32(cursor) else {
throw FlatBuffersBuildError.offsetIsTooBig
}
guard objectStart == -1 && vectorNumElems == -1 else {
throw FlatBuffersBuildError.objectIsNotClosed
}
var prefixLength = 4
if let fileIdentifier = fileIdentifier {
prefixLength += 4
align(size: minalign, additionalBytes: prefixLength)
let utf8View = fileIdentifier.utf8
let count = utf8View.count
guard count == 4 else {
throw FlatBuffersBuildError.badFileIdentifier
}
for c in utf8View.lazy.reversed() {
insert(value: c)
}
} else {
align(size: minalign, additionalBytes: prefixLength)
}
let v = (Int32(cursor + 4) - offset)
insert(value: v)
}
}
| mit |
mzaks/FlexBuffersSwift | FlexBuffersTests/FlexBufferDecodeTest.swift | 1 | 8073 | //
// FlexBufferDecodeTest.swift
// FlexBuffers
//
// Created by Maxim Zaks on 30.12.16.
// Copyright © 2016 Maxim Zaks. All rights reserved.
//
import XCTest
import FlexBuffers
class FlexBufferDecodeTest: XCTestCase {
func testReadInt8() {
let data = Data([25, 4, 1])
let v = FlexBuffer.decode(data: data)?.asInt
XCTAssertEqual(v, 25)
}
func testReadInt8Negative() {
let data = Data([231, 4, 1])
let v = FlexBuffer.decode(data: data)?.asInt
XCTAssertEqual(v, -25)
}
func testReadInt16() {
let data = Data([1, 4, 5, 2])
let v = FlexBuffer.decode(data: data)?.asInt
XCTAssertEqual(v, 1025)
}
func testReadInt32() {
let data = Data([255, 255, 255, 127, 6, 4])
let v = FlexBuffer.decode(data: data)?.asInt
XCTAssertEqual(v, Int(Int32.max))
}
func testReadInt64() {
let data = Data([255, 255, 255, 255, 255, 255, 255, 127, 7, 8])
let v = FlexBuffer.decode(data: data)?.asInt
XCTAssertEqual(v, Int(Int64.max))
}
func testReadInt64_WithRightAccessor() {
let data = Data([255, 255, 255, 255, 255, 255, 255, 127, 7, 8])
let v = FlexBuffer.decode(data: data)?.asInt64
XCTAssertEqual(v, Int64.max)
}
func testReadUInt8() {
let data = Data( [25, 8, 1])
let v = FlexBuffer.decode(data: data)?.asUInt
XCTAssertEqual(v, 25)
}
func testReadUInt16() {
let data = Data( [1, 4, 9, 2])
let v = FlexBuffer.decode(data: data)?.asUInt
XCTAssertEqual(v, 1025)
}
func testReadUInt32() {
let data = Data( [233, 1, 1, 0, 10, 4])
let v = FlexBuffer.decode(data: data)?.asUInt
XCTAssertEqual(v, 66025)
}
func testReadUInt64() {
let data = Data( [255, 255, 255, 255, 255, 255, 255, 255, 11, 8])
let v = FlexBuffer.decode(data: data)?.asUInt
XCTAssertEqual(v, UInt(UInt64.max))
}
func testReadUInt64_WithRightAccessor() {
let data = Data( [255, 255, 255, 255, 255, 255, 255, 255, 11, 8])
let v = FlexBuffer.decode(data: data)?.asUInt64
XCTAssertEqual(v, UInt64.max)
}
func testReadFloat() {
let data = Data( [0, 0, 144, 64, 14, 4])
let v = FlexBuffer.decode(data: data)?.asFloat
XCTAssertEqual(v, 4.5)
}
func testReadFloat_fromDouble() {
let data = Data( [0, 0, 0, 0, 0, 0, 18, 64, 15, 8])
let v = FlexBuffer.decode(data: data)?.asFloat
XCTAssertEqual(v, 4.5)
}
func testReadDouble_fromFloat() {
let data = Data( [0, 0, 144, 64, 14, 4])
let v = FlexBuffer.decode(data: data)?.asDouble
XCTAssertEqual(v, 4.5)
}
func testReadDouble() {
let data = Data( [0, 0, 0, 0, 0, 0, 18, 64, 15, 8])
let v = FlexBuffer.decode(data: data)?.asFloat
XCTAssertEqual(v, 4.5)
}
func testReadTrue() {
let data = Data( [1, 4, 1])
let v = FlexBuffer.decode(data: data)?.asBool
XCTAssertEqual(v, true)
}
func testReadFalse() {
let data = Data( [0, 4, 1])
let v = FlexBuffer.decode(data: data)?.asBool
XCTAssertEqual(v, false)
}
func testReadBadBool() {
let data = Data( [2, 4, 1])
let v = FlexBuffer.decode(data: data)?.asBool
XCTAssertEqual(v, nil)
}
func testReadString() {
let data = Data( [5, 77, 97, 120, 105, 109, 0, 6, 20, 1])
let v = FlexBuffer.decode(data: data)?.asString
XCTAssertEqual(v, "Maxim")
}
func testReadVectorOfStrings() {
let data = Data( [3, 102, 111, 111, 0, 3, 98, 97, 114, 0, 3, 98, 97, 122, 0, 3, 15, 11, 7, 20, 20, 20, 6, 40, 1])
let v = FlexBuffer.decode(data: data)?.asVector
XCTAssertEqual(v?.count, 3)
XCTAssertEqual(v?[0]?.asString, "foo")
XCTAssertEqual(v?[1]?.asString, "bar")
XCTAssertEqual(v?[2]?.asString, "baz")
}
func testReadTypedVectorOfStrings() {
let data = Data( [3, 102, 111, 111, 0, 3, 98, 97, 114, 0, 3, 98, 97, 122, 0, 3, 15, 11, 7, 3, 60, 1])
let v = FlexBuffer.decode(data: data)?.asVector
XCTAssertEqual(v?.count, 3)
XCTAssertEqual(v?[0]?.asString, "foo")
XCTAssertEqual(v?[1]?.asString, "bar")
XCTAssertEqual(v?[2]?.asString, "baz")
}
func testReadMixedVector() {
let data = Data( [1, 61, 4, 2, 3, 64, 40, 4, 4, 40, 1])
let v = FlexBuffer.decode(data: data)?.asVector
XCTAssertEqual(v?.count, 2)
XCTAssertEqual(v?[0]?.asVector?[0]?.asInt, 61)
XCTAssertEqual(v?[1]?.asInt, 64)
}
func testReadTypedVector() {
let data = Data( [3, 1, 2, 3, 3, 44, 1])
let v = FlexBuffer.decode(data: data)?.asVector
XCTAssertEqual(v?.count, 3)
XCTAssertEqual(v?[0]?.asInt, 1)
XCTAssertEqual(v?[1]?.asInt, 2)
XCTAssertEqual(v?[2]?.asInt, 3)
}
func testIterateOverTypedVector() {
let data = Data( [3, 1, 2, 3, 3, 44, 1])
let v = FlexBuffer.decode(data: data)?.asVector
var i = 1
for r in v! {
XCTAssertEqual(r.asInt, i)
i += 1
}
XCTAssertEqual(i, 4)
let ints = v!.map({$0.asInt})
XCTAssertEqual(ints.count, 3)
XCTAssertEqual(ints[0], 1)
XCTAssertEqual(ints[1], 2)
XCTAssertEqual(ints[2], 3)
}
func testIterateOverMap() {
let data = Data( [97, 0, 1, 3, 1, 1, 1, 12, 4, 2, 36, 1])
let v = FlexBuffer.decode(data: data)?.asMap
let pairs = v!.map({$0})
XCTAssertEqual(pairs.count, 1)
XCTAssertEqual(pairs[0].key, "a")
XCTAssertEqual(pairs[0].value.asInt, 12)
// 99, 0, 45, 97, 0, 236, 98, 0, 0, 0, 240, 64, 100, 0, 0, 0, 57, 180, 200, 118, 190, 15, 76, 64, 4, 22, 20, 27, 16, 4, 1, 4, 27, 25, 32, 19, 24, 34, 28, 35, 8, 36, 1
}
func testAccessMap() {
// [a:-20, b:7.5, c:45, d:56.123]
let data = Data( [99, 0, 45, 97, 0, 236, 98, 0, 0, 0, 240, 64, 100, 0, 0, 0, 57, 180, 200, 118, 190, 15, 76, 64, 4, 22, 20, 27, 16, 4, 1, 4, 27, 25, 32, 19, 24, 34, 28, 35, 8, 36, 1])
let v = FlexBuffer.decode(data: data)?.asMap
XCTAssertEqual(v?.count, 4)
XCTAssertEqual(v?["a"]?.asInt, -20)
XCTAssertEqual(v?["b"]?.asFloat, 7.5)
XCTAssertEqual(v?["c"]?.asUInt64, 45)
XCTAssertEqual(v?["d"]?.asDouble, 56.123)
XCTAssertEqual(v?["e"]?.asInt, nil)
XCTAssertEqual(v?[""]?.asInt, nil)
XCTAssertEqual(v?["aa"]?.asInt, nil)
}
func testComplexMap() {
// { vec: [ -100, "Fred", 4.0 ], bar: [ 1, 2, 3 ], bar3: [ 1, 2, 3 ] foo: 100, mymap { foo: "Fred" } }
let data = Data( [118, 101, 99, 0, 4, 70, 114, 101, 100, 0, 0, 0, 0, 0, 128, 64, 3, 156, 13, 7, 4, 20, 34, 98, 97, 114, 0, 3, 1, 2, 3, 98, 97, 114, 51, 0, 1, 2, 3, 102, 111, 111, 0, 109, 121, 109, 97, 112, 0, 1, 11, 1, 1, 1, 49, 20, 5, 34, 27, 20, 17, 61, 5, 1, 5, 37, 30, 100, 14, 52, 44, 72, 4, 36, 40, 10, 36, 1])
let v = FlexBuffer.decode(data: data)!.asMap!
print(v.map({$0}))
XCTAssertEqual(v.count, 5)
XCTAssertEqual(v["vec"]?.asVector?[0]?.asInt, -100)
XCTAssertEqual(v["vec"]?.asVector?[1]?.asString, "Fred")
XCTAssertEqual(v["vec"]?.asVector?[2]?.asDouble, 4)
XCTAssertEqual(v["bar"]?.asVector?[0]?.asInt, 1)
XCTAssertEqual(v["bar"]?.asVector?[1]?.asInt, 2)
XCTAssertEqual(v["bar"]?.asVector?[2]?.asInt, 3)
// XCTAssertEqual(v["bar3"]?.asVector?[0]?.asInt, 1)
// XCTAssertEqual(v["bar3"]?.asVector?[1]?.asInt, 2)
// XCTAssertEqual(v["bar3"]?.asVector?[2]?.asInt, 3)
XCTAssertEqual(v["mymap"]?.asMap?.count, 1)
XCTAssertEqual(v["mymap"]?.asMap?["foo"]?.asString, "Fred")
XCTAssertEqual(v["foo"]?.asInt, 100)
}
}
| mit |
Ruenzuo/Traveler | TravelerExample/TravelerExample/Source/AppDelegate.swift | 1 | 472 | //
// AppDelegate.swift
// TravelerExample
//
// Created by Renzo Crisostomo on 26/09/15.
// Copyright © 2015 Ruenzuo.io. All rights reserved.
//
import UIKit
import Traveler
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Traveler.APIKey = ""
return true
}
}
| mit |
wireapp/wire-ios | Wire-iOS Tests/SearchGroup/SearchGroupSelectorSnapshotTests.swift | 1 | 1807 | //
// Wire
// Copyright (C) 2021 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import SnapshotTesting
import XCTest
@testable import Wire
final class SearchGroupSelectorSnapshotTests: XCTestCase {
var sut: SearchGroupSelector!
override func setUp() {
super.setUp()
}
override func tearDown() {
sut = nil
super.tearDown()
}
private func createSut() {
sut = SearchGroupSelector(style: .light)
sut.frame = CGRect(origin: .zero, size: CGSize(width: 320, height: 320))
}
func testForInitState_WhenSelfUserCanNotCreateService() {
// GIVEN
let mockSelfUser = MockUserType.createSelfUser(name: "selfUser")
SelfUser.provider = SelfProvider(selfUser: mockSelfUser)
createSut()
// WHEN & THEN
verify(matching: sut)
}
func testThatServiceTabExists_WhenSelfUserCanCreateService() {
// GIVEN
let mockSelfUser = MockUserType.createSelfUser(name: "selfUser")
mockSelfUser.canCreateService = true
SelfUser.provider = SelfProvider(selfUser: mockSelfUser)
createSut()
// WHEN & THEN
verify(matching: sut)
}
}
| gpl-3.0 |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/BlacklistReason+BlockerViewControllerContext.swift | 1 | 1051 | //
// Wire
// Copyright (C) 2022 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireSyncEngine
extension BlacklistReason {
var blockerViewControllerContext: BlockerViewControllerContext {
switch self {
case .appVersionBlacklisted, .clientAPIVersionObsolete:
return .blacklist
case .backendAPIVersionObsolete:
return .backendNotSupported
}
}
}
| gpl-3.0 |
benlangmuir/swift | validation-test/compiler_crashers_fixed/25913-swift-valuedecl-settype.swift | 65 | 432 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func b{enum b{protocol c case c(c
| apache-2.0 |
benlangmuir/swift | test/SILGen/stored_property_init_reabstraction.swift | 9 | 2471 | // RUN: %target-swift-emit-silgen %s | %FileCheck %s
// rdar://problem/67419937
class Class<T> {
var fn: ((T) -> ())? = nil
init(_: T) where T == Int {}
}
// CHECK-LABEL: sil hidden [ossa] @$s34stored_property_init_reabstraction5ClassCyACySiGSicSiRszlufc : $@convention(method) (Int, @owned Class<Int>) -> @owned Class<Int> {
// CHECK: [[SELF:%.*]] = mark_uninitialized [rootself] %1 : $Class<Int>
// CHECK: [[BORROW:%.*]] = begin_borrow [[SELF]] : $Class<Int>
// CHECK: [[ADDR:%.*]] = ref_element_addr [[BORROW]] : $Class<Int>, #Class.fn
// CHECK: [[INIT:%.*]] = function_ref @$s34stored_property_init_reabstraction5ClassC2fnyxcSgvpfi : $@convention(thin) <τ_0_0> () -> @owned Optional<@callee_guaranteed @substituted <τ_0_0> (@in_guaranteed τ_0_0) -> () for <τ_0_0>>
// CHECK: [[VALUE:%.*]] = apply [[INIT]]<Int>() : $@convention(thin) <τ_0_0> () -> @owned Optional<@callee_guaranteed @substituted <τ_0_0> (@in_guaranteed τ_0_0) -> () for <τ_0_0>>
// CHECK: store [[VALUE]] to [init] [[ADDR]] : $*Optional<@callee_guaranteed @substituted <τ_0_0> (@in_guaranteed τ_0_0) -> () for <Int>>
// CHECK: end_borrow [[BORROW]] : $Class<Int>
struct Struct<T> {
var fn: ((T) -> ())? = nil
init(_: T) where T == Int {}
}
// CHECK-LABEL: sil hidden [ossa] @$s34stored_property_init_reabstraction6StructVyACySiGSicSiRszlufC : $@convention(method) (Int, @thin Struct<Int>.Type) -> @owned Struct<Int> {
// CHECK: [[SELF_BOX:%.*]] = mark_uninitialized [rootself] {{%.*}} : ${ var Struct<Int> }
// CHECK: [[SELF_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[SELF_BOX]]
// CHECK: [[SELF:%.*]] = project_box [[SELF_LIFETIME]] : ${ var Struct<Int> }, 0
// CHECK: [[ADDR:%.*]] = struct_element_addr [[SELF]] : $*Struct<Int>, #Struct.fn
// CHECK: [[INIT:%.*]] = function_ref @$s34stored_property_init_reabstraction6StructV2fnyxcSgvpfi : $@convention(thin) <τ_0_0> () -> @owned Optional<@callee_guaranteed @substituted <τ_0_0> (@in_guaranteed τ_0_0) -> () for <τ_0_0>>
// CHECK: [[VALUE:%.*]] = apply [[INIT]]<Int>() : $@convention(thin) <τ_0_0> () -> @owned Optional<@callee_guaranteed @substituted <τ_0_0> (@in_guaranteed τ_0_0) -> () for <τ_0_0>>
// CHECK: store [[VALUE]] to [init] [[ADDR]] : $*Optional<@callee_guaranteed @substituted <τ_0_0> (@in_guaranteed τ_0_0) -> () for <Int>>
struct ComplexExample<T, U> {
var (fn, value): (((T) -> ())?, U?) = (nil, nil)
var anotherValue: (((T) -> ())?, U?) = (nil, nil)
init(_: T) where T == String {}
}
| apache-2.0 |
seandavidmcgee/HumanKontactBeta | src/keyboardTest/SyncAddressBookOperation.swift | 1 | 6706 | //
// SyncAddressBookOperation.swift
// keyboardTest
//
// Created by Sean McGee on 10/20/15.
// Copyright © 2015 Kannuu. All rights reserved.
//
import UIKit
import AddressBook
import AddressBookUI
import RealmSwift
class SyncAddressBookContactsOperation: NSOperation {
var adbk: ABAddressBook!
override func main() {
if self.cancelled {
return
}
if !self.determineStatus() {
print("not authorized")
return
}
importContacts()
if self.cancelled {
return
}
}
var lastSyncDate:NSDate?{
get{
return NSUserDefaults.standardUserDefaults().objectForKey("modifiedDate") as? NSDate
}
set{
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey:"modifiedDate")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
func importContacts(){
do {
let realm = try Realm()
realm.beginWrite()
let allPeople = ABAddressBookCopyArrayOfAllPeople(
adbk).takeRetainedValue() as NSArray
if let _ = lastSyncDate {
//Not first sync
let deleted = findDeletedPersons(inRealm: realm)
print("Deleted: \(deleted.count)")
for person in deleted{
person.deleteWithChildren(inRealm: realm)
}
for personRec: ABRecordRef in allPeople{
let recordId = ABRecordGetRecordID(personRec)
let queryRecordID = realm.objects(HKPerson).filter("record == \(recordId)")
let foundRecID = queryRecordID.first
if let foundRecID = foundRecID{
if Int(recordId) == foundRecID.record{
print("Existing person in AB.")
foundRecID.updateIfNeeded(fromRecord: personRec, inRealm: realm)
}
}else{
print("New person was created in AB, let's add it too.")
let newPerson = HKPerson()
newPerson.update(fromRecord: personRec, inRealm: realm)
realm.add(newPerson)
}
}
}else{
print("First sync with AB. Add all contacts.")
for personRec: ABRecordRef in allPeople{
//First sync
let newPerson = HKPerson()
newPerson.update(fromRecord: personRec, inRealm: realm)
realm.add(newPerson)
}
}
let index = HKPerson()
index.createIndex(false)
try realm.commitWrite()
lastSyncDate = NSDate()
} catch {
print("Something went wrong!")
}
}
func findDeletedPersons(inRealm realm:Realm) -> [HKPerson]{
let realm = try! Realm()
var allRecordsIds = [Int]()
let allPeople = ABAddressBookCopyArrayOfAllPeople(
adbk).takeRetainedValue() as NSArray
for personRec: ABRecordRef in allPeople{
let recordId = ABRecordGetRecordID(personRec)
allRecordsIds.append(Int(recordId))
}
let allPersons = realm.objects(HKPerson)
var missingPersons = [HKPerson]()
for person in allPersons{
let isPersonFound = allRecordsIds.filter { $0 == person.record }.count > 0
if !isPersonFound{
let foundPerson: ABRecord? = lookup(person: person) as ABRecord?
if foundPerson == nil{
missingPersons.append(person)
}
}
}
print("Missing Persons in AB sync: \(missingPersons)")
return missingPersons
}
func lookup(person person:HKPerson!) -> ABRecord?{
var rec : ABRecord! = nil
let people = ABAddressBookCopyPeopleWithName(self.adbk, person.fullName).takeRetainedValue() as NSArray
for personRec in people {
if let createdDate = ABRecordCopyValue(personRec, kABPersonCreationDateProperty).takeRetainedValue() as? NSDate {
if createdDate == person.createdDate {
let recordId = ABRecordGetRecordID(personRec)
person.record == Int(recordId)
rec = personRec
break
}
}
}
if rec != nil {
print("found person and updated recordID")
}
return rec
}
func createAddressBook() -> Bool {
if self.adbk != nil {
return true
}
var err : Unmanaged<CFError>? = nil
let adbk : ABAddressBook? = ABAddressBookCreateWithOptions(nil, &err).takeRetainedValue()
if adbk == nil {
print(err)
self.adbk = nil
return false
}
self.adbk = adbk
return true
}
func determineStatus() -> Bool {
let status = ABAddressBookGetAuthorizationStatus()
switch status {
case .Authorized:
return self.createAddressBook()
case .NotDetermined:
var ok = false
ABAddressBookRequestAccessWithCompletion(nil) {
(granted:Bool, err:CFError!) in
dispatch_async(dispatch_get_main_queue()) {
if granted {
ok = self.createAddressBook()
}
}
}
if ok == true {
return true
}
adbk = nil
return false
case .Restricted:
adbk = nil
return false
case .Denied:
let alert = UIAlertController(title: "Need Authorization", message: "Wouldn't you like to authorize this app to use your Contacts?", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "No", style: .Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: {
_ in
let url = NSURL(string:UIApplicationOpenSettingsURLString)!
UIApplication.sharedApplication().openURL(url)
}))
UIApplication.sharedApplication().keyWindow?.rootViewController!.presentViewController(alert, animated:true, completion:nil)
adbk = nil
return false
}
}
}
| mit |
onmyway133/Github.swift | Sources/Classes/Git/Tree.swift | 1 | 685 | //
// Tree.swift
// GithubSwift
//
// Created by Khoa Pham on 23/04/16.
// Copyright © 2016 Fantageek. All rights reserved.
//
import Foundation
import Tailor
import Sugar
// A git tree.
public class Tree: Object {
// The SHA of the tree.
public private(set) var SHA: String = ""
// The URL for the tree.
public private(set) var URL: NSURL?
// The `OCTTreeEntry` objects.
public private(set) var entries: [TreeEntry] = []
public required init(_ map: JSONDictionary) {
super.init(map)
self.SHA <- map.property("sha")
self.URL <- map.transform("url", transformer: NSURL.init(string: ))
self.entries <- map.relationsHierarchically("tree")
}
}
| mit |
RLovelett/VHS | VHSTests/Helpers/ExpectResponseFromDelegate.swift | 1 | 1111 | //
// ExpectResponseFromDelegate.swift
// VHS
//
// Created by Ryan Lovelett on 7/19/16.
// Copyright © 2016 Ryan Lovelett. All rights reserved.
//
import Foundation
import XCTest
final class ExpectResponseFromDelegate: NSObject, URLSessionDataDelegate {
enum QueueType {
case `default`, main
}
private let type: QueueType
private let expectation: XCTestExpectation
private let file: StaticString
private let line: UInt
init(on type: QueueType, fulfill: XCTestExpectation, file: StaticString = #file, line: UInt = #line) {
self.type = type
self.expectation = fulfill
self.file = file
self.line = line
super.init()
}
func urlSession(
_ session: URLSession,
task: URLSessionTask,
didCompleteWithError error: Error?
) {
switch self.type {
case .default:
XCTAssertFalse(Thread.isMainThread, file: file, line: line)
case .main:
XCTAssertTrue(Thread.isMainThread, file: file, line: line)
}
self.expectation.fulfill()
}
}
| mit |
qvik/qvik-swift-ios | QvikSwift/StringExtensions.swift | 1 | 5599 | // The MIT License (MIT)
//
// Copyright (c) 2015-2016 Qvik (www.qvik.fi)
//
// 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
/// Extensions to the String class.
public extension String {
/**
Trims all the whitespace-y / newline characters off the begin/end of the string.
- returns: a new string with all the newline/whitespace characters removed from the ends of the original string
*/
func trim() -> String {
return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
/**
Returns an URL encoded string of this string.
- returns: String that is an URL-encoded representation of this string.
*/
var urlEncoded: String? {
return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
}
/**
Convenience method for a more familiar name for string splitting.
- parameter separator: string to split the original string by
- returns: the original string split into parts
*/
func split(_ separator: String) -> [String] {
return components(separatedBy: separator)
}
/**
Checks whether the string contains a given substring.
- parameter s: substring to check for
- returns: true if this string contained the given substring, false otherwise.
*/
func contains(_ s: String) -> Bool {
return (self.range(of: s) != nil)
}
/**
Returns a substring of this string from a given index up the given length.
- parameter startIndex: index of the first character to include in the substring
- parameter length: number of characters to include in the substring
- returns: the substring
*/
func substring(startIndex: Int, length: Int) -> String {
let start = self.index(self.startIndex, offsetBy: startIndex)
let end = self.index(self.startIndex, offsetBy: startIndex + length)
return String(self[start..<end])
}
/**
Returns a substring of this string from a given index to the end of the string.
- parameter startIndex: index of the first character to include in the substring
- returns: the substring from startIndex to the end of this string
*/
func substring(startIndex: Int) -> String {
let start = self.index(self.startIndex, offsetBy: startIndex)
return String(self[start...])
}
/**
Returns the i:th character in the string.
- parameter i: index of the character to return
- returns: i:th character in the string
*/
subscript (i: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: i)]
}
/**
Returns a substring matching the given range.
- parameter r: range for substring to return
- returns: substring matching the range r
*/
subscript (r: Range<Int>) -> String {
let start = index(startIndex, offsetBy: r.lowerBound)
let end = index(start, offsetBy: r.upperBound - r.lowerBound)
return String(self[start..<end])
}
/**
Splits the string into substring of equal 'lengths'; any remainder string
will be shorter than 'length' in case the original string length was not multiple of 'length'.
- parameter length: (max) length of each substring
- returns: the substrings array
*/
func splitEqually(length: Int) -> [String] {
var index = 0
let len = self.count
var strings: [String] = []
while index < len {
let numChars = min(length, (len - index))
strings.append(self.substring(startIndex: index, length: numChars))
index += numChars
}
return strings
}
/**
Returns the bounding rectangle that drawing required for drawing this string using
the given font. By default the string is drawn on a single line, but it can be
constrained to a specific width with the optional parameter constrainedToSize.
- parameter font: font used
- parameter constrainedToSize: the constraints for drawing
- returns: the bounding rectangle required to draw the string
*/
func boundingRect(font: UIFont, constrainedToSize size: CGSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)) -> CGRect {
let attributedString = NSAttributedString(string: self, attributes: [NSAttributedString.Key.font: font])
return attributedString.boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil)
}
}
| mit |
iSame7/ViperCode | ViperCode/Templates/Default/Swift/Code/Protocols/VIPERProtocols.swift | 1 | 1751 | //
// ___FILENAME___.swift
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright © ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//
import Foundation
protocol VIPERViewProtocol: class {
var presenter: VIPERPresenterProtocol? { get set }
/**
* Add here your methods for communication PRESENTER -> VIEW
*/
}
protocol VIPERWireFrameProtocol: class {
static func presentVIPERModule(fromView view: AnyObject)
/**
* Add here your methods for communication PRESENTER -> WIREFRAME
*/
}
protocol VIPERPresenterProtocol: class {
var view: VIPERViewProtocol? { get set }
var interactor: VIPERInteractorInputProtocol? { get set }
var wireFrame: VIPERWireFrameProtocol? { get set }
/**
* Add here your methods for communication VIEW -> PRESENTER
*/
}
protocol VIPERInteractorOutputProtocol: class {
/**
* Add here your methods for communication INTERACTOR -> PRESENTER
*/
}
protocol VIPERInteractorInputProtocol: class
{
var presenter: VIPERInteractorOutputProtocol? { get set }
var APIDataManager: VIPERAPIDataManagerInputProtocol? { get set }
var localDatamanager: VIPERLocalDataManagerInputProtocol? { get set }
/**
* Add here your methods for communication PRESENTER -> INTERACTOR
*/
}
protocol VIPERDataManagerInputProtocol: class
{
/**
* Add here your methods for communication INTERACTOR -> DATAMANAGER
*/
}
protocol VIPERAPIDataManagerInputProtocol: class
{
/**
* Add here your methods for communication INTERACTOR -> APIDATAMANAGER
*/
}
protocol VIPERLocalDataManagerInputProtocol: class
{
/**
* Add here your methods for communication INTERACTOR -> LOCALDATAMANAGER
*/
}
| mit |
StachkaConf/ios-app | StachkaIOS/StachkaIOS/Classes/User Stories/Talks/FiltersMain/ViewModel/FiltersMainViewModelImplementation.swift | 1 | 2363 | //
// FiltersViewModelImplementation.swift
// StachkaIOS
//
// Created by m.rakhmanov on 27.03.17.
// Copyright © 2017 m.rakhmanov. All rights reserved.
//
import RxSwift
import RealmSwift
class FiltersMainViewModelImplementation: FiltersMainViewModel {
var filters: Observable<[FilterCellViewModel]> {
return _filters.asObservable()
}
var _filters: Variable<[FilterCellViewModel]> = Variable([])
var parentFilters: [ParentFilter] = []
var parentFilterPublisher = PublishSubject<ParentFilter>()
let disposeBag = DisposeBag()
fileprivate let filterFactory: FilterFactory
fileprivate let filterCellViewModelFactory: FilterCellViewModelFactory
fileprivate let filterService: FilterService
fileprivate weak var view: FiltersMainView?
init(view: FiltersMainView,
filterService: FilterService,
filterFactory: FilterFactory,
filterCellViewModelFactory: FilterCellViewModelFactory) {
self.view = view
self.filterService = filterService
self.filterFactory = filterFactory
self.filterCellViewModelFactory = filterCellViewModelFactory
filterService
.updateFilters()
.do(onNext: { [weak self] filters in
guard let strongSelf = self else { return }
strongSelf.parentFilters = filters as? [ParentFilter] ?? []
})
.map { [weak self] filters -> [FilterCellViewModel] in
guard let strongSelf = self else { return [] }
return strongSelf.filterCellViewModelFactory.navigationViewModels(from: filters)
}
.subscribe(onNext: { [weak self] filterModels in
guard let strongSelf = self else { return }
strongSelf._filters.value = filterModels
})
.disposed(by: disposeBag)
view.indexSelected
.subscribe(onNext: { [weak self] indexPath in
guard let strongSelf = self else { return }
strongSelf.parentFilterPublisher.onNext(strongSelf.parentFilters[indexPath.row])
})
.disposed(by: disposeBag)
}
}
extension FiltersMainViewModelImplementation: FiltersMainModuleOutput {
var parentFilterSelected: Observable<ParentFilter> {
return parentFilterPublisher.asObservable()
}
}
| mit |
farshadtx/Fleet | FleetTests/CoreExtensions/UIButton+FleetSpec.swift | 1 | 652 | import XCTest
import Fleet
import Nimble
class UIButton_FleetSpec: XCTestCase {
var buttonTapTestViewController: ButtonTapTestViewController?
override func setUp() {
super.setUp()
buttonTapTestViewController = ButtonTapTestViewController(nibName: "ButtonTapTestViewController", bundle: Bundle.currentTestBundle)
let _ = buttonTapTestViewController?.view
}
func testCallingTapOnButton() {
buttonTapTestViewController?.testButton?.tap()
buttonTapTestViewController?.changeLabel()
expect(self.buttonTapTestViewController?.testLabel?.text).toEventually(equal("some test label"))
}
}
| apache-2.0 |
jisudong/study | Study/Study/Study_RxSwift/Disposable.swift | 1 | 181 | //
// Disposable.swift
// Study
//
// Created by syswin on 2017/7/27.
// Copyright © 2017年 syswin. All rights reserved.
//
public protocol Disposable {
func dispose()
}
| mit |
mikekavouras/Glowb-iOS | Glowb/Protocols/Styleable.swift | 1 | 185 | //
// Styleable.swift
// Glowb
//
// Created by Michael Kavouras on 12/4/16.
// Copyright © 2016 Michael Kavouras. All rights reserved.
//
protocol Styleable {
func style()
}
| mit |
googlecodelabs/flutter-github-graphql-client | step-07/macos/Runner/AppDelegate.swift | 5 | 803 | // Copyright 2020 Google LLC
//
// 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 FlutterMacOS
@NSApplicationMain
class AppDelegate: FlutterAppDelegate {
override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
}
| apache-2.0 |
austinzheng/swift-compiler-crashes | crashes-duplicates/16435-no-stacktrace.swift | 11 | 218 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
[ T : {
class A {
let a {
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/27434-swift-parser-diagnose.swift | 4 | 275 | // 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<l where h:A{
class B{
}
struct B<d{
struct c
var d=c
}
}
>(
{
{
struct B{
class A{enum b{let:{c{
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.