repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
austinzheng/swift
|
test/SILOptimizer/devirt_witness_method_empty_conformance.swift
|
31
|
2506
|
// RUN: %target-swift-frontend -O -emit-ir -primary-file %s | %FileCheck %s
public struct PublicStruct {
}
public enum PublicEnum {
}
struct RegStruct {
enum EnumInRegStruct {
case case1
case case2
}
private var optNode: Any?
private var ClassInRegStructs = [ClassInRegStruct]()
var isEmpty: Bool {
return optNode == nil && ClassInRegStructs.isEmpty
}
private func funcInRegStruct() -> RegStruct? {
var funcInRegStruct = RegStruct()
return funcInRegStruct
}
func func2InRegStruct(boolParam: Bool = false,
_ body: (inout Bool) -> Void) {
var finished = false
func2InRegStruct(body, boolParam: boolParam, &finished)
}
private func func2InRegStruct(_ body: (inout Bool) -> Void,
boolParam: Bool = false, _ finished: inout Bool) {
funcInRegStruct()?.func2InRegStruct(body, boolParam: boolParam, &finished)
}
private static func func2InRegStruct(_ ClassInRegStructs: [ClassInRegStruct],
_ body: (inout Bool) -> Void,
boolParam: Bool, _ finished: inout Bool) {
}
func funcInStructAndProtAndExt(_ EnumInRegStruct: EnumInRegStruct, space: PublicEnum,
_ body: () -> Void) {
guard !isEmpty else { return }
func2InRegStruct(boolParam: !EnumInRegStruct.isDownwards) { finished in
}
}
final private class ClassInRegStruct {
}
}
extension RegStruct.EnumInRegStruct {
fileprivate var isDownwards: Bool {
switch self {
case .case1:
return true
case .case2:
return false
}
}
}
private protocol ApplyRegStruct {
mutating func applyTransform()
}
protocol RegStructable {
mutating func funcInStructAndProtAndExt(from space: PublicEnum, transform: RegStruct)
}
extension ApplyRegStruct {
mutating func funcInStructAndProtAndExt(
from space: PublicEnum, transform: RegStruct
) {
transform.funcInStructAndProtAndExt(.case2, space: space) {
// CHECK-LABEL: define hidden swiftcc void @"$sSa39devirt_witness_method_empty_conformanceAA12PublicStructVRszlE14applyTransformyyF"(%TSa* nocapture swiftself dereferenceable
// CHECK-NEXT: entry
// CHECK-NEXT: ret void
applyTransform()
}
}
}
extension Array : ApplyRegStruct, RegStructable where Element == PublicStruct {
mutating func applyTransform() {
}
}
|
apache-2.0
|
9e924f1b7a6055128cb84184ccd666aa
| 26.844444 | 174 | 0.641261 | 4.135314 | false | false | false | false |
zhou9734/Warm
|
Warm/Classes/Experience/View/ETableViewTagCell.swift
|
1
|
1480
|
//
// ETableViewTagCell.swift
// Warm
//
// Created by zhoucj on 16/9/17.
// Copyright © 2016年 zhoucj. All rights reserved.
//
import UIKit
class ETableViewTagCell: ETableViewBaseCell {
override var classes: WClass?{
didSet{
if let tags_bds = classes!.tags_bd{
var tags_bdsStr = ""
for t in tags_bds{
tags_bdsStr = tags_bdsStr + t.name!
}
if tags_bdsStr != ""{
imgTag.hidden = false
imgTag.setTitle(tags_bdsStr, forState: .Normal)
}
}
}
}
override func addImgTag() {
contentView.addSubview(imgTag)
imgTag.snp_makeConstraints { (make) -> Void in
make.top.equalTo(contentView.snp_top).offset(-3)
make.left.equalTo(contentView.snp_left).offset(15)
make.width.equalTo(60)
make.height.equalTo(30)
}
}
let titleColor = UIColor.whiteColor()
let imgTagBgImager = UIImage.imageWithColor(UIColor.orangeColor())
private lazy var imgTag: UIButton = {
let btn = UIButton()
btn.setTitleColor(self.titleColor, forState: .Normal)
btn.titleLabel?.font = UIFont.systemFontOfSize(15)
btn.layer.cornerRadius = 6
btn.layer.masksToBounds = true
btn.setBackgroundImage(self.imgTagBgImager, forState: .Normal)
btn.hidden = true
return btn
}()
}
|
mit
|
1ea24b52257cf5c53b565fce182e965e
| 29.142857 | 70 | 0.569397 | 4.068871 | false | false | false | false |
KarlWarfel/nutshell-ios
|
Nutshell/ViewControllers/LoginViewController.swift
|
1
|
21329
|
/*
* Copyright (c) 2015, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* 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 License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import UIKit
import Alamofire
import SwiftyJSON
import CocoaLumberjack
import MessageUI
import HealthKit
/// Presents the UI to capture email and password for login and calls APIConnector to login. Show errors to the user. Backdoor UI for development setting of the service.
class LoginViewController: BaseUIViewController, MFMailComposeViewControllerDelegate {
@IBOutlet weak var logInScene: UIView!
@IBOutlet weak var logInEntryContainer: UIView!
@IBOutlet weak var inputContainerView: UIView!
@IBOutlet weak var offlineMessageContainerView: UIView!
@IBOutlet weak var emailTextField: NutshellUITextField!
@IBOutlet weak var passwordTextField: NutshellUITextField!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var loginIndicator: UIActivityIndicatorView!
@IBOutlet weak var errorFeedbackLabel: NutshellUILabel!
@IBOutlet weak var forgotPasswordLabel: NutshellUILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
let nc = NSNotificationCenter.defaultCenter()
nc.removeObserver(self, name: nil, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: #selector(LoginViewController.textFieldDidChange), name: UITextFieldTextDidChangeNotification, object: nil)
updateButtonStates()
// forgot password text needs an underline...
if let forgotText = forgotPasswordLabel.text {
let forgotStr = NSAttributedString(string: forgotText, attributes:[NSFontAttributeName: forgotPasswordLabel.font, NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue])
forgotPasswordLabel.attributedText = forgotStr
}
// TODO: hide for now until implemented!
forgotPasswordLabel.hidden = true
notificationCenter.addObserver(self, selector: #selector(LoginViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(LoginViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.reachabilityChanged(_:)), name: ReachabilityChangedNotification, object: nil)
configureForReachability()
// Tap all four corners to bring up server selection action sheet
let width: CGFloat = 100
let height: CGFloat = width
corners.append(CGRect(x: 0, y: 0, width: width, height: height))
corners.append(CGRect(x: self.view.frame.width - width, y: 0, width: width, height: height))
corners.append(CGRect(x: 0, y: self.view.frame.height - height, width: width, height: height))
corners.append(CGRect(x: self.view.frame.width - width, y: self.view.frame.height - height, width: width, height: height))
for _ in 0 ..< corners.count {
cornersBool.append(false)
}
}
func reachabilityChanged(note: NSNotification) {
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
// try token refresh if we are now connected...
// TODO: change message to "attempting token refresh"?
let api = APIConnector.connector()
if api.isConnectedToNetwork() && api.sessionToken != nil {
NSLog("Login: attempting to refresh token...")
api.refreshToken() { succeeded -> (Void) in
if succeeded {
appDelegate.setupUIForLoginSuccess()
} else {
NSLog("Refresh token failed, need to log in normally")
api.logout() {
self.configureForReachability()
}
}
}
return
}
}
configureForReachability()
}
private func configureForReachability() {
let connected = APIConnector.connector().isConnectedToNetwork()
inputContainerView.hidden = !connected
offlineMessageContainerView.hidden = connected
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//
// MARK: - Button and text field handlers
//
@IBAction func tapOutsideFieldHandler(sender: AnyObject) {
passwordTextField.resignFirstResponder()
emailTextField.resignFirstResponder()
}
@IBAction func passwordEnterHandler(sender: AnyObject) {
passwordTextField.resignFirstResponder()
if (loginButton.enabled) {
login_button_tapped(self)
}
}
@IBAction func emailEnterHandler(sender: AnyObject) {
passwordTextField.becomeFirstResponder()
}
@IBAction func login_button_tapped(sender: AnyObject) {
updateButtonStates()
loginIndicator.startAnimating()
APIConnector.connector().login(emailTextField.text!,
password: passwordTextField.text!) { (result:Alamofire.Result<User, NSError>) -> (Void) in
//NSLog("Login result: \(result)")
self.processLoginResult(result)
}
}
private func processLoginResult(result: Alamofire.Result<User, NSError>) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
self.loginIndicator.stopAnimating()
if (result.isSuccess) {
if let user=result.value {
NSLog("Login success: \(user)")
APIConnector.connector().fetchProfile() { (result:Alamofire.Result<JSON, NSError>) -> (Void) in
NSLog("Profile fetch result: \(result)")
if (result.isSuccess) {
if let json = result.value {
NutDataController.controller().processProfileFetch(json)
}
}
}
appDelegate.setupUIForLoginSuccess()
} else {
// This should not happen- we should not succeed without a user!
NSLog("Fatal error: No user returned!")
}
} else {
NSLog("login failed! Error: " + result.error.debugDescription)
var errorText = NSLocalizedString("loginErrUserOrPassword", comment: "Wrong email or password!")
if let error = result.error {
NSLog("NSError: \(error)")
if error.code == -1009 {
errorText = NSLocalizedString("loginErrOffline", comment: "The Internet connection appears to be offline!")
}
// TODO: handle network offline!
}
self.errorFeedbackLabel.text = errorText
self.errorFeedbackLabel.hidden = false
self.passwordTextField.text = ""
}
}
func textFieldDidChange() {
updateButtonStates()
}
private func updateButtonStates() {
errorFeedbackLabel.hidden = true
// login button
if (emailTextField.text != "" && passwordTextField.text != "") {
loginButton.enabled = true
loginButton.setTitleColor(UIColor.whiteColor(), forState:UIControlState.Normal)
} else {
loginButton.enabled = false
loginButton.setTitleColor(UIColor.lightGrayColor(), forState:UIControlState.Normal)
}
}
//
// MARK: - View handling for keyboard
//
private var viewAdjustAnimationTime: Float = 0.25
private func adjustLogInView(centerOffset: CGFloat) {
for c in logInScene.constraints {
if c.firstAttribute == NSLayoutAttribute.CenterY {
c.constant = -centerOffset
break
}
}
UIView.animateWithDuration(NSTimeInterval(viewAdjustAnimationTime)) {
self.logInScene.layoutIfNeeded()
}
}
// UIKeyboardWillShowNotification
func keyboardWillShow(notification: NSNotification) {
// make space for the keyboard if needed
let keyboardFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
viewAdjustAnimationTime = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Float
let loginViewDistanceToBottom = logInScene.frame.height - logInEntryContainer.frame.origin.y - logInEntryContainer.frame.size.height
let additionalKeyboardRoom = keyboardFrame.height - loginViewDistanceToBottom
if (additionalKeyboardRoom > 0) {
self.adjustLogInView(additionalKeyboardRoom)
}
}
// UIKeyboardWillHideNotification
func keyboardWillHide(notification: NSNotification) {
// reposition login view if needed
self.adjustLogInView(0.0)
}
// MARK: - Debug Config
private var corners: [CGRect] = []
private var cornersBool: [Bool] = []
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let touchLocation = touch.locationInView(self.view)
var i = 0
for corner in corners {
let viewFrame = self.view.convertRect(corner, fromView: self.view)
if CGRectContainsPoint(viewFrame, touchLocation) {
cornersBool[i] = true
self.checkCorners()
return
}
i += 1
}
}
}
func checkCorners() {
for cornerBool in cornersBool {
if (!cornerBool) {
return
}
}
showServerActionSheet()
}
func showServerActionSheet() {
for i in 0 ..< corners.count {
cornersBool[i] = false
}
let api = APIConnector.connector()
let actionSheet = UIAlertController(title: "Settings" + " (" + api.currentService! + ")", message: "", preferredStyle: .ActionSheet)
for server in api.kServers {
actionSheet.addAction(UIAlertAction(title: server.0, style: .Default, handler: { Void in
let serverName = server.0
api.switchToServer(serverName)
}))
}
actionSheet.addAction(UIAlertAction(title: "Count HealthKit Blood Glucose Samples", style: .Default, handler: {
Void in
self.handleCountBloodGlucoseSamples()
}))
actionSheet.addAction(UIAlertAction(title: "Find date range for blood glucose samples", style: .Default, handler: {
Void in
self.handleFindDateRangeBloodGlucoseSamples()
}))
actionSheet.addAction(UIAlertAction(title: "Email export of HealthKit blood glucose data", style: .Default, handler: {
Void in
self.handleEmailExportOfBloodGlucoseData()
}))
if defaultDebugLevel == DDLogLevel.Off {
actionSheet.addAction(UIAlertAction(title: "Enable logging", style: .Default, handler: { Void in
defaultDebugLevel = DDLogLevel.Verbose
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "LoggingEnabled");
NSUserDefaults.standardUserDefaults().synchronize()
}))
} else {
actionSheet.addAction(UIAlertAction(title: "Disable logging", style: .Default, handler: { Void in
defaultDebugLevel = DDLogLevel.Off
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "LoggingEnabled");
NSUserDefaults.standardUserDefaults().synchronize()
self.clearLogFiles()
}))
}
actionSheet.addAction(UIAlertAction(title: "Email logs", style: .Default, handler: { Void in
self.handleEmailLogs()
}))
if let popoverController = actionSheet.popoverPresentationController {
popoverController.sourceView = self.view
popoverController.sourceRect = logInEntryContainer.bounds
}
self.presentViewController(actionSheet, animated: true, completion: nil)
}
func clearLogFiles() {
// Clear log files
let logFileInfos = fileLogger.logFileManager.unsortedLogFileInfos()
for logFileInfo in logFileInfos {
if let logFilePath = logFileInfo.filePath {
do {
try NSFileManager.defaultManager().removeItemAtPath(logFilePath)
logFileInfo.reset()
DDLogInfo("Removed log file: \(logFilePath)")
} catch let error as NSError {
DDLogError("Failed to remove log file at path: \(logFilePath) error: \(error), \(error.userInfo)")
}
}
}
}
//
// MARK: - Debug action handlers - HealthKit Debug UI
//
func handleCountBloodGlucoseSamples() {
HealthKitManager.sharedInstance.countBloodGlucoseSamples {
(error: NSError?, totalSamplesCount: Int, totalDexcomSamplesCount: Int) in
var alert: UIAlertController?
let title = "HealthKit Blood Glucose Sample Count"
var message = ""
if error == nil {
message = "There are \(totalSamplesCount) blood glucose samples and \(totalDexcomSamplesCount) Dexcom samples in HealthKit"
} else if HealthKitManager.sharedInstance.authorizationRequestedForBloodGlucoseSamples() {
message = "Error counting samples: \(error)"
} else {
message = "Unable to count sample. Maybe you haven't connected to Health yet. Please login and connect to Health and try again."
}
DDLogInfo(message)
alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alert!.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
dispatch_async(dispatch_get_main_queue(), {
self.presentViewController(alert!, animated: true, completion: nil)
})
}
}
func handleFindDateRangeBloodGlucoseSamples() {
let sampleType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodGlucose)!
HealthKitManager.sharedInstance.findSampleDateRange(sampleType: sampleType) {
(error: NSError?, startDate: NSDate?, endDate: NSDate?) in
var alert: UIAlertController?
let title = "Date range for blood glucose samples"
var message = ""
if error == nil && startDate != nil && endDate != nil {
let days = startDate!.differenceInDays(endDate!) + 1
message = "Start date: \(startDate), end date: \(endDate). Total days: \(days)"
} else {
message = "Unable to find date range for blood glucose samples, maybe you haven't connected to Health yet, please login and connect to Health and try again. Or maybe there are no samples in HealthKit."
}
DDLogInfo(message)
alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alert!.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
dispatch_async(dispatch_get_main_queue(), {
self.presentViewController(alert!, animated: true, completion: nil)
})
}
}
func handleEmailLogs() {
DDLog.flushLog()
let logFilePaths = fileLogger.logFileManager.sortedLogFilePaths() as! [String]
var logFileDataArray = [NSData]()
for logFilePath in logFilePaths {
let fileURL = NSURL(fileURLWithPath: logFilePath)
if let logFileData = try? NSData(contentsOfURL: fileURL, options: NSDataReadingOptions.DataReadingMappedIfSafe) {
// Insert at front to reverse the order, so that oldest logs appear first.
logFileDataArray.insert(logFileData, atIndex: 0)
}
}
if MFMailComposeViewController.canSendMail() {
let appName = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as! String
let composeVC = MFMailComposeViewController()
composeVC.mailComposeDelegate = self
composeVC.setSubject("Logs for \(appName)")
composeVC.setMessageBody("", isHTML: false)
let attachmentData = NSMutableData()
for logFileData in logFileDataArray {
attachmentData.appendData(logFileData)
}
composeVC.addAttachmentData(attachmentData, mimeType: "text/plain", fileName: "\(appName).txt")
self.presentViewController(composeVC, animated: true, completion: nil)
}
}
func handleEmailExportOfBloodGlucoseData() {
let sampleType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodGlucose)!
let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: nil, limit: HKObjectQueryNoLimit, sortDescriptors: nil) {
(query, samples, error) -> Void in
if error == nil && samples?.count > 0 {
// Write header row
let rows = NSMutableString()
rows.appendString("sequence,sourceBundleId,UUID,date,value,units\n")
// Write rows
let dateFormatter = NSDateFormatter()
var sequence = 0
for sample in samples! {
sequence += 1
let sourceBundleId = sample.sourceRevision.source.bundleIdentifier
let UUIDString = sample.UUID.UUIDString
let date = dateFormatter.isoStringFromDate(sample.startDate, zone: NSTimeZone(forSecondsFromGMT: 0), dateFormat: iso8601dateZuluTime)
if let quantitySample = sample as? HKQuantitySample {
let units = "mg/dL"
let unit = HKUnit(fromString: units)
let value = quantitySample.quantity.doubleValueForUnit(unit)
rows.appendString("\(sequence),\(sourceBundleId),\(UUIDString),\(date),\(value),\(units)\n")
} else {
rows.appendString("\(sequence),\(sourceBundleId),\(UUIDString)\n")
}
}
// Send mail
if MFMailComposeViewController.canSendMail() {
let composeVC = MFMailComposeViewController()
composeVC.mailComposeDelegate = self
composeVC.setSubject("HealthKit blood glucose samples")
composeVC.setMessageBody("", isHTML: false)
if let attachmentData = rows.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
composeVC.addAttachmentData(attachmentData, mimeType: "text/csv", fileName: "HealthKit Samples.csv")
}
self.presentViewController(composeVC, animated: true, completion: nil)
}
} else {
var alert: UIAlertController?
let title = "Error"
let message = "Unable to export HealthKit blood glucose data. Maybe you haven't connected to Health yet. Please login and connect to Health and try again. Or maybe there is no blood glucose data in Health."
DDLogInfo(message)
alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alert!.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
dispatch_async(dispatch_get_main_queue(), {
self.presentViewController(alert!, animated: true, completion: nil)
})
}
}
HKHealthStore().executeQuery(sampleQuery)
}
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
}
|
bsd-2-clause
|
5a8ea8bbb1a2d9412552e3a06a901ee1
| 43.621339 | 222 | 0.614375 | 5.639609 | false | false | false | false |
domenicosolazzo/practice-swift
|
Views/WebViews/WebView Example/WebView Example/ViewController.swift
|
1
|
2528
|
//
// ViewController.swift
// WebView Example
//
// Created by Domenico Solazzo on 06/05/15.
// License MIT
//
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView?
override func viewDidLoad() {
super.viewDidLoad()
// Adding preferences
let preferences = WKPreferences()
preferences.javaScriptEnabled = true
// Adding configuration
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
webView = WKWebView(frame: view.bounds, configuration: configuration)
if let theWebView = webView{
let url = URL(string: "http://www.domenicosolazzo.com")
let request = URLRequest(url: url!)
// Load the request
theWebView.load(request)
// Adding the delegate
theWebView.navigationDelegate = self
// Adding the web view to the main view
view.addSubview(theWebView)
}
}
//- MARK: WKNavigationDelegate
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
/* Start the network activity indicator when the web view is loading */
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
/* Stop the network activity indicator when the loading finishes */
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
// We do not allow clicking on a link
if navigationAction.navigationType == WKNavigationType.linkActivated{
let alertController = UIAlertController(title: nil, message: "Sorry, you can click any link.", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
// Present the alert
self.present(alertController, animated: true, completion:nil)
decisionHandler(WKNavigationActionPolicy.cancel)
return
}
// Allow all the other actions
decisionHandler(WKNavigationActionPolicy.allow)
}
}
|
mit
|
83d8045390c0244195fecee7126800a5
| 34.605634 | 157 | 0.648339 | 5.948235 | false | true | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/FeatureOpenBanking/Sources/FeatureOpenBankingData/Network.swift
|
1
|
7572
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Blockchain
import DIKit
import Foundation
#if canImport(WalletNetworkKit)
import WalletNetworkKit
typealias RequestBuilderToUse = WalletNetworkKit.RequestBuilder
typealias NetworkRequestToUse = WalletNetworkKit.NetworkRequest
#else
import NetworkKit
typealias RequestBuilderToUse = NetworkKit.RequestBuilder
typealias NetworkRequestToUse = NetworkKit.NetworkRequest
#endif
public protocol Network {
func perform<ResponseType>(
request: Request,
responseType: ResponseType.Type
) -> AnyPublisher<ResponseType, NetworkError> where ResponseType: Decodable
func perform(
request: Request
) -> AnyPublisher<Void, NetworkError>
}
extension Network {
public func perform(request: Request) -> AnyPublisher<Void, NetworkError> {
perform(request: request, responseType: EmptyNetworkResponse.self).mapToVoid()
}
}
public protocol Request {
var urlRequest: URLRequest { get }
}
public protocol RequestBuilder {
func get(
path: [String],
authenticated: Bool
) -> Request
func post(
path: [String],
body: Data?,
authenticated: Bool
) -> Request
func delete(
path: [String],
authenticated: Bool
) -> Request
}
extension RequestBuilder {
public func get(path: String..., authenticated: Bool = true) -> Request {
get(path: path, authenticated: authenticated)
}
public func post(path: String..., body: Data? = nil, authenticated: Bool = true) -> Request {
post(path: path, body: body, authenticated: authenticated)
}
public func delete(path: [String], authenticated: Bool = true) -> Request {
delete(path: path, authenticated: authenticated)
}
}
extension RequestBuilderToUse: RequestBuilder {
public func get(path: [String], authenticated: Bool) -> Request {
get(path: path, parameters: nil, authenticated: authenticated)!
}
public func post(path: [String], body: Data?, authenticated: Bool) -> Request {
post(path: path, body: body, authenticated: authenticated)!
}
public func delete(path: [String], authenticated: Bool) -> Request {
delete(path: path, authenticated: authenticated)!
}
}
extension NetworkRequestToUse: Request {}
extension URLRequest: Request {
public var urlRequest: URLRequest { self }
}
protocol NetworkRequestConvertible {
var networkRequest: NetworkRequest { get }
}
struct AnyNetwork<N: NetworkAdapterAPI, R>: Network where R: Request & NetworkRequestConvertible {
let adapter: N
init(_ adapter: N, _ requestType: R.Type = R.self) {
self.adapter = adapter
}
func perform<ResponseType>(
request: R,
responseType: ResponseType.Type
) -> AnyPublisher<ResponseType, NetworkError> where ResponseType: Decodable {
adapter.perform(request: request.networkRequest, responseType: ResponseType.self)
}
func perform<ResponseType>(
request: Request, responseType: ResponseType.Type = ResponseType.self
) -> AnyPublisher<ResponseType, NetworkError> where ResponseType: Decodable {
guard let request = request as? R else {
return Fail(
error: NetworkError(
request: request.urlRequest,
type: .urlError(URLError(.badURL))
)
)
.eraseToAnyPublisher()
}
return perform(request: request, responseType: ResponseType.self)
}
}
extension NetworkRequest: NetworkRequestConvertible {
var networkRequest: NetworkRequest { self }
}
extension NetworkAdapterAPI {
public var network: Network { AnyNetwork(self, NetworkRequest.self) }
}
#if DEBUG
public struct URLRequestBuilder: RequestBuilder {
let baseURL: URL
var headers: [String: String] = [:]
var authorization: String
public init(
baseURL: URL,
headers: [String: String] = [:],
authorization: String
) {
self.baseURL = baseURL
self.headers = headers
self.authorization = authorization
}
public func get(
path: [String],
authenticated: Bool
) -> Request {
makeRequest(method: "GET", path: path, authenticated: authenticated)
}
public func post(
path: [String],
body: Data?,
authenticated: Bool
) -> Request {
var url = makeRequest(method: "POST", path: path, authenticated: authenticated)
url.httpBody = body
return url
}
public func delete(
path: [String],
authenticated: Bool
) -> Request {
makeRequest(method: "DELETE", path: path, authenticated: authenticated)
}
func makeRequest(method: String, path: [String], authenticated: Bool) -> URLRequest {
var url = URLRequest(
url: path.reduce(into: baseURL) { url, component in
url.appendPathComponent(component)
}
)
url.httpMethod = method
var allHTTPHeaderFields = headers
if authenticated {
allHTTPHeaderFields.merge(["Authorization": authorization])
}
url.allHTTPHeaderFields = allHTTPHeaderFields
return url
}
}
public class OfflineNetwork: Network {
public typealias Method = String
public let data: [URL: [Method: Any]]
public var requests: [URLRequest] = []
init(_ data: [URL: [Method: Any]]) {
self.data = data
}
public func perform<ResponseType>(
request: Request,
responseType: ResponseType.Type = ResponseType.self
) -> AnyPublisher<ResponseType, NetworkError> where ResponseType: Decodable {
requests.append(request.urlRequest)
guard
let url = request.urlRequest.url,
let method = request.urlRequest.httpMethod,
let value = data[url]?[method]
else {
return Fail(
error: NetworkError(
request: request.urlRequest,
type: .urlError(URLError(.unsupportedURL))
)
)
.eraseToAnyPublisher()
}
do {
let data = try JSONSerialization.data(withJSONObject: value, options: .fragmentsAllowed)
let object = try JSONDecoder().decode(ResponseType.self, from: data)
return Just(object).setFailureType(to: NetworkError.self).eraseToAnyPublisher()
} catch {
return Fail(
error: NetworkError(
request: request.urlRequest,
type: .payloadError(.emptyData)
)
)
.eraseToAnyPublisher()
}
}
}
public class SessionNetwork: Network {
public var session: URLSession
public init(session: URLSession = .shared) {
self.session = session
}
public func perform<ResponseType>(
request: Request,
responseType: ResponseType.Type = ResponseType.self
) -> AnyPublisher<ResponseType, NetworkError> where ResponseType: Decodable {
session.dataTaskPublisher(for: request.urlRequest)
.mapError { error in
NetworkError(request: request.urlRequest, type: .urlError(error))
}
.map(\.data)
.decode(type: ResponseType.self, decoder: JSONDecoder())
.mapError { _ in NetworkError(request: request.urlRequest, type: .serverError(.badResponse)) }
.eraseToAnyPublisher()
}
}
#endif
|
lgpl-3.0
|
655b959a01c99dd9bb2797379d8842da
| 28.23166 | 106 | 0.632149 | 4.987484 | false | false | false | false |
victoraliss0n/FireRecord
|
FireRecord/Source/Extensions/Storage/FirebaseModel+Storator.swift
|
1
|
2781
|
//
// FirebaseDataModel+Storator.swift
// FirebaseCommunity
//
// Created by David Sanford on 24/08/17.
//
import Foundation
import FirebaseCommunity
import HandyJSON
public extension Storator where Self: FirebaseModel {
func uploadFiles(completion: @escaping ([NameAndUrl?]) -> Void) {
let selfMirror = Mirror(reflecting: self)
var possibleUploads = [UploadOperation?]()
for (name, value) in selfMirror.children {
guard let name = name else { continue }
//This aditional cast to Anyobject is needed because of this swift bug: https://bugs.swift.org/browse/SR-3871
if let firebaseStorable = value as? AnyObject as? FirebaseStorable {
let uniqueId = NSUUID().uuidString
let storagePath = "FireRecord/\(Self.className)/\(Self.autoId)/\(name)-\(uniqueId)"
firebaseStorable.uploadFinishedCallback = { _ in
firebaseStorable.removeUploadProgress()
firebaseStorable.uploadFinishedCallback = nil
}
possibleUploads.append(
firebaseStorable.buildUploadOperation(fileName: name,
path: storagePath,
onProgress: firebaseStorable.onProgress,
uploadFinishedCallback: firebaseStorable.uploadFinishedCallback))
}
}
let uploads = possibleUploads.flatMap { $0 }
let operationQueue = UploadOperationQueue(operations: uploads)
operationQueue.startUploads { results in
completion(results)
}
}
internal mutating func deserializeStorablePaths(snapshot: DataSnapshot) {
let selfMirror = Mirror(reflecting: self)
let modelDictionary = snapshot.value as? NSDictionary
var storables = [String: Any]()
for (name, propertyValue) in selfMirror.children {
guard let name = name else { continue }
// Cast to OptionalProtocol because swift(4.0) still can't infer that FirebaseImage?.self is FirebaseStorable?.Type.
if let optionalProperty = propertyValue as? OptionalProtocol,
let propertyType = optionalProperty.wrappedType() as? FirebaseStorable.Type {
var firebaseStorable = propertyType.init()
firebaseStorable.path = modelDictionary?[name] as? String
storables[name] = firebaseStorable
}
}
JSONDeserializer.update(object: &self, from: storables)
}
}
|
mit
|
b7258886117d4e27b8e72215bfa2f0ed
| 39.897059 | 128 | 0.57785 | 5.734021 | false | false | false | false |
hisui/ReactiveSwift
|
ReactiveSwift/ArrayDeque.swift
|
1
|
2014
|
// Copyright (c) 2014 segfault.jp. All rights reserved.
public class ArrayDeque<A> {
private var dest: [A?]
private var base: Int = 0
private var size: Int = 0
public init(_ capacity: Int=8) {
var n = 1
while n < capacity {
n *= 2
}
dest = [A?](count:n, repeatedValue:nil)
}
public var count: Int { return size }
public subscript(i: Int) -> A? { return (0 <= i && i < size) ? get(i): nil }
public var head: A? { return self[0] }
public var last: A? { return self[size - 1] }
public func clear() {
dest = [A?](count:1, repeatedValue:nil)
base = 0
size = 0
}
public func toArray() -> [A] {
var a = Array<A?>(count:size, repeatedValue:nil)
drainTo(&a)
return a.map { $0! }
}
public func unshift(e: A) {
doubleCapacityIfFull()
if base == 0 { base = dest.count }
base--
size++
dest[base] = e
}
public func shift() -> A? {
if size == 0 { return nil }
let e = dest[base]
size--
base++
base &= dest.count - 1
return e
}
public func push(e: A) {
doubleCapacityIfFull()
dest[(base + size++) & (dest.count - 1)] = e
}
public func pop() -> A? {
return size > 0 ? get(--size): nil
}
private func get(i: Int) -> A? {
return dest[ (base + i) & (dest.count - 1) ]
}
private func doubleCapacityIfFull() {
if dest.count == size {
doubleCapacity()
}
}
private func doubleCapacity() {
var a = [A?](count:dest.count * 2, repeatedValue:nil)
drainTo(&a)
dest = a
base = 0
}
private func drainTo(inout o: [A?]) {
var i = 0
var j = base
let n = size
while i < n {
o[i++] = dest[j]
j += 1
j &= dest.count - 1
}
}
}
|
mit
|
0ac150ef59ebf135f7db4a90be189f40
| 21.377778 | 80 | 0.460775 | 3.695413 | false | false | false | false |
sishenyihuba/Weibo
|
Weibo/06-Compose(发布)/PicPicker/PicPickerCollectionView.swift
|
1
|
1730
|
//
// PicPickerCollectionView.swift
// Weibo
//
// Created by daixianglong on 2017/2/4.
// Copyright © 2017年 Dale. All rights reserved.
//
import UIKit
let picPickerIdentifier = "picPickerIdentifier"
let picMargin :CGFloat = 5
let picEdge :CGFloat = 12
class PicPickerCollectionView: UICollectionView {
var images : [UIImage] = [UIImage]() {
didSet {
reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
dataSource = self
setupCollectionViewLayout()
registerNib(UINib.init(nibName: "PicPickerCell", bundle: nil), forCellWithReuseIdentifier: picPickerIdentifier)
}
}
extension PicPickerCollectionView : UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count + 1
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = dequeueReusableCellWithReuseIdentifier(picPickerIdentifier, forIndexPath: indexPath) as! PicPickerCell
cell.image = (indexPath.row <= images.count - 1) ? images[indexPath.row] : nil
return cell
}
}
extension PicPickerCollectionView {
private func setupCollectionViewLayout() {
let itemWH = (UIScreen.mainScreen().bounds.width - 2 * picMargin - 2 * picEdge) / 3
let layout = collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSizeMake(itemWH, itemWH)
contentInset = UIEdgeInsetsMake(picEdge, picEdge, 0, picEdge)
}
}
|
mit
|
cb761bb4d786af494248c62821d7cc9c
| 27.311475 | 130 | 0.663578 | 5.109467 | false | false | false | false |
nathan3o4/Top-Movies
|
Top Movies/Top Movies/TopMoviesAsCollectionViewController.swift
|
2
|
5987
|
//
// TopMoviesAsCollectionViewController.swift
// Top Movies
//
// Created by Nathan Ansel on 1/24/16.
// Copyright © 2016 Nathan Ansel. All rights reserved.
//
import UIKit
import AFNetworking
import MBProgressHUD
class TopMoviesAsCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UISearchBarDelegate {
// MARK: - Properties
@IBOutlet weak var collectionView: UICollectionView!
var searchBar: UISearchBar!
var endPoint: String!
var movies = [NSDictionary]?()
var filteredMovies = [Movie]?()
var refreshControl: UIRefreshControl!
var hud: MBProgressHUD!
// MARK: - Methods
// MARK: View controller overrides
override func viewDidLoad() {
super.viewDidLoad()
searchBar = UISearchBar()
searchBar.showsCancelButton = false
searchBar.barStyle = .BlackTranslucent
navigationItem.titleView = searchBar
collectionView.dataSource = self
collectionView.delegate = self
searchBar.delegate = self
collectionView.allowsMultipleSelection = true
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: "refreshData", forControlEvents: UIControlEvents.ValueChanged)
refreshControl.layer.zPosition = -1
collectionView.insertSubview(refreshControl, atIndex: 0)
hud = MBProgressHUD.showHUDAddedTo(collectionView, animated: true)
hud.mode = .Indeterminate
hud.labelText = "Loading"
hud.removeFromSuperViewOnHide = true
refreshData()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let indexPaths = collectionView.indexPathsForSelectedItems() {
for indexPath in indexPaths {
collectionView.deselectItemAtIndexPath(indexPath, animated: true)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Collection view overrides
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MovieCollectionViewCell", forIndexPath: indexPath) as! MovieCollectionViewCell
if let posterPath = filteredMovies?[indexPath.row].posterPath {
let imageUrl = NSURL(string:"https://image.tmdb.org/t/p/w342" + posterPath)
cell.posterView.setImageWithURL(imageUrl!)
}
else {
}
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let numRows = filteredMovies?.count {
return numRows
}
return 0
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let aspectRatio = CGFloat(300) / CGFloat(444)
let width = view.frame.size.width / 3
let height = width / aspectRatio
return CGSizeMake(width, height)
}
// MARK: Reloading data
/// Refreshes the movie data held in the app.
///
/// - author: Nathan Ansel
///
func refreshData() {
let apiKey = "a07e22bc18f5cb106bfe4cc1f83ad8ed"
let url = NSURL(string:"https://api.themoviedb.org/3/movie/\(endPoint)?api_key=\(apiKey)")
let request = NSURLRequest(URL: url!)
let session = NSURLSession(
configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate:nil,
delegateQueue:NSOperationQueue.mainQueue()
)
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request,
completionHandler: { (dataOrNil, response, error) in
if let data = dataOrNil {
if let responseDictionary = try! NSJSONSerialization.JSONObjectWithData(
data, options:[]) as? NSDictionary {
let results = responseDictionary["results"] as! [NSDictionary]
self.movies = results
self.makeMovieList(self.movies!)
self.collectionView.reloadData()
// NSLog("response: \(responseDictionary)")
self.hud.hide(true)
}
}
else {
print("failed response")
}
self.refreshControl.endRefreshing()
});
task.resume()
}
func makeMovieList(dictionaryList: [NSDictionary]) {
filteredMovies = [Movie]()
for dict in dictionaryList {
filteredMovies?.append(Movie(
title: dict["title"] as? String,
overview: dict["overview"] as? String,
rating: dict["vote_average"] as? Double,
posterPath: dict["poster_path"] as? String,
releaseDateString: dict["release_date"] as? String))
}
}
// MARK: Animations
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
searchBar.endEditing(true)
if segue.identifier == "toDetailView" {
let destinationViewController = segue.destinationViewController as! DetailViewController
let cell = sender as! MovieCollectionViewCell
let indexPath = collectionView.indexPathForCell(cell)
destinationViewController.movie = filteredMovies![indexPath!.row]
// destinationViewController.hidesBottomBarWhenPushed = true
}
}
// MARK: Search Bar Delegate
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
makeMovieList(movies!)
if searchText != "" {
filteredMovies = filteredMovies!.filter({(movie: Movie) -> Bool in
(movie.title).lowercaseString.containsString(searchText.lowercaseString)
|| (movie.overview).lowercaseString.containsString(searchText.lowercaseString)
})
}
collectionView.reloadData()
}
}
|
apache-2.0
|
9e6ec83bfc1def690d6358524c5435a6
| 28.343137 | 172 | 0.676412 | 5.283319 | false | false | false | false |
Antondomashnev/FBSnapshotsViewer
|
FBSnapshotsViewerTests/KaleidoscopeViewerSpec.swift
|
1
|
5541
|
//
// KaleidoscopeViewerSpec.swift
// FBSnapshotsViewer
//
// Created by Anton Domashnev on 06.05.17.
// Copyright © 2017 Anton Domashnev. All rights reserved.
//
import Foundation
import Quick
import Nimble
@testable import FBSnapshotsViewer
private class ProcessLauncherMock: ProcessLauncher {
var launchedProcessPath: String?
var launchedProcessArguments: [String]?
override func launchProcess(at launchPath: String, with arguments: [String]?) {
launchedProcessPath = launchPath
launchedProcessArguments = arguments
}
}
private class OSXApplicationFinderMock: OSXApplicationFinder {
var applicationURL: URL?
override func findApplication(with bundleIdentifier: String) -> URL? {
return applicationURL
}
}
class KaleidoscopeViewerSpec: QuickSpec {
override func spec() {
let subject: KaleidoscopeViewer.Type = KaleidoscopeViewer.self
var processLauncher: ProcessLauncherMock!
var osxApplicationFinder: OSXApplicationFinderMock!
beforeEach {
processLauncher = ProcessLauncherMock()
osxApplicationFinder = OSXApplicationFinderMock()
}
describe("name") {
it("is Kaleidoscope") {
expect(subject.name).to(equal("Kaleidoscope"))
}
}
describe("bundleID") {
it("is correct") {
expect(subject.bundleID).to(equal("com.blackpixel.kaleidoscope"))
}
}
describe(".canView") {
var testResult: SnapshotTestResult!
var build: Build!
var testInformation: SnapshotTestInformation!
beforeEach {
build = Build(date: Date(), applicationName: "MyApp", fbReferenceImageDirectoryURLs: [URL(fileURLWithPath: "foo/bar", isDirectory: true)])
testInformation = SnapshotTestInformation(testClassName: "ExampleTestClass", testName: "testName", testFilePath: "testFilePath", testLineNumber: 1)
}
context("for recorded snapshot test result") {
beforeEach {
testResult = SnapshotTestResult.recorded(testInformation: testInformation, referenceImagePath: "foo/bar/referenceImage.png", build: build)
}
it("returns false") {
expect(subject.canView(snapshotTestResult: testResult)).to(beFalse())
}
}
context("for failed snapshot test result") {
beforeEach {
testResult = SnapshotTestResult.failed(testInformation: testInformation, referenceImagePath: "foo/bar/referenceImage.png", diffImagePath: "foo/bar/diffImage.png", failedImagePath: "foo/bar/failedImage.png", build: build)
}
it("returns true") {
expect(subject.canView(snapshotTestResult: testResult)).to(beTrue())
}
}
}
describe(".isAvailable") {
context("when application finder finds the app with bundleID") {
beforeEach {
osxApplicationFinder.applicationURL = URL(fileURLWithPath: "foo/bar.app")
}
it("is true") {
expect(subject.isAvailable(osxApplicationFinder: osxApplicationFinder)).to(beTrue())
}
}
context("when application finder doesn't find the app with bundleID") {
beforeEach {
osxApplicationFinder.applicationURL = nil
}
it("is false") {
expect(subject.isAvailable(osxApplicationFinder: osxApplicationFinder)).to(beFalse())
}
}
}
describe(".view") {
var testResult: SnapshotTestResult!
var build: Build!
var testInformation: SnapshotTestInformation!
beforeEach {
build = Build(date: Date(), applicationName: "MyApp", fbReferenceImageDirectoryURLs: [URL(fileURLWithPath: "foo/bar", isDirectory: true)])
testInformation = SnapshotTestInformation(testClassName: "ExampleTestClass", testName: "testName", testFilePath: "testFilePath", testLineNumber: 1)
}
context("for recorded snapshot test result") {
beforeEach {
testResult = SnapshotTestResult.recorded(testInformation: testInformation, referenceImagePath: "foo/bar/referenceImage.png", build: build)
}
it("throws an assertion") {
expect { subject.view(snapshotTestResult: testResult, using: processLauncher) }.to(throwAssertion())
}
}
context("for failed snapshot test result") {
beforeEach {
testResult = SnapshotTestResult.failed(testInformation: testInformation, referenceImagePath: "foo/bar/referenceImage.png", diffImagePath: "foo/bar/diffImage.png", failedImagePath: "foo/bar/failedImage.png", build: build)
}
it("launches correct process") {
subject.view(snapshotTestResult: testResult, using: processLauncher)
expect(processLauncher.launchedProcessArguments).to(equal(["foo/bar/referenceImage.png", "foo/bar/failedImage.png"]))
expect(processLauncher.launchedProcessPath).to(equal("/usr/local/bin/ksdiff"))
}
}
}
}
}
|
mit
|
3b3625b4bc12651ff28b9f6c5d00459c
| 38.014085 | 240 | 0.601264 | 5.236295 | false | true | false | false |
apple/swift
|
test/decl/protocol/special/coding/class_codable_inheritance_diagnostics.swift
|
23
|
4573
|
// RUN: %target-typecheck-verify-swift -verify-ignore-unknown
// Non-Decodable superclasses of synthesized Decodable classes must implement
// init().
class NonDecodableSuper { // expected-note {{cannot automatically synthesize 'init(from:)' because superclass does not have a callable 'init()'}}
init(_: Int) {}
}
class NonDecodableSub : NonDecodableSuper, Decodable { // expected-error {{type 'NonDecodableSub' does not conform to protocol 'Decodable'}}
}
// Non-Decodable superclasses of synthesized Decodable classes must have
// designated init()'s.
class NonDesignatedNonDecodableSuper {
convenience init() { // expected-note {{cannot automatically synthesize 'init(from:)' because implementation would need to call 'init()', which is not designated}}
self.init(42)
}
init(_: Int) {}
}
class NonDesignatedNonDecodableSub : NonDesignatedNonDecodableSuper, Decodable { // expected-error {{type 'NonDesignatedNonDecodableSub' does not conform to protocol 'Decodable'}}
}
// Non-Decodable superclasses of synthesized Decodable classes must have an
// accessible init().
class InaccessibleNonDecodableSuper {
private init() {} // expected-note {{cannot automatically synthesize 'init(from:)' because implementation would need to call 'init()', which is inaccessible due to 'private' protection level}}
}
class InaccessibleNonDecodableSub : InaccessibleNonDecodableSuper, Decodable { // expected-error {{type 'InaccessibleNonDecodableSub' does not conform to protocol 'Decodable'}}
}
// Non-Decodable superclasses of synthesized Decodable classes must have a
// non-failable init().
class FailableNonDecodableSuper {
init?() {} // expected-note {{cannot automatically synthesize 'init(from:)' because implementation would need to call 'init()', which is failable}}
}
class FailableNonDecodableSub : FailableNonDecodableSuper, Decodable { // expected-error {{type 'FailableNonDecodableSub' does not conform to protocol 'Decodable'}}
}
// Subclasses of classes whose Decodable synthesis fails should not inherit
// conformance.
class FailedSynthesisDecodableSuper : Decodable { // expected-error 2{{type 'FailedSynthesisDecodableSuper' does not conform to protocol 'Decodable'}}
enum CodingKeys : String, CodingKey {
case nonexistent // expected-note 2{{CodingKey case 'nonexistent' does not match any stored properties}}
}
}
class FailedSynthesisDecodableSub : FailedSynthesisDecodableSuper { // expected-note {{did you mean 'init'?}}
func foo() {
// Decodable should fail to synthesis or be inherited.
let _ = FailedSynthesisDecodableSub.init(from:) // expected-error {{type 'FailedSynthesisDecodableSub' has no member 'init(from:)'}}
}
}
// Subclasses of Decodable classes which can't inherit their initializers should
// produce diagnostics.
class DecodableSuper : Decodable {
var value = 5
}
class DecodableSubWithoutInitialValue : DecodableSuper { // expected-error {{class 'DecodableSubWithoutInitialValue' has no initializers}}
// expected-note@-1 {{did you mean to override 'init(from:)'?}}{{1-1=\noverride init(from decoder: Decoder) throws {\n <#code#>\n\}}}
var value2: Int // expected-note {{stored property 'value2' without initial value prevents synthesized initializers}}
}
class DecodableSubWithInitialValue : DecodableSuper {
var value2 = 10
}
// Subclasses of Codable classes which can't inherit their initializers should
// produce diagnostics.
class CodableSuper : Codable {
var value = 5
}
class CodableSubWithoutInitialValue : CodableSuper { // expected-error {{class 'CodableSubWithoutInitialValue' has no initializers}}
// expected-note@-1 {{did you mean to override 'init(from:)' and 'encode(to:)'?}}{{1-1=\noverride init(from decoder: Decoder) throws {\n <#code#>\n\}\n\noverride func encode(to encoder: Encoder) throws {\n <#code#>\n\}}}
var value2: Int // expected-note {{stored property 'value2' without initial value prevents synthesized initializers}}
}
// We should only mention encode(to:) in the diagnostic if the subclass does not
// override it.
class EncodableSubWithoutInitialValue : CodableSuper { // expected-error {{class 'EncodableSubWithoutInitialValue' has no initializers}}
// expected-note@-1 {{did you mean to override 'init(from:)'?}}{{1-1=\noverride init(from decoder: Decoder) throws {\n <#code#>\n\}}}
var value2: Int // expected-note {{stored property 'value2' without initial value prevents synthesized initializers}}
override func encode(to: Encoder) throws {}
}
class CodableSubWithInitialValue : CodableSuper {
var value2 = 10
}
|
apache-2.0
|
7f211705d3af8b099dc3ae882c59ee7a
| 47.136842 | 228 | 0.753335 | 4.605237 | false | false | false | false |
hackiftekhar/IQKeyboardManager
|
Demo/Swift_Demo/ViewController/TextViewSpecialCaseViewController.swift
|
1
|
2383
|
//
// TextViewSpecialCaseViewController.swift
// IQKeyboard
//
// Created by Iftekhar on 23/09/14.
// Copyright (c) 2014 Iftekhar. All rights reserved.
//
import UIKit
class TextViewSpecialCaseViewController: UIViewController, UITextViewDelegate, UIPopoverPresentationControllerDelegate {
@IBOutlet var buttonPush: UIButton!
@IBOutlet var buttonPresent: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
if self.navigationController == nil {
buttonPush.isHidden = true
buttonPresent.setTitle("Dismiss", for: .normal)
}
}
override func viewWillAppear (_ animated: Bool) {
super.viewWillAppear(animated)
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
textView.resignFirstResponder()
}
return true
}
@IBAction func presentClicked (_ barButton: UIButton!) {
if (navigationController) != nil {
if let controller = self.storyboard?.instantiateViewController(withIdentifier: "TextViewSpecialCaseViewController") {
present(controller, animated: true, completion: nil)
}
} else {
dismiss(animated: true, completion: nil)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let identifier = segue.identifier else {
return
}
if identifier == "SettingsNavigationController" {
let controller = segue.destination
controller.modalPresentationStyle = .popover
controller.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem
let heightWidth = max(UIScreen.main.bounds.width, UIScreen.main.bounds.height)
controller.preferredContentSize = CGSize(width: heightWidth, height: heightWidth)
controller.popoverPresentationController?.delegate = self
}
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
func prepareForPopoverPresentation(_ popoverPresentationController: UIPopoverPresentationController) {
self.view.endEditing(true)
}
override var shouldAutorotate: Bool {
return true
}
}
|
mit
|
93df532671945d41e216e3137e30bd93
| 28.7875 | 129 | 0.665967 | 5.580796 | false | false | false | false |
ferranabello/Viperit
|
Example/modules/TableOfContents/TableOfContentsView.swift
|
1
|
1669
|
//
// TableOfContentsView.swift
// Viperit
//
// Created by Ferran on 01/04/2019.
//Copyright © 2019 Ferran Abelló. All rights reserved.
//
import UIKit
import Viperit
//MARK: TableOfContentsView Class
final class TableOfContentsView: TableUserInterface {
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Viperit App"
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0: presenter.showHome()
case 1: presenter.showCool()
case 2: presenter.showSimple()
default: break
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
switch indexPath.row {
case 0:
cell.textLabel?.text = "Storyboard module"
case 1:
cell.textLabel?.text = "Swift UI module"
case 2:
cell.textLabel?.text = "Code-generated module"
default: break
}
return cell
}
}
//MARK: - TableOfContentsView API
extension TableOfContentsView: TableOfContentsViewApi {
}
// MARK: - TableOfContentsView Viper Components API
private extension TableOfContentsView {
var presenter: TableOfContentsPresenterApi {
return _presenter as! TableOfContentsPresenterApi
}
var displayData: TableOfContentsDisplayData {
return _displayData as! TableOfContentsDisplayData
}
}
|
mit
|
6a58c6e1c83720649a81495b27ee310c
| 26.327869 | 109 | 0.659868 | 4.976119 | false | false | false | false |
Yeltsinn/FloatingNavigator
|
FloatingNavigator/FNViewController.swift
|
1
|
8620
|
//
// FNViewController.swift
// FloatingNavigator
//
// Created by Yeltsin Suares Lobato Gama on 10/6/16.
// Copyright © 2016 Yeltsin Suares Lobato Gama. All rights reserved.
//
import UIKit
class FNViewController: UIViewController, UIScrollViewDelegate {
/* TabViews Structural Attributes */
internal var tabViewsHeigth: CGFloat = 50
internal var tabViewIndicatorHeigth: CGFloat = 2
internal var scaleFactorOfImageInTabView: CGFloat = 1
internal var distanceBetweenTabViewComponents: CGFloat = 2
internal var distanceTabViewComponentsToSideBounds: CGFloat = 10
/* TabViews Customization Attributes */
internal var colorOfTabViewIndicator: UIColor = UIColor.red
internal var colorOfTabViewTitlesInActiveState: UIColor = UIColor.black
internal var colorOfTabViewTitlesInInactiveState: UIColor = UIColor.lightGray
/* SearchBar Customization Attributes */
internal var colorOfSearchBarText: UIColor = UIColor.blue
internal var colorOfSearchBarIcon: UIColor = UIColor.lightGray
internal var colorOfSearchBarTextField: UIColor = UIColor.white
internal var colorOfSearchBarPlaceholder: UIColor = UIColor.lightGray
internal var colorOfSearchBarBox: UIColor = UIColor(colorLiteralRed: 225.0/255,
green: 228.0/255,
blue: 229.0/255,
alpha: 1.0)
/* DataSource Attributes */
internal var numberOfTabs: Int = 0
/* FNSegementControl Components */
internal var tabViews = [UIView]()
internal var tabViewIndicator: UIView!
internal var tabViewsTitles = [String]()
internal var tabViewsImages = [UIImageView]()
internal var tabViewsImagesActiveState = [UIImage]()
internal var tabViewsImagesInactiveState = [UIImage]()
internal var tabViewsTitlesLabels = [UILabel]()
internal var tabViewsControllers = [UIViewController]()
/* Auxiliar Components */
internal var addSearchController: Bool = false
internal var searchController: UISearchController!
internal var currentControllerInFocus: UIViewController!
internal var scrollView: UIScrollView!
internal var mainView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
internal var headerView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
internal var tabViewIndicatorStyle: TabViewIndicatorStyle = .simple
{
didSet {
self.checkFNViewControllerDataSourceRequired()
self.setupTabIndicatorConstraints()
}
}
internal var tabViewsSeparatorStyle: TabViewSeparatorStyle = .none {
didSet {
self.checkFNViewControllerDataSourceRequired()
self.setupTabViewsSeparator()
}
}
/* Constraints */
internal var constraintsToActivate = [NSLayoutConstraint]()
internal var distanceTabIndicatorToMarginLeftConstraint: NSLayoutConstraint!
/* Delegates and DataSource */
var fNViewControllerDataSource: FNViewControllerDataSource!
var fNViewControllerDelegate: FNViewControllerDelegate!
var fNViewControllerSearchBarCustomize: FNViewControllerSearchBarCustomize!
func setupFNSegmentControl() {
checkFNViewControllerDataSourceRequired()
checkFNViewControllerDataSourceOptional()
checkFNViewControllerDelegateOptional()
setupImageViews()
if addSearchController {
checkFNViewControllerSearchBarCustomizeOptional()
setupSearchController()
}
setupFNScrollView(numberOfPagesInScroll: numberOfTabs)
createTabViews()
setupConstraints()
}
/* Check DataSouce Required Values */
private func checkFNViewControllerDataSourceRequired() {
guard numberOfTabs == 0 else { return }
numberOfTabs = fNViewControllerDataSource.numberOfTabsInSegmentControl()
for index in 0...numberOfTabs - 1 {
tabViewsControllers.append(fNViewControllerDataSource.controllerOfTabViewAtIndex(index: index))
}
}
/* Check DataSouce Optional Values */
private func checkFNViewControllerDataSourceOptional() {
for index in 0...numberOfTabs - 1 {
if let title = fNViewControllerDataSource?.titleForTabViewAtIndex?(index: index) {
tabViewsTitles.append(title)
}
if let image = fNViewControllerDataSource?.imageForTabViewAtIndexInInactiveState?(index: index) {
tabViewsImagesInactiveState.append(image)
}
if let image = fNViewControllerDataSource?.imageForTabViewAtIndexInActiveState?(index: index) {
tabViewsImagesActiveState.append(image)
}
}
}
private func setupImageViews() {
for image in tabViewsImagesInactiveState {
tabViewsImages.append(UIImageView(image: image))
}
if tabViewsImagesInactiveState.isEmpty {
for image in tabViewsImagesActiveState {
tabViewsImages.append(UIImageView(image: image))
}
} else {
guard !tabViewsImagesActiveState.isEmpty else { return }
tabViewsImages.first?.image = tabViewsImagesActiveState.first
}
}
/* Check Delegate Optional Values */
private func checkFNViewControllerDelegateOptional() {
if let bool = fNViewControllerDelegate?.addSearchBar?() {
addSearchController = bool
}
if let value = fNViewControllerDelegate?.setTabViewIndicatorHeigth?() {
tabViewIndicatorHeigth = value
}
if let value = fNViewControllerDelegate?.setTabViewsHeigth?() {
tabViewsHeigth = value
}
if let value = fNViewControllerDelegate?.setScaleFactorOfImageInTabView?() {
scaleFactorOfImageInTabView = value
}
if let value = fNViewControllerDelegate?.setDistanceTabViewComponentsToSideBounds?() {
distanceTabViewComponentsToSideBounds = value
}
if let value = fNViewControllerDelegate?.setDistanceBetweenTabViewComponents?() {
distanceBetweenTabViewComponents = value
}
if let color = fNViewControllerDelegate?.setColorOfTabViewTitlesInActiveState?() {
colorOfTabViewTitlesInActiveState = color
}
if let color = fNViewControllerDelegate?.setColorOfTabViewTitlesInInactiveState?() {
colorOfTabViewTitlesInInactiveState = color
}
if let color = fNViewControllerDelegate?.setColorOfTabViewIndicator?() {
colorOfTabViewIndicator = color
}
}
/* Check SearchBarCustomize Delegate Optional Values */
private func checkFNViewControllerSearchBarCustomizeOptional() {
if let color = fNViewControllerSearchBarCustomize?.setColorOfSearchBarBox?() {
colorOfSearchBarBox = color
}
if let color = fNViewControllerSearchBarCustomize?.setColorOfSearchBarIcon?() {
colorOfSearchBarIcon = color
}
if let color = fNViewControllerSearchBarCustomize?.setColorOfSearchBarText?() {
colorOfSearchBarText = color
}
if let color = fNViewControllerSearchBarCustomize?.setColorOfSearchBarTextField?() {
colorOfSearchBarTextField = color
}
if let color = fNViewControllerSearchBarCustomize?.setColorOfSearchBarPlaceholder?() {
colorOfSearchBarPlaceholder = color
}
}
/* Setup Constraints */
private func setupConstraints() {
if addSearchController {
self.setupSearchBarConstraints()
}
self.setupMainViewConstraints()
self.setupScrollViewConstraints()
self.setupHeaderViewConstraints()
self.setupTabIndicatorConstraints()
self.setHeightConstraintsOfTabViews()
self.setWidthConstraintsOfTabViews()
self.setCenterYConstraintOfTabViews()
self.setConstraintsToFirstAndLastTabViews()
self.setupViewControllersConstraints()
self.setConstraintDistanceBetweenTabViews()
self.setupLabelsTitlesAndImagesConstraints()
self.setupSwitchTabViewButtons()
NSLayoutConstraint.activate(constraintsToActivate)
}
}
|
mit
|
72634302cf1c45df4f694b84deb03ab4
| 37.137168 | 109 | 0.661562 | 5.546332 | false | false | false | false |
lorentey/GlueKit
|
Sources/NSButton Glue.swift
|
1
|
1665
|
//
// NSButton Glue.swift
// macOS
//
// Created by Károly Lőrentey on 2017-09-05.
// Copyright © 2017 Károly Lőrentey. All rights reserved.
//
#if os(macOS)
import AppKit
extension NSButton {
@objc open dynamic override var glue: GlueForNSButton { return _glue() }
}
public func <-- <V: UpdatableValueType>(target: GlueForNSButton.StateReceiver, model: V) where V.Value == NSControl.StateValue {
target.glue.model = model.anyUpdatableValue
}
public func <-- <B: UpdatableValueType>(target: GlueForNSButton.StateReceiver, model: B) where B.Value == Bool {
target.glue.model = model.map({ $0 ? .on : .off }, inverse: { $0 == .off ? false : true })
}
open class GlueForNSButton: GlueForNSControl {
private var object: NSButton { return owner as! NSButton }
public struct StateReceiver {
let glue: GlueForNSButton
}
public var state: StateReceiver { return StateReceiver(glue: self) }
private let modelConnector = Connector()
fileprivate var model: AnyUpdatableValue<NSControl.StateValue>? {
didSet {
modelConnector.disconnect()
if object.target === self {
object.target = nil
object.action = nil
}
if let model = model {
object.target = self
object.action = #selector(GlueForNSButton.buttonAction(_:))
modelConnector.connect(model.values) { [unowned self] value in
self.object.state = value
}
}
}
}
@IBAction func buttonAction(_ sender: NSButton) {
self.model?.value = sender.state
}
}
#endif
|
mit
|
4277195e33fa2543fe1d3ae6171d7b01
| 29.181818 | 128 | 0.61988 | 4.245524 | false | false | false | false |
sahandnayebaziz/Dana-Hills
|
Dana Hills/News.swift
|
1
|
1826
|
//
// News.swift
// Dana Hills
//
// Created by Nayebaziz, Sahand on 9/21/16.
// Copyright © 2016 Nayebaziz, Sahand. All rights reserved.
//
import Foundation
import Alamofire
import PromiseKit
import Fuzi
struct NewsArticle {
var title: String
var body: String
var datePublished: Date
}
extension DanaHillsBack {
static func getNews() -> Promise<[NewsArticle]> {
return Promise { resolve, reject in
let rssUrl = "http://dhhs.schoolloop.com/cms/rss?d=x&group_id=1169069797587"
request(rssUrl, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil)
.responseString { response in
guard let responseString = response.result.value else {
return reject(DanaHillsBackError.BadResponse)
}
guard let xml = try? XMLDocument(string: responseString) else {
return reject(DanaHillsBackError.BadResponse)
}
var news: [NewsArticle] = []
for item in xml.xpath("//channel/item") {
if let title = item.firstChild(tag: "title")?.stringValue,
let body = item.firstChild(tag: "description")?.stringValue,
let datePublished = item.firstChild(tag: "pubDate")?.stringValue,
let date = Date(fromString: datePublished, format: .rss) {
news.append(NewsArticle(title: title, body: body, datePublished: date))
}
}
resolve(news)
}
}
}
}
|
mit
|
5fcba9d661d7228859aeace4b913869d
| 32.796296 | 103 | 0.506849 | 4.986339 | false | false | false | false |
kperryua/swift
|
test/SILGen/default_arguments_generic.swift
|
1
|
1396
|
// RUN: %target-swift-frontend -emit-silgen -swift-version 3 %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-silgen -swift-version 4 %s | %FileCheck %s
func foo<T: ExpressibleByIntegerLiteral>(_: T.Type, x: T = 0) { }
struct Zim<T: ExpressibleByIntegerLiteral> {
init(x: T = 0) { }
init<U: ExpressibleByFloatLiteral>(_ x: T = 0, y: U = 0.5) { }
static func zim(x: T = 0) { }
static func zang<U: ExpressibleByFloatLiteral>(_: U.Type, _ x: T = 0, y: U = 0.5) { }
}
// CHECK-LABEL: sil hidden @_TF25default_arguments_generic3barFT_T_ : $@convention(thin) () -> () {
func bar() {
// CHECK: [[FOO_DFLT:%.*]] = function_ref @_TIF25default_arguments_generic3foo
// CHECK: apply [[FOO_DFLT]]<Int, Int>
foo(Int.self)
// CHECK: [[ZIM_DFLT:%.*]] = function_ref @_TIZFV25default_arguments_generic3Zim3zim
// CHECK: apply [[ZIM_DFLT]]<Int, Int>
Zim<Int>.zim()
// CHECK: [[ZANG_DFLT_0:%.*]] = function_ref @_TIZFV25default_arguments_generic3Zim4zang
// CHECK: apply [[ZANG_DFLT_0]]<Int, Double, Int, Double>
// CHECK: [[ZANG_DFLT_1:%.*]] = function_ref @_TIZFV25default_arguments_generic3Zim4zang
// CHECK: apply [[ZANG_DFLT_1]]<Int, Double, Int, Double>
Zim<Int>.zang(Double.self)
// CHECK: [[ZANG_DFLT_1:%.*]] = function_ref @_TIZFV25default_arguments_generic3Zim4zang
// CHECK: apply [[ZANG_DFLT_1]]<Int, Double, Int, Double>
Zim<Int>.zang(Double.self, 22)
}
|
apache-2.0
|
1ce986610af2cec026a7bfd8279f2586
| 45.533333 | 99 | 0.647564 | 2.995708 | false | false | false | false |
evanhughes3/reddit-news-swift
|
reddit-news-swift/Domain/Models/NetworkError.swift
|
1
|
720
|
protocol NetworkErrorProtocol: Error {
var localizedTitle: String { get }
var localizedDescription: String { get }
var code: Int { get }
}
struct NetworkError: NetworkErrorProtocol, Equatable {
var localizedTitle: String
var localizedDescription: String
var code: Int
init(localizedTitle: String?, localizedDescription: String, code: Int) {
self.localizedTitle = localizedTitle ?? "Error"
self.localizedDescription = localizedDescription
self.code = code
}
static func ==(lhs: NetworkError, rhs: NetworkError) -> Bool {
return lhs.localizedTitle == rhs.localizedTitle &&
lhs.localizedDescription == rhs.localizedDescription &&
lhs.code == rhs.code
}
}
|
mit
|
67669958c8c35ebedee82a92a12a6382
| 29.041667 | 74 | 0.704167 | 5.034965 | false | false | false | false |
TrustWallet/trust-wallet-ios
|
Trust/Foundation/QRURLParser.swift
|
1
|
2256
|
// Copyright DApps Platform Inc. All rights reserved.
import Foundation
struct ParserResult {
let protocolName: String
let address: String
let params: [String: String]
}
struct QRURLParser {
static func from(string: String) -> ParserResult? {
let parts = string.components(separatedBy: ":")
if parts.count == 1, let address = parts.first, CryptoAddressValidator.isValidAddress(address) {
return ParserResult(
protocolName: "",
address: address,
params: [:]
)
}
if parts.count == 2, let address = QRURLParser.getAddress(from: parts.last), CryptoAddressValidator.isValidAddress(address) {
let uncheckedParamParts = Array(parts[1].components(separatedBy: "?")[1...])
let paramParts = uncheckedParamParts.isEmpty ? [] : Array(uncheckedParamParts[0].components(separatedBy: "&"))
let params = QRURLParser.parseParamsFromParamParts(paramParts: paramParts)
return ParserResult(
protocolName: parts.first ?? "",
address: address,
params: params
)
}
return nil
}
private static func getAddress(from: String?) -> String? {
guard let from = from, from.count >= AddressValidatorType.ethereum.addressLength else {
return .none
}
return from.substring(to: AddressValidatorType.ethereum.addressLength)
}
private static func parseParamsFromParamParts(paramParts: [String]) -> [String: String] {
if paramParts.isEmpty {
return [:]
}
var params = [String: String]()
var i = 0
while i < paramParts.count {
let tokenizedParamParts = paramParts[i].components(separatedBy: "=")
if tokenizedParamParts.count < 2 {
break
}
params[tokenizedParamParts[0]] = tokenizedParamParts[1]
i += 1
}
return params
}
}
extension ParserResult: Equatable {
static func == (lhs: ParserResult, rhs: ParserResult) -> Bool {
return lhs.protocolName == rhs.protocolName && lhs.address == rhs.address && lhs.params == rhs.params
}
}
|
gpl-3.0
|
0cfcaa283fedddb6a55b907ab1c9d32f
| 33.707692 | 133 | 0.598848 | 4.739496 | false | false | false | false |
Brightify/ReactantUI
|
Example-tvOS/Source/AppDelegate.swift
|
1
|
617
|
//
// AppDelegate.swift
// Example-tvOS
//
// Created by Matous Hybl on 03/11/2017.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
let window = UIWindow()
self.window = window
window.backgroundColor = .white
window.rootViewController = ViewController()
window.makeKeyAndVisible()
activateLiveReload(in: window)
return true
}
}
|
mit
|
dedc2be94685e02091ff69c6e92a82bb
| 23.68 | 151 | 0.688817 | 4.975806 | false | false | false | false |
shridharmalimca/iOSDev
|
iOS/Components/ShoppingCart/ShoppingCart/SelectedProductDataModel.swift
|
2
|
636
|
//
// SelectedProductDataModel.swift
// ShoppingCart
//
// Created by Shridhar Mali on 12/26/16.
// Copyright © 2016 TIS. All rights reserved.
//
import UIKit
class SelectedProductDataModel: NSObject {
static let sharedInstance = SelectedProductDataModel()
var selectedProductImageUrl = String()
var selectedProductName = String()
var selectedProductOwner = String()
var selectedProductPrice = Double()
func clearAllData() {
selectedProductImageUrl = String()
selectedProductName = String()
selectedProductOwner = String()
selectedProductPrice = Double()
}
}
|
apache-2.0
|
a16a8c629761a6ae222129c79db4105b
| 24.4 | 58 | 0.689764 | 4.635036 | false | false | false | false |
renyufei8023/WeiBo
|
weibo/Classes/Main/Controller/BaseTableViewController.swift
|
1
|
1181
|
//
// BaseTableViewController.swift
// weibo
//
// Created by 任玉飞 on 16/4/25.
// Copyright © 2016年 任玉飞. All rights reserved.
//
import UIKit
class BaseTableViewController: UITableViewController {
var userLogin = false
var visitorView: VisitorView?
override func loadView() {
userLogin ? super.loadView() : setupVisitorView()
}
private func setupVisitorView() {
let customView = VisitorView()
view = customView
visitorView = customView
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: "registerBtnWillClick")
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self, action: "loginBtnWillClick")
}
override func viewDidLoad() {
super.viewDidLoad()
}
func leftBtnClick() {
}
//MARK:-导航栏按钮
func registerBtnWillClick() -> Void {
}
func loginBtnWillClick() -> Void {
}
}
|
mit
|
7d3e34ebbd0087cc8386438c9079422c
| 23.425532 | 152 | 0.641986 | 4.948276 | false | false | false | false |
schrockblock/gtfs-stations
|
Pod/Classes/NYCStop.swift
|
1
|
722
|
//
// Stop.swift
// GTFS Stations
//
// Created by Elliot Schrock on 7/25/15.
// Copyright (c) 2015 Elliot Schrock. All rights reserved.
//
import UIKit
import SubwayStations
open class NYCStop: NSObject, Stop {
public var latitude: Double?
public var longitude: Double?
@objc open var name: String!
@objc open var objectId: String!
@objc open var parentId: String!
open var station: Station!
@objc init(name: String!, objectId: String!, parentId: String?, latitude: Double, longitude: Double) {
super.init()
self.name = name
self.objectId = objectId
self.parentId = parentId
self.latitude = latitude
self.longitude = longitude
}
}
|
mit
|
6d893173529d61e718cc3c91d000c747
| 24.785714 | 106 | 0.65097 | 3.98895 | false | false | false | false |
AdaptiveMe/adaptive-arp-api-lib-darwin
|
Pod/Classes/Sources.Api/FileListResultCallbackImpl.swift
|
1
|
4647
|
/**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:[email protected]>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:[email protected]>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
Interface for Managing the File result operations
Auto-generated implementation of IFileListResultCallback specification.
*/
public class FileListResultCallbackImpl : BaseCallbackImpl, IFileListResultCallback {
/**
Constructor with callback id.
@param id The id of the callback.
*/
public override init(id : Int64) {
super.init(id: id)
}
/**
On error result of a file operation.
@param error Error processing the request.
@since v2.0
*/
public func onError(error : IFileListResultCallbackError) {
let param0 : String = "Adaptive.IFileListResultCallbackError.toObject(JSON.parse(\"{ \\\"value\\\": \\\"\(error.toString())\\\"}\"))"
var callbackId : Int64 = -1
if (getId() != nil) {
callbackId = getId()!
}
AppRegistryBridge.sharedInstance.getPlatformContextWeb().executeJavaScript("Adaptive.handleFileListResultCallbackError( \(callbackId), \(param0))")
}
/**
On correct result of a file operation.
@param files Array of resulting files/folders.
@since v2.0
*/
public func onResult(files : [FileDescriptor]) {
let param0Array : NSMutableString = NSMutableString()
param0Array.appendString("[")
for (index,obj) in files.enumerate() {
param0Array.appendString("Adaptive.FileDescriptor.toObject(JSON.parse(\"\(JSONUtil.escapeString(FileDescriptor.Serializer.toJSON(obj)))\"))")
if index < files.count-1 {
param0Array.appendString(", ")
}
}
param0Array.appendString("]")
let param0 : String = param0Array as String
var callbackId : Int64 = -1
if (getId() != nil) {
callbackId = getId()!
}
AppRegistryBridge.sharedInstance.getPlatformContextWeb().executeJavaScript("Adaptive.handleFileListResultCallbackResult( \(callbackId), \(param0))")
}
/**
On partial result of a file operation, containing a warning.
@param files Array of resulting files/folders.
@param warning Warning condition encountered.
@since v2.0
*/
public func onWarning(files : [FileDescriptor], warning : IFileListResultCallbackWarning) {
let param0Array : NSMutableString = NSMutableString()
param0Array.appendString("[")
for (index,obj) in files.enumerate() {
param0Array.appendString("Adaptive.FileDescriptor.toObject(JSON.parse(\"\(JSONUtil.escapeString(FileDescriptor.Serializer.toJSON(obj)))\"))")
if index < files.count-1 {
param0Array.appendString(", ")
}
}
param0Array.appendString("]")
let param0 : String = param0Array as String
let param1 : String = "Adaptive.IFileListResultCallbackWarning.toObject(JSON.parse(\"{ \\\"value\\\": \\\"\(warning.toString())\\\"}\"))"
var callbackId : Int64 = -1
if (getId() != nil) {
callbackId = getId()!
}
AppRegistryBridge.sharedInstance.getPlatformContextWeb().executeJavaScript("Adaptive.handleFileListResultCallbackWarning( \(callbackId), \(param0), \(param1))")
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
|
apache-2.0
|
390d255f9bb2e855097633c111dc0d64
| 37.708333 | 168 | 0.614424 | 4.793602 | false | false | false | false |
guowilling/iOSExamples
|
Swift/Socket/protobuf-swift-master/Source/AbstractMessage.swift
|
6
|
9031
|
// Protocol Buffers for Swift
//
// Copyright 2014 Alexey Khohklov(AlexeyXo).
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
public typealias ONEOF_NOT_SET = Int
public protocol ProtocolBuffersMessageInit {
}
public enum ProtocolBuffersError: Error {
case obvious(String)
//Streams
case invalidProtocolBuffer(String)
case illegalState(String)
case illegalArgument(String)
case outOfSpace
}
public protocol ProtocolBuffersMessage:ProtocolBuffersMessageInit {
var unknownFields:UnknownFieldSet{get}
func serializedSize() -> Int32
func isInitialized() -> Bool
func writeTo(codedOutputStream:CodedOutputStream) throws
func writeTo(outputStream:OutputStream) throws
func data() throws -> Data
static func classBuilder()-> ProtocolBuffersMessageBuilder
func classBuilder()-> ProtocolBuffersMessageBuilder
//JSON
func encode() throws -> Dictionary<String,Any>
static func decode(jsonMap:Dictionary<String,Any>) throws -> Self
func toJSON() throws -> Data
static func fromJSON(data:Data) throws -> Self
}
public protocol ProtocolBuffersMessageBuilder {
var unknownFields:UnknownFieldSet{get set}
func clear() -> Self
func isInitialized()-> Bool
func build() throws -> AbstractProtocolBuffersMessage
func merge(unknownField:UnknownFieldSet) throws -> Self
func mergeFrom(codedInputStream:CodedInputStream) throws -> Self
func mergeFrom(codedInputStream:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Self
func mergeFrom(data:Data) throws -> Self
func mergeFrom(data:Data, extensionRegistry:ExtensionRegistry) throws -> Self
func mergeFrom(inputStream:InputStream) throws -> Self
func mergeFrom(inputStream:InputStream, extensionRegistry:ExtensionRegistry) throws -> Self
//Delimited Encoding/Decoding
func mergeDelimitedFrom(inputStream:InputStream) throws -> Self?
static func decodeToBuilder(jsonMap:Dictionary<String,Any>) throws -> Self
static func fromJSONToBuilder(data:Data) throws -> Self
}
public func == (lhs: AbstractProtocolBuffersMessage, rhs: AbstractProtocolBuffersMessage) -> Bool {
return lhs.hashValue == rhs.hashValue
}
open class AbstractProtocolBuffersMessage:Hashable, ProtocolBuffersMessage {
public var unknownFields:UnknownFieldSet
required public init() {
unknownFields = UnknownFieldSet(fields: Dictionary())
}
final public func data() -> Data {
let ser_size = serializedSize()
let data = Data(count: Int(ser_size))
let stream:CodedOutputStream = CodedOutputStream(data: data)
do {
try writeTo(codedOutputStream: stream)
}
catch {}
return Data(bytes: stream.buffer.buffer, count: Int(ser_size))
}
open func isInitialized() -> Bool {
return false
}
open func serializedSize() -> Int32 {
return 0
}
open func getDescription(indent:String) throws -> String {
throw ProtocolBuffersError.obvious("Override")
}
open func writeTo(codedOutputStream: CodedOutputStream) throws {
throw ProtocolBuffersError.obvious("Override")
}
final public func writeTo(outputStream: OutputStream) throws {
let codedOutput:CodedOutputStream = CodedOutputStream(stream:outputStream)
try! writeTo(codedOutputStream: codedOutput)
try codedOutput.flush()
}
public func writeDelimitedTo(outputStream: OutputStream) throws {
let serializedDataSize = serializedSize()
let codedOutputStream = CodedOutputStream(stream: outputStream)
try codedOutputStream.writeRawVarint32(value: serializedDataSize)
try writeTo(codedOutputStream: codedOutputStream)
try codedOutputStream.flush()
}
open class func classBuilder() -> ProtocolBuffersMessageBuilder {
return AbstractProtocolBuffersMessageBuilder()
}
open func classBuilder() -> ProtocolBuffersMessageBuilder {
return AbstractProtocolBuffersMessageBuilder()
}
open var hashValue: Int {
get {
return unknownFields.hashValue
}
}
//JSON
open func encode() throws -> Dictionary<String, Any> {
throw ProtocolBuffersError.obvious("JSON Encoding/Decoding available only in syntax=\"proto3\"")
}
open class func decode(jsonMap: Dictionary<String, Any>) throws -> Self {
throw ProtocolBuffersError.obvious("JSON Encoding/Decoding available only in syntax=\"proto3\"")
}
open func toJSON() throws -> Data {
let json = try JSONSerialization.data(withJSONObject: encode(), options: JSONSerialization.WritingOptions(rawValue: 0))
return json
}
open class func fromJSON(data:Data) throws -> Self {
throw ProtocolBuffersError.obvious("JSON Encoding/Decoding available only in syntax=\"proto3\"")
}
}
open class AbstractProtocolBuffersMessageBuilder:ProtocolBuffersMessageBuilder {
open var unknownFields:UnknownFieldSet
public init() {
unknownFields = UnknownFieldSet(fields:Dictionary())
}
open func build() throws -> AbstractProtocolBuffersMessage {
return AbstractProtocolBuffersMessage()
}
open func clone() throws -> Self {
return self
}
open func clear() -> Self {
return self
}
open func isInitialized() -> Bool {
return false
}
@discardableResult
open func mergeFrom(codedInputStream:CodedInputStream) throws -> Self {
return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry())
}
open func mergeFrom(codedInputStream:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Self {
throw ProtocolBuffersError.obvious("Override")
}
@discardableResult
open func merge(unknownField: UnknownFieldSet) throws -> Self {
let merged:UnknownFieldSet = try UnknownFieldSet.builderWithUnknownFields(copyFrom: unknownFields).merge(unknownFields: unknownField).build()
unknownFields = merged
return self
}
@discardableResult
final public func mergeFrom(data:Data) throws -> Self {
let input:CodedInputStream = CodedInputStream(data:data)
_ = try mergeFrom(codedInputStream: input)
try input.checkLastTagWas(value: 0)
return self
}
@discardableResult
final public func mergeFrom(data:Data, extensionRegistry:ExtensionRegistry) throws -> Self {
let input:CodedInputStream = CodedInputStream(data:data)
_ = try mergeFrom(codedInputStream: input, extensionRegistry:extensionRegistry)
try input.checkLastTagWas(value: 0)
return self
}
@discardableResult
final public func mergeFrom(inputStream: InputStream) throws -> Self {
let codedInput:CodedInputStream = CodedInputStream(stream: inputStream)
_ = try mergeFrom(codedInputStream: codedInput)
try codedInput.checkLastTagWas(value: 0)
return self
}
@discardableResult
final public func mergeFrom(inputStream: InputStream, extensionRegistry:ExtensionRegistry) throws -> Self {
let codedInput:CodedInputStream = CodedInputStream(stream: inputStream)
_ = try mergeFrom(codedInputStream: codedInput, extensionRegistry:extensionRegistry)
try codedInput.checkLastTagWas(value: 0)
return self
}
//Delimited Encoding/Decoding
@discardableResult
public func mergeDelimitedFrom(inputStream: InputStream) throws -> Self? {
var firstByte:UInt8 = 0
if inputStream.read(&firstByte, maxLength: 1) != 1 {
return nil
}
let rSize = try CodedInputStream.readRawVarint32(firstByte: firstByte, inputStream: inputStream)
var data = [UInt8](repeating: 0, count: Int(rSize))
_ = inputStream.read(&data, maxLength: Int(rSize))
return try mergeFrom(data: Data(data))
}
//JSON
class open func decodeToBuilder(jsonMap: Dictionary<String, Any>) throws -> Self {
throw ProtocolBuffersError.obvious("JSON Encoding/Decoding available only in syntax=\"proto3\"")
}
open class func fromJSONToBuilder(data: Data) throws -> Self {
throw ProtocolBuffersError.obvious("JSON Encoding/Decoding available only in syntax=\"proto3\"")
}
}
|
mit
|
9a97933b9acacbcff1c0a7ec59c6485d
| 35.415323 | 149 | 0.699922 | 5.250581 | false | false | false | false |
dvlproad/CJUIKit
|
CJBaseUIKit-Swift/UIView/CJPopupAction/UIView+CJPopupInView.swift
|
1
|
19320
|
//
// UIView+CJPopupInView.m
// CJUIKitDemo
//
// Created by ciyouzen on 15/11/12.
// Copyright (c) 2015年 dvlproad. All rights reserved.
//
func CJPopupMainThreadAssert() {
assert(Thread.isMainThread, "UIView+CJPopupInView needs to be accessed on the main thread.");
}
enum CJWindowPosition: NSInteger {
case bottom = 0
case center
}
enum CJAnimationType: NSInteger {
case none = 0 //Directly
case normal //通过设置frame来实现
case CATransform3D
}
typealias CJTapBlankViewCompleteBlock = () -> ()
typealias CJShowPopupViewCompleteBlock = () -> ()
private var kCJPopupAnimationDuration: TimeInterval = 0.3
private var cjPopupAnimationTypeKey: String = "cjPopupAnimationType"
private var cjPopupViewHideFrameStringKey: String = "cjPopupViewHideFrameString"
private var cjPopupViewHideTransformKey: String = "cjPopupViewHideTransform"
private var cjShowInViewKey: String = "cjShowInView"
private var cjTapViewKey: String = "cjTapView"
private var cjShowPopupViewCompleteBlockKey: String = "cjShowPopupViewCompleteBlock"
private var cjTapBlankViewCompleteBlockKey: String = "cjTapBlankViewCompleteBlock"
private var cjPopupViewShowingKey: String = "cjPopupViewShowing"
private var cjMustHideFromPopupViewKey: String = "cjMustHideFromPopupView"
extension UIView {
// MARK: - runtime
/// 弹出视图的动画方式
var cjPopupAnimationType: CJAnimationType {
get {
let animationType = objc_getAssociatedObject(self, &cjPopupAnimationTypeKey)
return animationType as! CJAnimationType
}
set {
objc_setAssociatedObject(self, &cjPopupAnimationTypeKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
}
}
/// 弹出视图隐藏时候的frame
var cjPopupViewHideFrameString: String {
get {
return objc_getAssociatedObject(self, &cjPopupViewHideFrameStringKey) as! String
}
set {
objc_setAssociatedObject(self, &cjPopupViewHideFrameStringKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/*
/// 弹出视图隐藏时候的transform
var cjPopupViewHideTransform: CATransform3D {
get {
return objc_getAssociatedObject(self, &cjPopupViewHideTransformKey) as! CATransform3D
}
set {
objc_setAssociatedObject(self, &cjPopupViewHideTransformKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
*/
/// 弹出视图被add到的view
var cjShowInView: UIView {
get {
return objc_getAssociatedObject(self, &cjShowInViewKey) as! UIView
}
set {
objc_setAssociatedObject(self, &cjShowInViewKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// 空白区域(指radioButtons组合下的点击区域(不包括radioButtons区域),用来点击之后隐藏列表)
var cjTapView: UIView {
get {
return objc_getAssociatedObject(self, &cjTapViewKey) as! UIView
}
set {
objc_setAssociatedObject(self, &cjTapViewKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// 点击空白区域执行的操作
var cjTapBlankViewCompleteBlock: CJTapBlankViewCompleteBlock {
get {
return objc_getAssociatedObject(self, &cjTapBlankViewCompleteBlockKey) as! CJTapBlankViewCompleteBlock
}
set {
objc_setAssociatedObject(self, &cjTapBlankViewCompleteBlockKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC)
}
}
/// 显示弹出视图后的操作
var cjShowPopupViewCompleteBlock: CJShowPopupViewCompleteBlock {
get {
return objc_getAssociatedObject(self, &cjShowPopupViewCompleteBlockKey) as! CJShowPopupViewCompleteBlock
}
set {
objc_setAssociatedObject(self, &cjShowPopupViewCompleteBlockKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC)
}
}
/// 判断当前是否有弹出视图显示
var cjPopupViewShowing: Bool {
get {
let isShowing = objc_getAssociatedObject(self, &cjPopupViewShowingKey)
return isShowing as! Bool
}
set {
objc_setAssociatedObject(self, &cjPopupViewShowingKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
}
}
// MARK: - Event
/**
* 将本View以size大小弹出到showInView视图中location位置
*
* @param popupSuperview 弹出视图的父视图view
* @param popupViewOrigin 弹出视图的左上角origin坐标
* @param popupViewSize 弹出视图的size大小
* @param blankBGColor 空白区域的背景颜色
* @param showPopupViewCompleteBlock 显示弹出视图后的操作
* @param tapBlankViewCompleteBlock 点击空白区域后的操作(要自己执行cj_hidePopupView...来隐藏,因为有时候点击背景是不执行隐藏的)
*/
func cj_popupInView(popupSuperview: UIView,
popupViewOrigin: CGPoint,
popupViewSize: CGSize,
blankBGColor: UIColor,
showPopupViewCompleteBlock: @escaping CJShowPopupViewCompleteBlock,
tapBlankViewCompleteBlock: @escaping CJTapBlankViewCompleteBlock)
{
CJPopupMainThreadAssert();
let popupView: UIView = self
let canAdd: Bool = self.letPopupSuperview(popupSuperview: popupSuperview, popupView: popupView, blankBGColor: blankBGColor)
if !canAdd {
return
}
let blankView: UIView = self.cjTapView
let blankViewX: CGFloat = popupViewOrigin.x
let blankViewY: CGFloat = popupViewOrigin.y
let blankViewWidth: CGFloat = popupViewSize.width
let blankViewHeight: CGFloat = popupSuperview.frame.height-popupViewOrigin.y
let blankViewFrame: CGRect = CGRect(x: blankViewX, y: blankViewY, width: blankViewWidth, height: blankViewHeight)
blankView.frame = blankViewFrame
self.cjPopupAnimationType = .normal
self.cjShowPopupViewCompleteBlock = showPopupViewCompleteBlock
self.cjTapBlankViewCompleteBlock = tapBlankViewCompleteBlock
let popupViewX: CGFloat = popupViewOrigin.x
let popupViewY: CGFloat = popupViewOrigin.y
let popupViewWidth: CGFloat = popupViewSize.width
let popupViewShowHeight: CGFloat = popupViewSize.height
let popupViewHideHeight: CGFloat = 0
let popupViewShowFrame: CGRect = CGRect(x: popupViewX, y: popupViewY, width: popupViewWidth, height: popupViewShowHeight)
let popupViewHideFrame: CGRect = CGRect(x: popupViewX, y: popupViewY, width: popupViewWidth, height: popupViewHideHeight)
self.cjPopupViewHideFrameString = NSCoder.string(for: popupViewHideFrame)
//动画设置位置
blankView.alpha = 0.2
popupView.alpha = 0.2
popupView.frame = popupViewHideFrame
UIView.animate(withDuration: kCJPopupAnimationDuration, animations: { blankView.alpha = 1.0
popupView.alpha = 1.0
popupView.frame = popupViewShowFrame
})
showPopupViewCompleteBlock()
}
/**
* 将popupView添加进keyWindow中(会默认添加进blankView及对popupView做一些默认设置)
*
* @param popupView 要被添加的视图
* @param blankBGColor 空白区域的背景颜色
*
* @return 是否可以被添加成功
*/
func letkeyWindowAddPopupView(popupView: UIView, blankBGColor: UIColor) -> Bool {
let keyWindow: UIWindow = UIApplication.shared.keyWindow!
let canAdd: Bool = self.letPopupSuperview(popupSuperview: keyWindow, popupView: popupView, blankBGColor: blankBGColor)
if !canAdd {
return false
}
/* 设置blankView的位置 */
let blankView: UIView = self.cjTapView
let blankViewX: CGFloat = 0
let blankViewY: CGFloat = 0
let blankViewWidth: CGFloat = keyWindow.frame.width
let blankViewHeight: CGFloat = keyWindow.frame.height
let blankViewFrame: CGRect = CGRect(x: blankViewX, y: blankViewY, width: blankViewWidth, height: blankViewHeight)
blankView.frame = blankViewFrame
/* 对popupView做一些默认设置 */
popupView.layer.shadowColor = UIColor.black.cgColor
popupView.layer.shadowOffset = CGSize(width: 0, height: -2)
popupView.layer.shadowRadius = 5.0
popupView.layer.shadowOpacity = 0.8
return true
}
/**
* 将popupView添加进popupSuperview中(会默认添加进blankView及对popupView做一些默认设置)
*
* @param popupSuperview 被添加到的地方
* @param popupView 要被添加的视图
* @param blankBGColor 空白区域的背景颜色
*
* @return 是否可以被添加成功
*/
func letPopupSuperview(popupSuperview: UIView, popupView: UIView, blankBGColor: UIColor?) -> Bool {
if popupSuperview.subviews.contains(popupView) {
return false
}
/* 添加进空白的点击区域blankView */
var blankView: UIView? = self.cjTapView
if blankView == nil {
blankView = UIView(frame: CGRect.zero)
if blankBGColor == nil {
blankView!.backgroundColor = UIColor(red: 0.16, green: 0.17, blue: 0.21, alpha: 0.6)
} else {
blankView!.backgroundColor = blankBGColor
}
let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(cj_TapBlankViewAction(tap:)))
blankView!.addGestureRecognizer(tapGesture)
self.cjTapView = blankView!
}
if self.cjPopupViewShowing {
//如果存在,先清除
blankView!.removeFromSuperview()
}
popupSuperview.addSubview(blankView!)
/* 添加进popupView,并做一些默认设置 */
if self.cjPopupViewShowing {
//如果存在,先清除
popupView.removeFromSuperview()
}
popupSuperview.addSubview(popupView)
self.cjShowInView = popupSuperview
self.cjPopupViewShowing = true
return true
}
/// 点击空白区域的事件
@objc func cj_TapBlankViewAction(tap: UITapGestureRecognizer) {
self.cjTapBlankViewCompleteBlock()
}
/**
* 将当前视图弹出到window中央
*
* @param animationType 弹出时候的动画采用的类型
* @param popupViewSize 弹出视图的大小
* @param blankBGColor 空白区域的背景颜色
* @param showPopupViewCompleteBlock 显示弹出视图后的操作
* @param tapBlankViewCompleteBlock 点击空白区域后的操作(要自己执行cj_hidePopupView...来隐藏,因为有时候点击背景是不执行隐藏的)
*/
func cj_popupInCenterWindow(animationType: CJAnimationType,
popupViewSize: CGSize,
blankBGColor: UIColor,
showPopupViewCompleteBlock: CJShowPopupViewCompleteBlock!,
tapBlankViewCompleteBlock: CJTapBlankViewCompleteBlock!)
{
CJPopupMainThreadAssert()
let keyWindow: UIWindow = UIApplication.shared.keyWindow!
let popupView: UIView = self
let popupSuperview: UIView = keyWindow
assert(popupViewSize.width != 0 && popupViewSize.height != 0, "弹出视图的宽高都不能为0")
var frame: CGRect = popupView.frame
frame.size.width = popupViewSize.width
frame.size.height = popupViewSize.height
popupView.frame = frame
let canAdd: Bool = self.letkeyWindowAddPopupView(popupView: popupView, blankBGColor: blankBGColor)
if !canAdd {
return
}
self.cjPopupAnimationType = animationType
self.cjShowPopupViewCompleteBlock = showPopupViewCompleteBlock
self.cjTapBlankViewCompleteBlock = tapBlankViewCompleteBlock
popupView.center = popupSuperview.center
if animationType == .none {
} else if animationType == .normal {
} else if animationType == .CATransform3D {
let popupViewShowTransform: CATransform3D = CATransform3DIdentity;
let rotate: CATransform3D = CATransform3DMakeRotation(CGFloat(70.0*Double.pi/180.0), 0.0, 0.0, 1.0);
let translate: CATransform3D = CATransform3DMakeTranslation(20.0, -500.0, 0.0);
let popupViewHideTransform: CATransform3D = CATransform3DConcat(rotate, translate);
self.layer.transform = popupViewHideTransform
UIView.animate(withDuration: kCJPopupAnimationDuration, delay: 0.0, options: .curveEaseOut, animations: {
self.layer.transform = popupViewShowTransform
})
}
showPopupViewCompleteBlock()
}
/**
* 将当前视图弹出到window底部
*
* @param animationType 弹出时候的动画采用的类型
* @param popupViewHeight 弹出视图的高度
* @param blankBGColor 空白区域的背景颜色
* @param showPopupViewCompleteBlock 显示弹出视图后的操作
* @param tapBlankViewCompleteBlock 点击空白区域后的操作(要自己执行cj_hidePopupView...来隐藏,因为有时候点击背景是不执行隐藏的)
*/
func cj_popupInBottomWindow(animationType: CJAnimationType,
popupViewHeight: CGFloat,
blankBGColor: UIColor,
showPopupViewCompleteBlock: @escaping CJShowPopupViewCompleteBlock,
tapBlankViewCompleteBlock: @escaping CJTapBlankViewCompleteBlock)
{
CJPopupMainThreadAssert()
assert(popupViewHeight != 0, "弹出视图的高都不能为0")
let keyWindow: UIWindow = UIApplication.shared.keyWindow!
let popupViewWidth: CGFloat = keyWindow.frame.width
let popupViewSize: CGSize = CGSize(width: popupViewWidth, height: popupViewHeight)
if self.frame.size.equalTo(popupViewSize) {
print("Warning:popupView视图大小将自动调整为指定的弹出视图大小")
var selfFrame: CGRect = self.frame
selfFrame.size = popupViewSize
self.frame = selfFrame
}
let popupView: UIView = self
let canAdd: Bool = self.letkeyWindowAddPopupView(popupView: popupView, blankBGColor: blankBGColor)
if !canAdd {
return
}
self.cjPopupAnimationType = animationType
self.cjShowPopupViewCompleteBlock = showPopupViewCompleteBlock
self.cjTapBlankViewCompleteBlock = tapBlankViewCompleteBlock
//popupViewShowFrame
let popupViewX: CGFloat = 0
let popupViewShowY: CGFloat = keyWindow.frame.height-popupViewHeight
var popupViewShowFrame: CGRect = CGRect.zero
popupViewShowFrame = CGRect(x: popupViewX, y: popupViewShowY, width: popupViewWidth, height: popupViewHeight)
if animationType == .none {
popupView.frame = popupViewShowFrame
} else if animationType == .normal {
//popupViewHideFrame
var popupViewHideFrame: CGRect = popupViewShowFrame
popupViewHideFrame.origin.y = keyWindow.frame.maxY
self.cjPopupViewHideFrameString = NSCoder.string(for: popupViewHideFrame)
//动画设置位置
let blankView: UIView = self.cjTapView
blankView.alpha = 0.2
popupView.alpha = 0.2
popupView.frame = popupViewHideFrame
UIView.animate(withDuration: kCJPopupAnimationDuration, animations: { blankView.alpha = 1.0
popupView.alpha = 1.0
popupView.frame = popupViewShowFrame
})
} else if animationType == .CATransform3D {
popupView.frame = popupViewShowFrame
let popupViewShowTransform: CATransform3D = CATransform3DIdentity;
let rotate: CATransform3D = CATransform3DMakeRotation(CGFloat(70.0*Double.pi/180.0), 0.0, 0.0, 1.0);
let translate: CATransform3D = CATransform3DMakeTranslation(20.0, -500.0, 0.0);
let popupViewHideTransform: CATransform3D = CATransform3DConcat(rotate, translate);
self.layer.transform = popupViewHideTransform
UIView.animate(withDuration: kCJPopupAnimationDuration, delay: 0.0, options: .curveEaseOut, animations: {
self.layer.transform = popupViewShowTransform
})
}
showPopupViewCompleteBlock()
}
/// 隐藏弹出视图
func cj_hidePopupView() {
let animationType: CJAnimationType = self.cjPopupAnimationType
self.cj_hidePopupView(animationType)
}
/**
* 隐藏弹出视图
*
* @param animationType 弹出时候的动画采用的类型
*/
func cj_hidePopupView(_ animationType: CJAnimationType) {
CJPopupMainThreadAssert();
self.cjPopupViewShowing = false
//设置成NO表示当前未显示任何弹出视图
self.endEditing(true)
let popupView: UIView = self
let tapView: UIView = self.cjTapView
switch animationType {
case .none:
popupView.removeFromSuperview()
tapView.removeFromSuperview()
break
case .normal:
var popupViewHideFrame: CGRect = NSCoder.cgRect(for: self.cjPopupViewHideFrameString)
if popupViewHideFrame.equalTo(CGRect.zero) {
popupViewHideFrame = self.frame
}
UIView.animate(withDuration: kCJPopupAnimationDuration, animations: { //要设置成0,不设置非零值如0.2,是为了防止在显示出来的时候,在0.3秒内很快按两次按钮,仍有view存在
tapView.alpha = 0.0
popupView.alpha = 0.0
popupView.frame = popupViewHideFrame
})
break
case .CATransform3D:
UIView.animate(withDuration: kCJPopupAnimationDuration, delay: 0.0, options: .curveEaseIn, animations: {
let rotate: CATransform3D = CATransform3DMakeRotation(CGFloat(-70.0 * Double.pi / 180.0), 0.0, 0.0, 1.0);
let translate: CATransform3D = CATransform3DMakeTranslation(-20.0, 500.0, 0.0);
popupView.layer.transform = CATransform3DConcat(rotate, translate)
})
break
}
}
}
|
mit
|
eb2ad450f8c06b0667e43eb967658634
| 39.097996 | 142 | 0.638358 | 4.545317 | false | false | false | false |
zimcherDev/ios
|
Zimcher/UIKit Objects/UI Helpers/EntryField/EntryField.swift
|
1
|
3693
|
//
// TableViwWithIntrinsicSize.swift
// Zimcher
//
// Created by Weiyu Huang on 12/3/15.
// Copyright © 2015 Zimcher. All rights reserved.
//
import UIKit
class TableViewWithIntrinsicSize: UITableView {
override func reloadData() {
invalidateIntrinsicContentSize()
super.reloadData()
}
override func intrinsicContentSize() -> CGSize {
layoutIfNeeded()
return CGSize(width: UIViewNoIntrinsicMetric, height: contentSize.height)
}
}
class EntryField: NSObject, UITableViewDelegate, UITableViewDataSource {
unowned let tableView: TableViewWithIntrinsicSize
var headerFooterHeight = CGFloat(0) { didSet { tableView.reloadData() } }
var headerFooterColor = UIColor.clearColor() { didSet { tableView.reloadData() }}
var datasource = [EntryFieldData]()
init(tableView: TableViewWithIntrinsicSize)
{
self.tableView = tableView
super.init()
tableView.delegate = self
tableView.dataSource = self
tableView.scrollEnabled = false
tableView.separatorStyle = .None
//dynamic cell height
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 69
}
func feedData(data: [EntryFieldData])
{
datasource = data
data.forEach(registerCell)
tableView.reloadData()
tableView.layoutIfNeeded()
tableView.reloadData()
tableView.updateConstraintsIfNeeded()
//Don't know why but it works
}
func onSubmitCallback() -> Bool
//stub
{
return datasource.flatMap { $0 as? HasOnSubmitCallback }
.filter{ $0.cell is TextEntryCell
} // STUB
.reduce(true) { result, i in
result ? i.onSubmitCallback?((i.cell as! TextEntryCell).textInput) ?? true : false }
}
private func registerCell(data: EntryFieldData)
{
let reuseID = data.dynamicType.cellReuseIdentifier
switch data.dynamicType.cellType {
case .Class(let c):
tableView.registerClass(c, forCellReuseIdentifier: reuseID)
case .NibName(let s):
tableView.registerNib(UINib(nibName: s, bundle: nil), forCellReuseIdentifier: reuseID)
}
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return headerFooterHeight
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return headerFooterHeight
}
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let v = UIView()
v.backgroundColor = headerFooterColor
return v
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return self.tableView(tableView, viewForFooterInSection: section)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datasource.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let type = (datasource[indexPath.row]).dynamicType
let cell = tableView.dequeueReusableCellWithIdentifier(type.cellReuseIdentifier, forIndexPath: indexPath) as! BaseEntryCell
datasource[indexPath.row].configureCell(cell)
cell.hasSeparator = !isLast(indexPath)
return cell
}
private func isLast(indexPath: NSIndexPath) -> Bool
{
return datasource.count - 1 == indexPath.row
}
}
|
apache-2.0
|
7848f312641cd092d04df97c527fb35e
| 30.033613 | 131 | 0.650867 | 5.31223 | false | false | false | false |
Vayne-Lover/Swift-Filter
|
Amplitude Limiting Filter.playground/Contents.swift
|
1
|
1109
|
import UIKit
//Setting Start
import UIKit
func getTestValueUInt16()->UInt16{
return UInt16(arc4random_uniform(255))
}
func getTestValueInt()->Int{
return Int(arc4random_uniform(255))
}
//Setting End
//Double Extension Start
extension Double{//If you want to format you can use the extension.
func format(f:String) -> String {
return NSString(format: "%\(f)f",self) as String
}
}
//Double Extension End
//Extension Example Start
//print(Double(3.1415).format(".2"))//There is the example to format Double
//Extension Example End
//Amplitude Limiting Filter
//Filter1 Start
let A=UInt16(10)
var Value1:UInt16=128//You should chose middle of the value
func filter1(inout Value1:UInt16)->Double{
let value=getTestValueUInt16()
//Value1 - value>=A//Take care.The type is UInt16,if false there will be error
if Value1>value{
if Value1 - value>A {
Value1=value}
} else {
if value - Value1>A {
Value1=value}
}
return Double(Value1)
}
//Filter1 End
//Filter1 Test Start
print(filter1(&Value1).format(".2"))
//Filter1 Test End
|
mit
|
ca08f12e7a9e93990cf886ac6e1b46ea
| 26 | 82 | 0.68654 | 3.503165 | false | true | false | false |
andykkt/BFWControls
|
BFWControls/Modules/Styled/Model/NSAttributedString+TextAttributes.swift
|
1
|
1691
|
//
// NSAttributedString+TextAttributes.swift
// BFWControls
//
// Created by Tom Brodhurst-Hill on 1/5/18.
// Copyright © 2018 BareFeetWare. All rights reserved.
// Free to use and modify, without warranty.
//
import Foundation
public extension NSAttributedString {
public func keepingTraitsAndColorButAdding(attributes: TextAttributes) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: string, attributes: attributes)
enumerateAttributes(in: NSRange(location: 0, length: length), options: [])
{ (attributes, range, stop) in
if let color = attributes[NSAttributedStringKey.foregroundColor] as? UIColor,
![UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1), .black].contains(color)
{
attributedString.addAttributes([NSAttributedStringKey.foregroundColor : color], range: range)
}
if let font = attributes[NSAttributedStringKey.font] as? UIFont,
!font.fontDescriptor.symbolicTraits.isEmpty,
let oldFont = attributedString.attribute(NSAttributedStringKey.font,
at: range.location,
longestEffectiveRange: nil,
in: range) as? UIFont
{
let newFont = oldFont.addingSymbolicTraits(font.fontDescriptor.symbolicTraits)
attributedString.addAttributes([NSAttributedStringKey.font : newFont], range: range)
}
}
return NSAttributedString(attributedString: attributedString)
}
}
|
mit
|
d849c92edc5f03a9faef7cbc2f5d2e54
| 47.285714 | 109 | 0.611243 | 5.596026 | false | false | false | false |
stanliski/iOS-SDK
|
Examples/nearables/MonitoringExample-Swift/MonitoringExample-Swift/AppDelegate.swift
|
10
|
3094
|
//
// AppDelegate.swift
// MonitoringExample-Swift
//
// Created by Marcin Klimek on 09/01/15.
// Copyright (c) 2015 Estimote. 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.
UINavigationBar.appearance().barTintColor = UIColor(red: 0.490, green: 0.631, blue: 0.549, alpha: 1.000)
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().titleTextAttributes = NSDictionary(objects: [UIColor.whiteColor(), UIFont.systemFontOfSize(18.0)], forKeys: [NSForegroundColorAttributeName, NSFontAttributeName])
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent;
if(UIApplication.sharedApplication().respondsToSelector(Selector("registerUserNotificationSettings:")))
{
var settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
}
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
|
ba6872a2b349494d5e6b3ce95c8af194
| 50.566667 | 285 | 0.748546 | 5.826742 | false | false | false | false |
tinrobots/CoreDataPlus
|
Tests/Resources/SampleModel2/Entities/Page.swift
|
1
|
847
|
// CoreDataPlus
import CoreData
// MARK: - V1
@objc(Page)
public class Page: NSManagedObject {
@NSManaged public var number: Int32
@NSManaged public var isBookmarked: Bool
@NSManaged public var content: Content?
@NSManaged public var book: Book
var isEmpty: Bool { content == .none }
}
// MARK: - V2
@objc(PageV2)
public class PageV2: NSManagedObject {
@NSManaged public var number: Int32
@NSManaged public var isBookmarked: Bool
@NSManaged public var content: Content?
@NSManaged public var book: BookV2
var isEmpty: Bool { content == .none }
}
// MARK: - V3
@objc(PageV3)
public class PageV3: NSManagedObject {
@NSManaged public var number: Int32
@NSManaged public var isBookmarked: Bool
@NSManaged public var content: Content?
@NSManaged public var book: BookV3
var isEmpty: Bool { content == .none }
}
|
mit
|
b20963f23a55d3a9dae2193c3c35b9ec
| 20.175 | 42 | 0.717828 | 3.731278 | false | false | false | false |
1170197998/SinaWeibo
|
SFWeiBo/SFWeiBo/Classes/Home/Compose/EmoticonView/UITextView+Category.swift
|
1
|
2647
|
//
// UITextView+Category.swift
// 表情键盘界面布局
//
// Created by mac on 15/9/16.
// Copyright © 2015年 ShaoFeng. All rights reserved.
//
import UIKit
extension UITextView
{
func insertEmoticon(emoticon: Emoticon)
{
// 0.处理删除按钮
if emoticon.isRemoveButton
{
deleteBackward()
}
// 1.判断当前点击的是否是emoji表情
if emoticon.emojiStr != nil{
self.replaceRange(self.selectedTextRange!, withText: emoticon.emojiStr!)
}
// 2.判断当前点击的是否是表情图片
if emoticon.png != nil{
// print("font = \(font)")
// 1.创建表情字符串
let imageText = EmoticonTextAttachment.imageText(emoticon, font: font ?? UIFont.systemFontOfSize(17))
// 3.拿到当前所有的内容
let strM = NSMutableAttributedString(attributedString: self.attributedText)
// 4.插入表情到当前光标所在的位置
let range = self.selectedRange
strM.replaceCharactersInRange(range, withAttributedString: imageText)
// 属性字符串有自己默认的尺寸
strM.addAttribute(NSFontAttributeName, value: font! , range: NSMakeRange(range.location, 1))
// 5.将替换后的字符串赋值给UITextView
self.attributedText = strM
// 恢复光标所在的位置
// 两个参数: 第一个是指定光标所在的位置, 第二个参数是选中文本的个数
self.selectedRange = NSMakeRange(range.location + 1, 0)
// 6.自己主动促发textViewDidChange方法
delegate?.textViewDidChange!(self)
}
}
/**
获取需要发送给服务器的字符串
*/
func emoticonAttributedText() -> String
{
var strM = String()
// 后去需要发送给服务器的数据
attributedText.enumerateAttributesInRange( NSMakeRange(0, attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (objc, range, _) -> Void in
if objc["NSAttachment"] != nil
{
// 图片
let attachment = objc["NSAttachment"] as! EmoticonTextAttachment
strM += attachment.chs!
}else
{
// 文字
strM += (self.text as NSString).substringWithRange(range)
}
}
return strM
}
}
|
apache-2.0
|
4248b8ed2db70f4bb2466fd6d4c93d98
| 28.5 | 179 | 0.54087 | 4.91453 | false | false | false | false |
ZackKingS/Tasks
|
task/Classes/Others/Lib/LLCycleScrollView/LLFilledPageControl.swift
|
3
|
5546
|
//
// LLFilledPageControl.swift
// LL 使用备注
// https://github.com/popwarsweet/PageControls
//
// Created by Kyle Zaragoza on 8/6/16.
// Copyright © 2016 Kyle Zaragoza. All rights reserved.
//
import UIKit
open class LLFilledPageControl: UIView {
// MARK: - PageControl
open var pageCount: Int = 0 {
didSet {
updateNumberOfPages(pageCount)
}
}
open var progress: CGFloat = 0 {
didSet {
updateActivePageIndicatorMasks(forProgress: progress)
}
}
open var currentPage: Int {
return Int(round(progress))
}
// MARK: - Appearance
override open var tintColor: UIColor! {
didSet {
inactiveLayers.forEach() { $0.backgroundColor = tintColor.cgColor }
}
}
open var inactiveRingWidth: CGFloat = 1 {
didSet {
updateActivePageIndicatorMasks(forProgress: progress)
}
}
open var indicatorPadding: CGFloat = 8 {
didSet {
layoutPageIndicators(inactiveLayers)
}
}
open var indicatorRadius: CGFloat = 4 {
didSet {
layoutPageIndicators(inactiveLayers)
}
}
fileprivate var indicatorDiameter: CGFloat {
return indicatorRadius * 2
}
fileprivate var inactiveLayers = [CALayer]()
override public init(frame: CGRect) {
super.init(frame: frame)
pageCount = 0
progress = 0
inactiveRingWidth = 1
indicatorPadding = 8
indicatorRadius = 4
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - State Update
fileprivate func updateNumberOfPages(_ count: Int) {
// no need to update
guard count != inactiveLayers.count else { return }
// reset current layout
inactiveLayers.forEach() { $0.removeFromSuperlayer() }
inactiveLayers = [CALayer]()
// add layers for new page count
inactiveLayers = stride(from: 0, to:count, by:1).map() { _ in
let layer = CALayer()
layer.backgroundColor = self.tintColor.cgColor
self.layer.addSublayer(layer)
return layer
}
layoutPageIndicators(inactiveLayers)
updateActivePageIndicatorMasks(forProgress: progress)
self.invalidateIntrinsicContentSize()
}
// MARK: - Layout
fileprivate func updateActivePageIndicatorMasks(forProgress progress: CGFloat) {
// ignore if progress is outside of page indicators' bounds
guard progress >= 0 && progress <= CGFloat(pageCount - 1) else { return }
// mask rect w/ default stroke width
let insetRect = CGRect(x: 0, y: 0, width: indicatorDiameter, height: indicatorDiameter).insetBy(dx: inactiveRingWidth, dy: inactiveRingWidth)
let leftPageFloat = trunc(progress)
let leftPageInt = Int(progress)
// inset right moving page indicator
let spaceToMove = insetRect.width / 2
let percentPastLeftIndicator = progress - leftPageFloat
let additionalSpaceToInsetRight = spaceToMove * percentPastLeftIndicator
let closestRightInsetRect = insetRect.insetBy(dx: additionalSpaceToInsetRight, dy: additionalSpaceToInsetRight)
// inset left moving page indicator
let additionalSpaceToInsetLeft = (1 - percentPastLeftIndicator) * spaceToMove
let closestLeftInsetRect = insetRect.insetBy(dx: additionalSpaceToInsetLeft, dy: additionalSpaceToInsetLeft)
// adjust masks
for (idx, layer) in inactiveLayers.enumerated() {
let maskLayer = CAShapeLayer()
maskLayer.fillRule = kCAFillRuleEvenOdd
let boundsPath = UIBezierPath(rect: layer.bounds)
let circlePath: UIBezierPath
if leftPageInt == idx {
circlePath = UIBezierPath(ovalIn: closestLeftInsetRect)
} else if leftPageInt + 1 == idx {
circlePath = UIBezierPath(ovalIn: closestRightInsetRect)
} else {
circlePath = UIBezierPath(ovalIn: insetRect)
}
boundsPath.append(circlePath)
maskLayer.path = boundsPath.cgPath
layer.mask = maskLayer
}
}
fileprivate func layoutPageIndicators(_ layers: [CALayer]) {
let layerDiameter = indicatorRadius * 2
var layerFrame = CGRect(x: 0, y: 0, width: layerDiameter, height: layerDiameter)
layers.forEach() { layer in
layer.cornerRadius = self.indicatorRadius
layer.frame = layerFrame
layerFrame.origin.x += layerDiameter + indicatorPadding
}
// 布局
let oldFrame = self.frame
let width = CGFloat(inactiveLayers.count) * layerDiameter + CGFloat(inactiveLayers.count - 1) * indicatorPadding
self.frame = CGRect.init(x: UIScreen.main.bounds.width / 2 - width / 2, y: oldFrame.origin.y, width: width, height: oldFrame.size.height)
}
override open var intrinsicContentSize: CGSize {
return sizeThatFits(CGSize.zero)
}
override open func sizeThatFits(_ size: CGSize) -> CGSize {
let layerDiameter = indicatorRadius * 2
return CGSize(width: CGFloat(inactiveLayers.count) * layerDiameter + CGFloat(inactiveLayers.count - 1) * indicatorPadding,
height: layerDiameter)
}
}
|
apache-2.0
|
477c3a97798767dac2df39fa0fb3213f
| 33.798742 | 149 | 0.621905 | 5.108957 | false | false | false | false |
OscarSwanros/swift
|
test/Prototypes/PatternMatching.swift
|
3
|
12831
|
//===--- PatternMatching.swift --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
//===--- Niceties ---------------------------------------------------------===//
extension Collection {
func index(_ d: IndexDistance) -> Index {
return index(startIndex, offsetBy: d)
}
func offset(of i: Index) -> IndexDistance {
return distance(from: startIndex, to: i)
}
}
//===--- Niceties ---------------------------------------------------------===//
enum MatchResult<Index: Comparable, MatchData> {
case found(end: Index, data: MatchData)
case notFound(resumeAt: Index?)
}
protocol Pattern {
associatedtype Element : Equatable
associatedtype Index : Comparable
associatedtype MatchData = ()
func matched<C: Collection>(atStartOf c: C) -> MatchResult<Index, MatchData>
where C.Index == Index, C.Element == Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection
}
extension Pattern {
func found<C: Collection>(in c: C) -> (extent: Range<Index>, data: MatchData)?
where C.Index == Index, C.Element == Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection
{
var i = c.startIndex
while i != c.endIndex {
let m = self.matched(atStartOf: c[i..<c.endIndex])
switch m {
case .found(let end, let data):
return (extent: i..<end, data: data)
case .notFound(let j):
i = j ?? c.index(after: i)
}
}
return nil
}
}
// FIXME: Using this matcher for found(in:) has worst-case performance
// O(pattern.count * c.count).
//
// Also implement one or more of
// KMP/Boyer-Moore[-Galil]/Sustik-Moore/Z-algorithm which run in O(pattern.count
// + c.count)
struct LiteralMatch<T: Collection, Index: Comparable> : Pattern
where T.Element : Equatable {
typealias Element = T.Element
init(_ pattern: T) { self.pattern = pattern }
func matched<C: Collection>(atStartOf c: C) -> MatchResult<Index, ()>
where C.Index == Index, C.Element == Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection
{
var i = c.startIndex
for p in pattern {
if i == c.endIndex || c[i] != p {
return .notFound(resumeAt: nil)
}
i = c.index(after: i)
}
return .found(end: i, data: ())
}
fileprivate let pattern: T
}
struct MatchAnyOne<T : Equatable, Index : Comparable> : Pattern {
typealias Element = T
func matched<C: Collection>(atStartOf c: C) -> MatchResult<Index, ()>
where C.Index == Index, C.Element == Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection
{
return c.isEmpty
? .notFound(resumeAt: c.endIndex)
: .found(end: c.index(after: c.startIndex), data: ())
}
}
extension MatchAnyOne : CustomStringConvertible {
var description: String { return "." }
}
enum MatchAny {}
var __ : MatchAny.Type { return MatchAny.self }
prefix func % <
T : Equatable, Index : Comparable
>(_: MatchAny.Type) -> MatchAnyOne<T,Index> {
return MatchAnyOne()
}
/// A matcher for two other matchers in sequence.
struct ConsecutiveMatches<M0: Pattern, M1: Pattern> : Pattern
where M0.Element == M1.Element, M0.Index == M1.Index {
init(_ m0: M0, _ m1: M1) { self.matchers = (m0, m1) }
fileprivate let matchers: (M0, M1)
typealias Element = M0.Element
typealias Index = M0.Index
typealias MatchData = (midPoint: M0.Index, data: (M0.MatchData, M1.MatchData))
func matched<C: Collection>(atStartOf c: C) -> MatchResult<Index, MatchData>
where C.Index == Index, C.Element == Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection
{
var src0 = c[c.startIndex..<c.endIndex]
while true {
switch matchers.0.matched(atStartOf: src0) {
case .found(let end0, let data0):
switch matchers.1.matched(atStartOf: c[end0..<c.endIndex]) {
case .found(let end1, let data1):
return .found(end: end1, data: (midPoint: end0, data: (data0, data1)))
case .notFound(_):
if src0.isEmpty {
// I don't think we can know anything interesting about where to
// begin searching again, because there's no communication between
// the two matchers that would allow it.
return .notFound(resumeAt: nil)
}
// backtrack
src0 = src0.dropLast()
}
case .notFound(let j):
return .notFound(resumeAt: j)
}
}
}
}
extension ConsecutiveMatches : CustomStringConvertible {
var description: String { return "(\(matchers.0))(\(matchers.1))" }
}
struct RepeatMatch<M0: Pattern> : Pattern {
typealias Element = M0.Element
typealias MatchData = [(end: M0.Index, data: M0.MatchData)]
let singlePattern: M0
var repeatLimits: ClosedRange<Int>
func matched<C: Collection>(atStartOf c: C) -> MatchResult<M0.Index, MatchData>
where C.Index == M0.Index, C.Element == M0.Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection
{
var lastEnd = c.startIndex
var rest = c.dropFirst(0)
var data: MatchData = []
searchLoop:
while !rest.isEmpty {
switch singlePattern.matched(atStartOf: rest) {
case .found(let x):
data.append(x)
lastEnd = x.end
if data.count == repeatLimits.upperBound { break }
rest = rest[x.end..<rest.endIndex]
case .notFound(let r):
if !repeatLimits.contains(data.count) {
return .notFound(resumeAt: r)
}
break searchLoop
}
}
return .found(end: lastEnd, data: data)
}
}
extension RepeatMatch : CustomStringConvertible {
var description: String {
let suffix: String
switch (repeatLimits.lowerBound, repeatLimits.upperBound) {
case (0, Int.max):
suffix = "*"
case (1, Int.max):
suffix = "+"
case (let l, Int.max):
suffix = "{\(l)...}"
default:
suffix = "\(repeatLimits)"
}
return "(\(singlePattern))\(suffix)"
}
}
enum OneOf<A, B> {
case a(A)
case b(B)
}
extension OneOf : CustomStringConvertible {
var description: String {
switch self {
case .a(let x):
return "\(x)"
case .b(let x):
return "\(x)"
}
}
}
struct MatchOneOf<M0: Pattern, M1: Pattern> : Pattern
where M0.Element == M1.Element, M0.Index == M1.Index {
init(_ m0: M0, _ m1: M1) { self.matchers = (m0, m1) }
fileprivate let matchers: (M0, M1)
typealias Element = M0.Element
typealias Index = M0.Index
typealias MatchData = OneOf<M0.MatchData,M1.MatchData>
func matched<C: Collection>(atStartOf c: C) -> MatchResult<Index, MatchData>
where C.Index == Index, C.Element == Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection
{
switch matchers.0.matched(atStartOf: c) {
case .found(let end, let data):
return .found(end: end, data: .a(data))
case .notFound(let r0):
switch matchers.1.matched(atStartOf: c) {
case .found(let end, let data):
return .found(end: end, data: .b(data))
case .notFound(let r1):
if let s0 = r0, let s1 = r1 {
return .notFound(resumeAt: min(s0, s1))
}
return .notFound(resumeAt: nil)
}
}
}
}
extension MatchOneOf : CustomStringConvertible {
var description: String { return "\(matchers.0)|\(matchers.1)" }
}
infix operator .. : AdditionPrecedence
postfix operator *
postfix operator +
func .. <M0: Pattern, M1: Pattern>(m0: M0, m1: M1) -> ConsecutiveMatches<M0,M1> {
return ConsecutiveMatches(m0, m1)
}
postfix func * <M: Pattern>(m: M) -> RepeatMatch<M> {
return RepeatMatch(singlePattern: m, repeatLimits: 0...Int.max)
}
postfix func + <M: Pattern>(m: M) -> RepeatMatch<M> {
return RepeatMatch(singlePattern: m, repeatLimits: 1...Int.max)
}
func | <M0: Pattern, M1: Pattern>(m0: M0, m1: M1) -> MatchOneOf<M0,M1> {
return MatchOneOf(m0, m1)
}
//===--- Just for testing -------------------------------------------------===//
struct MatchStaticString : Pattern {
typealias Element = UTF8.CodeUnit
typealias Buffer = UnsafeBufferPointer<Element>
typealias Index = Buffer.Index
let content: StaticString
init(_ x: StaticString) { content = x }
func matched<C: Collection>(atStartOf c: C) -> MatchResult<Index, ()>
where C.Index == Index, C.Element == Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection
{
return content.withUTF8Buffer {
LiteralMatch<Buffer, Index>($0).matched(atStartOf: c)
}
}
}
extension MatchStaticString : CustomStringConvertible {
var description: String { return String(describing: content) }
}
// A way to force string literals to be interpreted as StaticString
prefix operator %
extension StaticString {
static prefix func %(x: StaticString) -> MatchStaticString {
return MatchStaticString(x)
}
}
extension Collection where Iterator.Element == UTF8.CodeUnit {
var u8str : String {
var a = Array<UTF8.CodeUnit>()
a.reserveCapacity(numericCast(count) + 1)
a.append(contentsOf: self)
a.append(0)
return String(reflecting: String(cString: a))
}
}
extension Pattern where Element == UTF8.CodeUnit {
func searchTest<C: Collection>(
in c: C,
format: (MatchData)->String = { String(reflecting: $0) })
where C.Index == Index, C.Element == Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection {
print("searching for /\(self)/ in \(c.u8str)...", terminator: "")
if let (extent, data) = self.found(in: c) {
print(
"\nfound at",
"\(c.offset(of: extent.lowerBound)..<c.offset(of: extent.upperBound)):",
c[extent].u8str,
MatchData.self == Void.self ? "" : "\ndata: \(format(data))")
}
else {
print("NOT FOUND")
}
print()
}
}
//===--- Just for testing -------------------------------------------------===//
//===--- Tests ------------------------------------------------------------===//
let source = Array("the quick brown fox jumps over the lazy dog".utf8)
let source2 = Array("hack hack cough cough cough spork".utf8)
(%"fox").searchTest(in: source)
(%"fog").searchTest(in: source)
(%"fox" .. %" box").searchTest(in: source)
(%"fox" .. %" jump").searchTest(in: source)
(%"cough")*.searchTest(in: source2)
(%"sneeze")+.searchTest(in: source2)
(%"hack ")*.searchTest(in: source2)
(%"cough ")+.searchTest(in: source2)
let fancyPattern
= %"quick "..((%"brown" | %"black" | %"fox" | %"chicken") .. %" ")+
.. (%__)
fancyPattern.searchTest(in: source)
//===--- Parsing pairs ----------------------------------------------------===//
// The beginnings of what it will take to wrap and indent m.data in the end of
// the last test, to make it readable.
struct PairedStructure<I: Comparable> {
let bounds: Range<I>
let subStructure: [PairedStructure<I>]
}
struct Paired<T: Hashable, I: Comparable> : Pattern {
typealias Element = T
typealias Index = I
typealias MatchData = PairedStructure<I>
let pairs: Dictionary<T,T>
func matched<C: Collection>(atStartOf c: C) -> MatchResult<Index, MatchData>
where C.Index == Index, C.Element == Element
// The following requirements go away with upcoming generics features
, C.SubSequence : Collection
{
guard let closer = c.first.flatMap({ pairs[$0] }) else {
return .notFound(resumeAt: nil)
}
var subStructure: [PairedStructure<I>] = []
var i = c.index(after: c.startIndex)
var resumption: Index? = nil
while i != c.endIndex {
if let m = self.found(in: c[i..<c.endIndex]) {
i = m.extent.upperBound
subStructure.append(m.data)
resumption = resumption ?? i
}
else {
let nextI = c.index(after: i)
if c[i] == closer {
return .found(
end: nextI,
data: PairedStructure(
bounds: c.startIndex..<nextI, subStructure: subStructure))
}
i = nextI
}
}
return .notFound(resumeAt: resumption)
}
}
// Local Variables:
// swift-syntax-check-fn: swift-syntax-check-single-file
// End:
|
apache-2.0
|
9af582b95fb5e3577f20fb6ec8a1ade1
| 29.622912 | 81 | 0.620217 | 3.709454 | false | false | false | false |
RemyDCF/tpg-offline
|
tpg offline/Departures/AllDeparturesCollectionViewController.swift
|
1
|
6490
|
//
// AllDeparturesCollectionViewController.swift
// tpg offline
//
// Created by Rémy Da Costa Faro on 01/10/2017.
// Copyright © 2018 Rémy Da Costa Faro. All rights reserved.
//
import UIKit
import Alamofire
class AllDeparturesCollectionViewController: UICollectionViewController {
var departure: Departure?
var stop: Stop?
var departuresList: DeparturesGroup?
var hours: [Int] = []
var loading = false {
didSet {
self.collectionView?.reloadData()
}
}
var refreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
title = String(format: "Line %@".localized, "\(departure?.line.code ?? "#!?")")
navigationItem.rightBarButtonItems = [
UIBarButtonItem(image: #imageLiteral(resourceName: "reloadNavBar"),
style: UIBarButtonItem.Style.plain,
target: self,
action: #selector(self.refresh),
accessbilityLabel: "Reload".localized)
]
self.refreshControl = UIRefreshControl()
if #available(iOS 10.0, *) {
collectionView?.refreshControl = refreshControl
} else {
collectionView?.addSubview(refreshControl)
}
refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
refreshControl.tintColor = #colorLiteral(red: 1, green: 0.3411764706, blue: 0.1333333333, alpha: 1)
if App.darkMode {
collectionView?.backgroundColor = App.cellBackgroundColor
}
ColorModeManager.shared.addColorModeDelegate(self)
refresh()
}
@objc func refresh() {
guard let stop = self.stop,
let departure = self.departure else { return }
loading = true
let destinationCode = departure.line.destinationCode
Alamofire.request(URL.allNextDepartures,
method: .get,
parameters: ["key": API.tpg,
"stopCode": stop.code,
"lineCode": departure.line.code,
"destinationCode": destinationCode])
.responseData { (response) in
if let data = response.result.value {
var options = DeparturesOptions()
options.networkStatus = .online
let jsonDecoder = JSONDecoder()
jsonDecoder.userInfo = [ DeparturesOptions.key: options ]
do {
let json = try jsonDecoder.decode(DeparturesGroup.self, from: data)
self.departuresList = json
} catch {
self.loading = false
self.refreshControl.endRefreshing()
return
}
self.hours = self.departuresList?.departures.map({
$0.dateCompenents?.hour ?? 0
}).uniqueElements ?? []
self.hours.sort()
self.loading = false
self.refreshControl.endRefreshing()
}
}
}
deinit {
ColorModeManager.shared.removeColorModeDelegate(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
if loading {
return 1
} else {
return self.hours.count
}
}
override func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
if loading {
return 5
} else {
return self.departuresList?.departures.filter({
$0.dateCompenents?.hour == self.hours[section]
}).count ?? 0
}
}
override func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// swiftlint:disable:previous line_length
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier:
"allDeparturesCell", for: indexPath) as? AllDeparturesCollectionViewCell else {
return UICollectionViewCell()
}
if !loading {
cell.departure = self.departuresList?.departures.filter({
$0.dateCompenents?.hour == self.hours[indexPath.section]
})[indexPath.row]
}
return cell
}
override func collectionView(_ collectionView: UICollectionView,
viewForSupplementaryElementOfKind kind: String,
at indexPath: IndexPath) -> UICollectionReusableView {
if loading {
let cellId = "allDeparturesHeader"
guard let headerView = collectionView
.dequeueReusableSupplementaryView(ofKind: kind,
withReuseIdentifier: cellId,
for: indexPath)
as? AllDeparturesHeader else {
return UICollectionViewCell()
}
headerView.backgroundColor = App.darkMode ? .black : #colorLiteral(red: 0.9333333333, green: 0.9333333333, blue: 0.9333333333, alpha: 1)
headerView.title.text = ""
return headerView
} else {
switch kind {
case UICollectionView.elementKindSectionHeader:
let cellId = "allDeparturesHeader"
guard let headerView = collectionView
.dequeueReusableSupplementaryView(ofKind: kind,
withReuseIdentifier: cellId,
for: indexPath)
as? AllDeparturesHeader else {
return UICollectionViewCell()
}
var dateComponents = DateComponents()
let dateFormatter = DateFormatter()
dateComponents.calendar = Calendar.current
dateComponents.hour = self.hours[indexPath.section]
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .short
headerView.title.text = dateFormatter.string(from:
dateComponents.date ?? Date())
headerView.title.accessibilityLabel = dateFormatter.string(from:
dateComponents.date ?? Date())
headerView.backgroundColor = App.darkMode ? .black : #colorLiteral(red: 1, green: 0.3411764706, blue: 0.1333333333, alpha: 1)
headerView.title.textColor = App.darkMode ? #colorLiteral(red: 1, green: 0.3411764706, blue: 0.1333333333, alpha: 1) : .white
return headerView
default:
assert(false, "Unexpected element kind")
return UICollectionReusableView()
}
}
}
}
class AllDeparturesHeader: UICollectionReusableView {
@IBOutlet weak var title: UILabel!
}
|
mit
|
c35090e6815d8aa820530d084ed91e6c
| 32.786458 | 142 | 0.620318 | 5.20626 | false | false | false | false |
zhihuitang/Apollo
|
Apollo/RotationLabel/RotationLabelViewController.swift
|
1
|
1937
|
//
// RotationLabelViewController.swift
// Apollo
//
// Created by Zhihui Tang on 2017-08-01.
// Copyright © 2017 Zhihui Tang. All rights reserved.
//
import UIKit
import CoreTelephony
class RotationLabelViewController: BaseViewController {
@IBOutlet weak var rotationLabel: RotationLabel!
override var name: String {
return "RotationLabel Demo"
}
override func viewDidLoad() {
super.viewDidLoad()
rotationLabel.texts = ["aa","bb","cc"]
// Do any additional setup after loading the view.
let networkInfo = CTTelephonyNetworkInfo()
let carrier = networkInfo.subscriberCellularProvider
print("carrier name: \(carrier?.carrierName ?? "not available")")
let device = UIDevice.current
print("systemVersion: \(device.systemVersion), battery: \(device.batteryState.rawValue)")
report_memory()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func report_memory() {
var taskInfo = mach_task_basic_info()
var count = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size)/4
let kerr: kern_return_t = withUnsafeMutablePointer(to: &taskInfo) {
$0.withMemoryRebound(to: integer_t.self, capacity: 1) {
task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &count)
}
}
if kerr == KERN_SUCCESS {
print("Memory used in bytes: \(taskInfo.resident_size)")
}
else {
print("Error with task_info(): " +
(String(cString: mach_error_string(kerr), encoding: String.Encoding.ascii) ?? "unknown error"))
}
print("total memory in MB: \(ProcessInfo.processInfo.physicalMemory/1024/1024)")
}
}
|
apache-2.0
|
ca9f51afa0fc4f213aade1843323d011
| 29.730159 | 111 | 0.610537 | 4.491879 | false | false | false | false |
natecook1000/swift-compiler-crashes
|
fixed/00194-swift-parser-parseexprsequence.swift
|
12
|
1147
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol A {
typealias E
}
struct B<T : A> {
let h -> g {
d j d.i = {
}
{
g) {
h }
}
protocol f {
class func i()
}
class d: f{ class func i {}
struct d<f : e,e where g.h == f.h> {
}
protocolias h
}
func some<S: SequenceType, T where Optional<T> == S.Generator.Element>(xs : S) -> T? {
for (mx : T?) in xs {
if let x = mx {
return x
}
}
return nil
}
let xs : [Int?] = [nil, 4, nil]
println(some(xs))
fuotocol A {
typealias B
}return []
}
func i(c: () -> ()) {
}
cnc c<d {
enum c {
func e
var _ = e
}
}
class A<T : A> {
}
func some<C -> b = b
}
protocol A {
typealias E
}
struct B<T : As a {
typealias b = b
}
func a<T>() {f {
class func i()
}
class d: f{ class func i {}
func f() {
({})
}
func prefix(with: String) -> <T>(() -> T) -> String {
return { g in "\(with): \(g())" }
}
protocol a : a {
}
var x1 = 1
var f1: Int -> Int = {
return $0
}
let su a(2, 3)))
|
mit
|
389b6b93312e21524f7a0b79c5cea998
| 14.930556 | 87 | 0.513514 | 2.763855 | false | false | false | false |
tapglue/ios_sample
|
TapglueSample/ProfileFeedTableViewCell.swift
|
1
|
2355
|
//
// ProfileFeedTableViewCell.swift
// TapglueSample
//
// Created by Özgür Celebi on 15/12/15.
// Copyright © 2015 Özgür Celebi. All rights reserved.
//
import UIKit
import Tapglue
class ProfileFeedTableViewCell: UITableViewCell {
@IBOutlet weak var infoLabel: UILabel!
@IBOutlet weak var typeLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
let appDel = UIApplication.sharedApplication().delegate! as! AppDelegate
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func configureCellWithPost(post: Post!){
clearLabels()
let attachments = post.attachments
self.infoLabel.text = attachments![0].contents!["en"]
self.typeLabel.text = String(attachments![0].name!).capitalizeFirst
// String to elapsed time
self.dateLabel.text = post.createdAt!.toNSDateTime().toStringFormatDayMonthYear()
}
func configureCellWithEvent(activity: Activity!){
clearLabels()
self.dateLabel.text = activity.createdAt!.toNSDateTime().toStringFormatDayMonthYear()
switch activity.type! {
case "tg_friend":
if activity.targetUser != nil {
self.typeLabel.text = "Friends"
self.infoLabel.text = "You are Friends with " + (activity.targetUser?.username!)!
}
case "tg_like":
if activity.post?.user != nil {
self.typeLabel.text = "You Liked " + (activity.post?.user?.username!)! + "'s" + " post"
self.infoLabel.text = activity.post?.attachments![0].contents!["en"]
}
case "tg_follow":
if activity.targetUser != nil {
self.typeLabel.text = "Follow"
self.infoLabel.text = "You started to follow " + (activity.targetUser?.username!)!
}
case "tg_comment":
if activity.post?.user != nil {
self.typeLabel.text = "Commented"
self.infoLabel.text = "You commented on " + (activity.post?.user?.username!)! + "'s post"
}
default: print("default")
}
}
func clearLabels(){
self.typeLabel.text = ""
self.infoLabel.text = ""
self.dateLabel.text = ""
}
}
|
apache-2.0
|
b7ad99b0c84bb14a0e64f443e19693dd
| 31.638889 | 105 | 0.581277 | 4.450758 | false | false | false | false |
infobip/mobile-messaging-sdk-ios
|
Classes/Core/Utils/MMGCD.swift
|
1
|
3013
|
//
// MMGCD.swift
// MobileMessaging
//
// Created by Andrey K. on 17/02/16.
//
//
import Foundation
final class MMQueueObject: CustomStringConvertible {
private(set) var queue: DispatchQueue
private var queueTag: DispatchSpecificKey<String>
var isCurrentQueue: Bool {
if isMain {
return Thread.isMainThread
} else if isGlobal {
return DispatchQueue.getSpecific(key: queueTag) == DispatchQueue.global().label
}
return DispatchQueue.getSpecific(key: queueTag) != nil
}
init(queue: DispatchQueue) {
self.queue = queue
self.queueLabel = queue.label
self.queueTag = DispatchSpecificKey<String>()
queue.setSpecific(key: queueTag, value: queue.label)
}
var isGlobal: Bool {
return queueLabel?.hasPrefix("com.apple.root.") ?? false
}
var isMain: Bool {
return queueLabel == "com.apple.main-thread"
}
var queueLabel: String?
func async(closure: @escaping () -> Void) {
if isCurrentQueue {
closure()
} else {
queue.async(execute: closure)
}
}
func asyncBarier(closure: @escaping () -> Void) {
if isCurrentQueue {
closure()
} else {
queue.async(flags: .barrier) {
closure()
}
}
}
func sync(closure: () -> Void) {
if isCurrentQueue {
closure()
} else {
queue.sync(execute: closure)
}
}
func getSync<T>(closure: () -> T) -> T {
if isCurrentQueue {
return closure()
} else {
var ret: T!
queue.sync(execute: {
ret = closure()
})
return ret!
}
}
var description: String { return queue.label }
}
protocol MMQueueEnum {
var queue: MMQueueObject {get}
var queueName: String {get}
}
enum MMQueue {
case Main
case Global
var queue: MMQueueObject {
switch self {
case .Global:
return MMQueueObject(queue: DispatchQueue.global(qos: .default))
case .Main:
return MMQueueObject(queue: DispatchQueue.main)
}
}
enum Serial {
enum New: String, MMQueueEnum {
case MessageStorageQueue = "com.mobile-messaging.queue.serial.message-storage"
case UserSessionQueue = "com.mobile-messaging.queue.serial.user-session"
case PostponerQueue = "com.mobile-messaging.queue.serial.postponer"
var queueName: String { return rawValue }
var queue: MMQueueObject { return Serial.newQueue(queueName: queueName) }
}
static func newQueue(queueName: String) -> MMQueueObject {
return MMQueueObject(queue: DispatchQueue(label: queueName))
}
}
enum Concurrent {
static func newQueue(queueName: String) -> MMQueueObject {
return MMQueueObject(queue: DispatchQueue(label: queueName, attributes: DispatchQueue.Attributes.concurrent))
}
}
}
func getFromMain<T>(getter: () -> T) -> T {
return MMQueue.Main.queue.getSync(closure: { getter() })
}
func inMainWait(block: () -> Void) {
return MMQueue.Main.queue.sync(closure: block)
}
func inMain(block: @escaping () -> Void) {
return MMQueue.Main.queue.async(closure: block)
}
|
apache-2.0
|
d5e5e256456a1400d669d91d3d388e00
| 21.485075 | 112 | 0.657152 | 3.483237 | false | false | false | false |
Maxim-Inv/RealmS
|
Sources/RealmS.swift
|
1
|
25092
|
//
// RealmS.swift
// RealmS
//
// Created by DaoNV on 1/10/16.
// Copyright © 2016 Apple Inc. All rights reserved.
//
import RealmSwift
/**
A `Realm` instance (also referred to as "a Realm") represents a Realm database.
Realms can either be stored on disk (see `init(path:)`) or in memory (see `Configuration`).
`Realm` instances are cached internally, and constructing equivalent `Realm` objects (for example, by using the same
path or identifier) produces limited overhead.
If you specifically want to ensure a `Realm` instance is destroyed (for example, if you wish to open a Realm, check
some property, and then possibly delete the Realm file and re-open it), place the code which uses the Realm within an
`autoreleasepool {}` and ensure you have no other strong references to it.
- warning: `Realm` instances are not thread safe and cannot be shared across threads or dispatch queues. You must
construct a new instance for each thread in which a Realm will be accessed. For dispatch queues, this means
that you must construct a new instance in each block which is dispatched, as a queue is not guaranteed to
run all of its blocks on the same thread.
*/
public final class RealmS {
// MARK: Additional
public enum ErrorType: Error {
case write /// throwed while commit write transaction.
case encrypt /// throwed by `writeCopyToURL(_:, encryptionKey:)`
}
public typealias ErrorHandler = (_ realm: RealmS, _ error: NSError, _ type: ErrorType) -> Void
private static var handleError: ErrorHandler?
/**
Invoked after RealmS catched an exception.
- parameter handler: Error handler block.
*/
public static func onError(_ handler: @escaping ErrorHandler) {
handleError = handler
}
private var deletedTypes: [Object.Type] = []
private func clean() {
while deletedTypes.count > 0 {
let type = deletedTypes.removeFirst()
for relatived in type.relativedTypes() {
relatived.clean()
}
}
}
// MARK: Properties
/// The `Schema` used by the Realm.
public var schema: Schema { return realm.schema }
/// The `Configuration` value that was used to create the `Realm` instance.
public var configuration: Realm.Configuration { return realm.configuration }
/// Indicates if the Realm contains any objects.
public var isEmpty: Bool { return realm.isEmpty }
// MARK: Initializers
/**
Obtains an instance of the default Realm.
The default Realm is persisted as *default.realm* under the *Documents* directory of your Application on iOS, and
in your application's *Application Support* directory on OS X.
The default Realm is created using the default `Configuration`, which can be changed by setting the
`Realm.Configuration.defaultConfiguration` property to a new value.
- throws: An `NSError` if the Realm could not be initialized.
*/
public convenience init() {
do {
let realm = try Realm()
self.init(realm)
} catch {
fatalError((error as NSError).localizedDescription)
}
}
/**
Obtains a `Realm` instance with the given configuration.
- parameter configuration: A configuration value to use when creating the Realm.
- throws: An `NSError` if the Realm could not be initialized.
*/
public convenience init(configuration: Realm.Configuration) {
do {
let realm = try Realm(configuration: configuration)
self.init(realm)
} catch {
fatalError((error as NSError).localizedDescription)
}
}
/**
Obtains a `Realm` instance persisted at a specified file URL.
- parameter fileURL: The local URL of the file the Realm should be saved at.
- throws: An `NSError` if the Realm could not be initialized.
*/
public convenience init!(fileURL: URL) {
var configuration = Realm.Configuration.defaultConfiguration
configuration.fileURL = fileURL
self.init(configuration: configuration)
}
// MARK: Transactions
/**
Performs actions contained within the given block inside a write transaction.
If the block throws an error, the transaction will be canceled, reverting any writes made in the block before the
error was thrown.
Write transactions cannot be nested, and trying to execute a write transaction on a Realm which is already
participating in a write transaction will throw an error. Calls to `write` from `Realm` instances in other threads
will block until the current write transaction completes.
Before executing the write transaction, `write` updates the `Realm` instance to the latest Realm version, as if
`refresh()` had been called, and generates notifications if applicable. This has no effect if the Realm was already
up to date.
- parameter block: The block containing actions to perform.
- throws: An `NSError` if the transaction could not be completed successfully.
If `block` throws, the function throws the propagated `ErrorType` instead.
*/
public func write(_ block: (() throws -> Void)) {
do {
try realm.write(block)
clean()
} catch {
RealmS.handleError?(self, error as NSError, .write)
}
}
/**
Begins a write transaction on the Realm.
Only one write transaction can be open at a time. Write transactions cannot be nested, and trying to begin a write
transaction on a Realm which is already in a write transaction will throw an error. Calls to `beginWrite` from
`Realm` instances in other threads will block until the current write transaction completes.
Before beginning the write transaction, `beginWrite` updates the `Realm` instance to the latest Realm version, as
if `refresh()` had been called, and generates notifications if applicable. This has no effect if the Realm was
already up to date.
It is rarely a good idea to have write transactions span multiple cycles of the run loop, but if you do wish to do
so you will need to ensure that the Realm in the write transaction is kept alive until the write transaction is
committed.
*/
public func beginWrite() {
realm.beginWrite()
}
/**
Commits all write operations in the current write transaction, and ends the transaction.
- warning: This method may only be called during a write transaction.
- throws: An `NSError` if the transaction could not be written.
*/
public func commitWrite() {
do {
try realm.commitWrite()
clean()
} catch {
RealmS.handleError?(self, error as NSError, .write)
}
}
/**
Reverts all writes made in the current write transaction and ends the transaction.
This rolls back all objects in the Realm to the state they were in at the beginning of the write transaction, and
then ends the transaction.
This restores the data for deleted objects, but does not revive invalidated object instances. Any `Object`s which
were added to the Realm will be invalidated rather than becoming unmanaged.
Given the following code:
```swift
let oldObject = objects(ObjectType).first!
let newObject = ObjectType()
realm.beginWrite()
realm.add(newObject)
realm.delete(oldObject)
realm.cancelWrite()
```
Both `oldObject` and `newObject` will return `true` for `isInvalidated`, but re-running the query which provided
`oldObject` will once again return the valid object.
- warning: This method may only be called during a write transaction.
*/
public func cancelWrite() {
realm.cancelWrite()
}
/**
Indicates whether the Realm is currently in a write transaction.
- warning: Do not simply check this property and then start a write transaction whenever an object needs to be
created, updated, or removed. Doing so might cause a large number of write transactions to be created,
degrading performance. Instead, always prefer performing multiple updates during a single transaction.
*/
public var isInWriteTransaction: Bool {
return realm.isInWriteTransaction
}
// MARK: Adding and Creating objects
/**
Adds or updates an existing object into the Realm.
Only pass `true` to `update` if the object has a primary key. If no objects exist in the Realm with the same
primary key value, the object is inserted. Otherwise, the existing object is updated with any changed values.
When added, all child relationships referenced by this object will also be added to the Realm if they are not
already in it. If the object or any related objects are already being managed by a different Realm an error will be
thrown. Instead, use one of the `create` functions to insert a copy of a managed object into a different Realm.
The object to be added must be valid and cannot have been previously deleted from a Realm (i.e. `isInvalidated`
must be `false`).
- parameter object: The object to be added to this Realm.
- parameter update: If `true`, the Realm will try to find an existing copy of the object (with the same primary
key), and update it. Otherwise, the object will be added.
*/
public func add<T: Object>(_ object: T) {
let update = T.primaryKey() != nil
realm.add(object, update: update)
}
/**
Adds or updates all the objects in a collection into the Realm.
- see: `add(_:update:)`
- warning: This method may only be called during a write transaction.
- parameter objects: A sequence which contains objects to be added to the Realm.
- parameter update: If `true`, objects that are already in the Realm will be updated instead of added anew.
*/
public func add<S: Sequence>(_ objects: S) where S.Iterator.Element: Object {
typealias T = S.Iterator.Element
let update = T.primaryKey() != nil
for obj in objects {
realm.add(obj, update: update)
}
}
/**
Creates or updates a Realm object with a given value, adding it to the Realm and returning it.
Only pass `true` to `update` if the object has a primary key. If no objects exist in
the Realm with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
The `value` argument can be a key-value coding compliant object, an array or dictionary returned from the methods
in `NSJSONSerialization`, or an `Array` containing one element for each managed property. An exception will be
thrown if any required properties are not present and those properties were not defined with default values. Do not
pass in a `LinkingObjects` instance, either by itself or as a member of a collection.
When passing in an `Array` as the `value` argument, all properties must be present, valid and in the same order as
the properties defined in the model.
- warning: This method may only be called during a write transaction.
- parameter type: The type of the object to create.
- parameter value: The value used to populate the object.
- parameter update: If `true`, the Realm will try to find an existing copy of the object (with the same primary
key), and update it. Otherwise, the object will be added.
- returns: The newly created object.
*/
@discardableResult
public func create<T: Object>(_ type: T.Type, value: Any = [:]) -> T {
let typeName = (type as Object.Type).className()
let update = schema[typeName]?.primaryKeyProperty != nil
return realm.create(type, value: value, update: update)
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `create(_:value:update:)`.
Creates or updates an object with the given class name and adds it to the `Realm`, populating
the object with the given value.
When 'update' is 'true', the object must have a primary key. If no objects exist in
the Realm instance with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
The `value` argument is used to populate the object. It can be a key-value coding compliant object, an array or
dictionary returned from the methods in `NSJSONSerialization`, or an `Array` containing one element for each
managed property. An exception will be thrown if any required properties are not present and those properties were
not defined with default values.
When passing in an `Array` as the `value` argument, all properties must be present, valid and in the same order as
the properties defined in the model.
- warning: This method can only be called during a write transaction.
- parameter className: The class name of the object to create.
- parameter value: The value used to populate the object.
- parameter update: If true will try to update existing objects with the same primary key.
- returns: The created object.
:nodoc:
*/
@discardableResult
public func dynamicCreate(_ typeName: String, value: Any = [:]) -> DynamicObject! {
let update = schema[typeName]?.primaryKeyProperty != nil
return realm.dynamicCreate(typeName, value: value, update: update)
}
// MARK: Deleting objects
/**
Deletes an object from the Realm. Once the object is deleted it is considered invalidated.
- warning: This method may only be called during a write transaction.
- parameter object: The object to be deleted.
*/
public func delete<T: Object>(_ object: T) {
realm.delete(object)
deletedTypes.append(T.self)
}
/**
Deletes zero or more objects from the Realm.
- warning: This method may only be called during a write transaction.
- parameter objects: The objects to be deleted. This can be a `List<Object>`, `Results<Object>`, or any other
Swift `Sequence` whose elements are `Object`s.
*/
public func delete<S: Sequence>(_ objects: S) where S.Iterator.Element: Object {
realm.delete(objects)
let type = S.Iterator.Element.self
deletedTypes.append(type)
}
/**
Deletes zero or more objects from the Realm.
- warning: This method may only be called during a write transaction.
- parameter objects: A list of objects to delete.
:nodoc:
*/
public func delete<T: Object>(_ objects: List<T>) {
realm.delete(objects)
deletedTypes.append(T.self)
}
/**
Deletes zero or more objects from the Realm.
- warning: This method may only be called during a write transaction.
- parameter objects: A `Results` containing the objects to be deleted.
:nodoc:
*/
public func delete<T: Object>(_ objects: Results<T>) {
realm.delete(objects)
deletedTypes.append(T.self)
}
/**
Returns all objects of the given type stored in the Realm.
- parameter type: The type of the objects to be returned.
- returns: A `Results` containing the objects.
*/
public func deleteAll() {
realm.deleteAll()
}
// MARK: Object Retrieval
/**
Returns all objects of the given type stored in the Realm.
- parameter type: The type of the objects to be returned.
- returns: A `Results` containing the objects.
*/
public func objects<T: Object>(_ type: T.Type) -> Results<T> {
return realm.objects(type)
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `objects(type:)`.
Returns all objects for a given class name in the Realm.
- parameter typeName: The class name of the objects to be returned.
- returns: All objects for the given class name as dynamic objects
:nodoc:
*/
public func dynamicObjects(_ typeName: String) -> Results<DynamicObject> {
return realm.dynamicObjects(typeName)
}
/**
Retrieves the single instance of a given object type with the given primary key from the Realm.
This method requires that `primaryKey()` be overridden on the given object class.
- see: `Object.primaryKey()`
- parameter type: The type of the object to be returned.
- parameter key: The primary key of the desired object.
- returns: An object of type `type`, or `nil` if no instance with the given primary key exists.
*/
public func object<T: RealmSwift.Object, K>(ofType type: T.Type, forPrimaryKey key: K) -> T? {
return realm.object(ofType: type, forPrimaryKey: key)
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `objectForPrimaryKey(_:key:)`.
Get a dynamic object with the given class name and primary key.
Returns `nil` if no object exists with the given class name and primary key.
This method requires that `primaryKey()` be overridden on the given subclass.
- see: Object.primaryKey()
- warning: This method is useful only in specialized circumstances.
- parameter className: The class name of the object to be returned.
- parameter key: The primary key of the desired object.
- returns: An object of type `DynamicObject` or `nil` if an object with the given primary key does not exist.
:nodoc:
*/
public func dynamicObject(ofType typeName: String, forPrimaryKey key: Any) -> RealmSwift.DynamicObject? {
return realm.dynamicObject(ofType: typeName, forPrimaryKey: key)
}
// MARK: Notifications
/**
Adds a notification handler for changes made to this Realm, and returns a notification token.
Notification handlers are called after each write transaction is committed, independent of the thread or process.
Handler blocks are called on the same thread that they were added on, and may only be added on threads which are
currently within a run loop. Unless you are specifically creating and running a run loop on a background thread,
this will normally only be the main thread.
Notifications can't be delivered as long as the run loop is blocked by other activity. When notifications can't be
delivered instantly, multiple notifications may be coalesced.
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `stop()` on the token.
- parameter block: A block which is called to process Realm notifications. It receives the following parameters:
`notification`: the incoming notification; `realm`: the Realm for which the notification
occurred.
- returns: A token which must be held for as long as you wish to continue receiving change notifications.
*/
public func addNotificationBlock(_ block: @escaping NotificationBlock) -> NotificationToken {
return realm.addNotificationBlock { notif, _ in
block(notif, self)
}
}
// MARK: Autorefresh and Refresh
/**
Set this property to `true` to automatically update this Realm when changes happen in other threads.
If set to `true` (the default), changes made on other threads will be reflected in this Realm on the next cycle of
the run loop after the changes are committed. If set to `false`, you must manually call `refresh()` on the Realm
to update it to get the latest data.
Note that by default, background threads do not have an active run loop and you will need to manually call
`refresh()` in order to update to the latest version, even if `autorefresh` is set to `true`.
Even with this property enabled, you can still call `refresh()` at any time to update the Realm before the
automatic refresh would occur.
Notifications are sent when a write transaction is committed whether or not automatic refreshing is enabled.
Disabling `autorefresh` on a `Realm` without any strong references to it will not have any effect, and
`autorefresh` will revert back to `true` the next time the Realm is created. This is normally irrelevant as it
means that there is nothing to refresh (as managed `Object`s, `List`s, and `Results` have strong references to the
`Realm` that manages them), but it means that setting `autorefresh = false` in
`application(_:didFinishLaunchingWithOptions:)` and only later storing Realm objects will not work.
Defaults to `true`.
*/
public var autorefresh: Bool {
get {
return realm.autorefresh
}
set {
realm.autorefresh = newValue
}
}
/**
Updates the Realm and outstanding objects managed by the Realm to point to the most recent data.
- returns: Whether there were any updates for the Realm. Note that `true` may be returned even if no data actually
changed.
*/
@discardableResult
public func refresh() -> Bool {
return realm.refresh()
}
// MARK: Invalidation
/**
Invalidates all `Object`s, `Results`, `LinkingObjects`, and `List`s managed by the Realm.
A Realm holds a read lock on the version of the data accessed by it, so
that changes made to the Realm on different threads do not modify or delete the
data seen by this Realm. Calling this method releases the read lock,
allowing the space used on disk to be reused by later write transactions rather
than growing the file. This method should be called before performing long
blocking operations on a background thread on which you previously read data
from the Realm which you no longer need.
All `Object`, `Results` and `List` instances obtained from this `Realm` instance on the current thread are
invalidated. `Object`s and `Array`s cannot be used. `Results` will become empty. The Realm itself remains valid,
and a new read transaction is implicitly begun the next time data is read from the Realm.
Calling this method multiple times in a row without reading any data from the
Realm, or before ever reading any data from the Realm, is a no-op. This method
may not be called on a read-only Realm.
*/
public func invalidate() {
realm.invalidate()
}
// MARK: Writing a Copy
/**
Writes a compacted and optionally encrypted copy of the Realm to the given local URL.
The destination file cannot already exist.
Note that if this method is called from within a write transaction, the *current* data is written, not the data
from the point when the previous write transaction was committed.
- parameter fileURL: Local URL to save the Realm to.
- parameter encryptionKey: Optional 64-byte encryption key to encrypt the new file with.
- throws: An `NSError` if the copy could not be written.
*/
public func writeCopy(toFile fileURL: URL, encryptionKey: Data? = nil) {
do {
try realm.writeCopy(toFile: fileURL, encryptionKey: encryptionKey)
} catch {
RealmS.handleError?(self, error as NSError, .encrypt)
}
}
// MARK: Internal
internal var realm: Realm
internal init(_ realm: Realm) {
self.realm = realm
}
}
// MARK: Equatable
extension RealmS: Equatable { }
/// Returns whether the two realms are equal.
public func == (lhs: RealmS, rhs: RealmS) -> Bool { // swiftlint:disable:this valid_docs
return lhs.realm == rhs.realm
}
// MARK: Notifications
/// Closure to run when the data in a Realm was modified.
public typealias NotificationBlock = (_ notification: Realm.Notification, _ realm: RealmS) -> Void
// MARK: Unavailable
extension RealmS {
@available( *, unavailable, renamed: "isInWriteTransaction")
public var inWriteTransaction: Bool { fatalError() }
@available( *, unavailable, renamed: "object(ofType:forPrimaryKey:)")
public func objectForPrimaryKey<T: Object>(_ type: T.Type, key: AnyObject) -> T? { fatalError() }
@available( *, unavailable, renamed: "dynamicObject(ofType:forPrimaryKey:)")
public func dynamicObjectForPrimaryKey(_ className: String, key: AnyObject) -> DynamicObject? { fatalError() }
@available( *, unavailable, renamed: "writeCopy(toFile:encryptionKey:)")
public func writeCopyToURL(_ fileURL: NSURL, encryptionKey: Data? = nil) throws { fatalError() }
}
|
mit
|
5c9291e61c7c125a5a097bc27cb2901a
| 38.638231 | 120 | 0.688813 | 4.774691 | false | false | false | false |
clappr/clappr-ios
|
Tests/Clappr_tvOS_Tests/AVFoundationPlaybackNowPlayingServiceTests.swift
|
1
|
2723
|
import Quick
import Nimble
import MediaPlayer
@testable import Clappr
class AVFoundationNowPlayingServiceTests: QuickSpec {
override func spec() {
describe("AVFoundationNowPlayingService") {
var nowPlayingService: AVFoundationNowPlayingService?
var options: Options!
describe("#setItems(to, with options)") {
beforeEach {
nowPlayingService = AVFoundationNowPlayingService()
}
context("when has no metadata items") {
beforeEach {
options = [:]
}
it("doesn't set externalMetadata to item") {
let url = URL(string: "http://test.com")
let playerItem = AVPlayerItem(url: url!)
nowPlayingService?.setItems(to: playerItem, with: options)
let items = nowPlayingService?.nowPlayingBuilder?.build().compactMap{ $0.identifier } ?? []
let externalMetadataIdentifiers = playerItem.externalMetadata.map({ $0.identifier ?? AVMetadataIdentifier(rawValue: "") })
let didSetAllItems = !items.compactMap({ externalMetadataIdentifiers.contains($0) }).contains(true)
expect(didSetAllItems).to(beTrue())
}
}
context("when has metadata items") {
beforeEach {
let metadata = [kMetaDataTitle: "Foo",
kMetaDataDescription: "Lorem ipsum lorem",
kMetaDataContentIdentifier: "Foo v2",
kMetaDataDate: Date(),
kMetaDataWatchedTime: 1] as [String : Any]
options = [kMetaData: metadata]
}
it("doesn't set externalMetadata to item") {
let url = URL(string: "http://test.com")
let playerItem = AVPlayerItem(url: url!)
nowPlayingService?.setItems(to: playerItem, with: options)
let items = nowPlayingService?.nowPlayingBuilder?.build().compactMap{ $0.identifier } ?? []
let externalMetadataIdentifiers = playerItem.externalMetadata.map({ $0.identifier ?? AVMetadataIdentifier(rawValue: "") })
let didSetAllItems = !items.compactMap({ externalMetadataIdentifiers.contains($0) }).contains(false)
expect(didSetAllItems).to(beTrue())
}
}
}
}
}
}
|
bsd-3-clause
|
84acbcabb34b18ea7e5ab81082f5ff24
| 39.641791 | 146 | 0.509365 | 6.078125 | false | true | false | false |
csontosgabor/Twitter_Post
|
Twitter_Post/Utilities.swift
|
1
|
2384
|
//
// Utilities.swift
// Twitter_Post
//
// Created by Gabor Csontos on 12/18/16.
// Copyright © 2016 GaborMajorszki. All rights reserved.
//
import Foundation
import UIKit
internal func localizedString(_ key: String) -> String {
return "Error"//NSLocalizedString(key, tableName: CameraGlobals.shared.stringsTable, bundle: CameraGlobals.shared.bundle, comment: key)
}
internal func randomAlphaNumericString(_ length: Int) -> String {
let allowedChars = "56789"
let allowedCharsCount = UInt32(allowedChars.characters.count)
var randomString = ""
for _ in (0..<length) {
let randomNum = Int(arc4random_uniform(allowedCharsCount))
let newCharacter = allowedChars[allowedChars.characters.index(allowedChars.startIndex, offsetBy: randomNum)]
randomString += String(newCharacter)
}
return randomString
}
internal func largestPhotoSize() -> CGSize {
let scale = UIScreen.main.scale
let screenSize = UIScreen.main.bounds.size
let size = CGSize(width: screenSize.width * scale, height: screenSize.height * scale)
return size
}
internal func errorWithKey(_ key: String, domain: String) -> NSError {
let errorString = localizedString(key)
let errorInfo = [NSLocalizedDescriptionKey: errorString]
let error = NSError(domain: domain, code: 0, userInfo: errorInfo)
return error
}
internal func normalizedRect(_ rect: CGRect, orientation: UIImageOrientation) -> CGRect {
let normalizedX = rect.origin.x
let normalizedY = rect.origin.y
let normalizedWidth = rect.width
let normalizedHeight = rect.height
var normalizedRect: CGRect
switch orientation {
case .up, .upMirrored:
normalizedRect = CGRect(x: normalizedX, y: normalizedY, width: normalizedWidth, height: normalizedHeight)
case .down, .downMirrored:
normalizedRect = CGRect(x: 1-normalizedX-normalizedWidth, y: 1-normalizedY-normalizedHeight, width: normalizedWidth, height: normalizedHeight)
case .left, .leftMirrored:
normalizedRect = CGRect(x: 1-normalizedY-normalizedHeight, y: normalizedX, width: normalizedHeight, height: normalizedWidth)
case .right, .rightMirrored:
normalizedRect = CGRect(x: normalizedY, y: 1-normalizedX-normalizedWidth, width: normalizedHeight, height: normalizedWidth)
}
return normalizedRect
}
|
mit
|
bf89a270978e956d1d43323c59ed68bb
| 31.202703 | 150 | 0.715904 | 4.479323 | false | false | false | false |
yanil3500/acoustiCast
|
AcoustiCastr/AcoustiCastr/DetailPodcastViewController.swift
|
1
|
4000
|
//
// DetailPodcastViewController.swift
// AcoustiCastr
//
// Created by David Porter on 4/12/17.
// Copyright © 2017 Elyanil Liranzo Castro. All rights reserved.
//
import UIKit
class DetailPodcastViewController: UIViewController {
@IBOutlet weak var podcastArt: UIImageView!
@IBOutlet weak var episodeView: UITableView!
@IBOutlet weak var podcastTitle: UINavigationItem!
var selectedPod: Podcast!
var podcastDescription: String? {
didSet {
self.podcastDescription = (self.episodes.first?.summary)!
}
}
var rowHeight = 50
var episodes = [Episode]()
var interactor = Interactor()
override func viewDidLoad() {
super.viewDidLoad()
self.episodeView.delegate = self
self.episodeView.dataSource = self
print("Inside of podcastDetailViewController: ")
self.podcastArt.image = selectedPod.podcastAlbumArt
self.podcastTitle.title = selectedPod.collectionName
//Register nib
let episodeNib = UINib(nibName: "PodcastDetailViewCell", bundle: Bundle.main)
self.episodeView.register(episodeNib, forCellReuseIdentifier: "PodcastDetailViewCell")
self.episodeView.estimatedRowHeight = CGFloat(rowHeight)
self.episodeView.rowHeight = UITableViewAutomaticDimension
//hands rss feed from selected podcast to our RSS singleton
RSS.shared.rssFeed = selectedPod.podcastFeed
RSS.shared.getEpisodes(completion: { (episodes) in
guard let podcastEps = episodes else { print("failed to get episodes."); return }
self.episodes = podcastEps
self.episodeView.reloadData()
})
}
}
extension DetailPodcastViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.episodes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let episodeDate = self.episodes[indexPath.row].pubDate.components(separatedBy: " ").dropLast().dropLast().dropLast().dropFirst()
let cell = tableView.dequeueReusableCell(withIdentifier: "PodcastDetailViewCell", for: indexPath) as! PodcastDetailViewCell
cell.nameLabel.text = self.episodes[indexPath.row].title
cell.day.text = episodeDate.first
cell.month.text = episodeDate.last
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: PlayerViewController.identifier, sender: nil)
self.episodeView.deselectRow(at: indexPath, animated: false)
}
}
extension DetailPodcastViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == PlayerViewController.identifier {
if let selectedIndex = self.episodeView.indexPathForSelectedRow?.row {
let selectedEpisode = self.episodes[selectedIndex]
guard let destinationController = segue.destination as? PlayerViewController else { print("Failed to prepare segue"); return }
destinationController.transitioningDelegate = self
destinationController.interactor = interactor
destinationController.episode = selectedEpisode
destinationController.selectedPodcast = self.selectedPod
}
}
}
}
extension DetailPodcastViewController: UIViewControllerTransitioningDelegate {
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return DismissAnimator()
}
func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactor.hasStarted ? interactor : nil
}
}
|
mit
|
3092de9d8244d79e22e4be5cc9f83573
| 37.825243 | 144 | 0.694674 | 5.493132 | false | false | false | false |
LipliStyle/Liplis-iOS
|
Liplis/CtvCellWidgetCtrlRescueWIdget.swift
|
1
|
3629
|
//
// CtvCellWidgetCtrlRescueWIdget.swift
// Liplis
//
//ウィジェット操作 要素 ウィジェット全復帰
//
//アップデート履歴
// 2015/05/07 ver0.1.0 作成
// 2015/05/09 ver1.0.0 リリース
// 2015/05/16 ver1.4.0 リファクタリング
//
// Created by sachin on 2015/05/07.
// Copyright (c) 2015年 sachin. All rights reserved.
//
import UIKit
class CtvCellWidgetCtrlRescueWIdget : UITableViewCell
{
///=============================
///カスタムセル要素
internal var parView : ViewWidgetCtrl!
///=============================
///カスタムセル要素
internal var lblTitle = UILabel();
internal var btnHelp = UIButton();
///=============================
///レイアウト情報
internal var viewWidth : CGFloat! = 0
//============================================================
//
//初期化処理
//
//============================================================
internal override init(style: UITableViewCellStyle, reuseIdentifier: String!)
{
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.lblTitle = UILabel(frame: CGRectMake(10, 23, 300, 15));
self.lblTitle.text = "全てのウィジェットを画面内に呼び戻します。";
self.lblTitle.font = UIFont.systemFontOfSize(15)
self.lblTitle.numberOfLines = 2
self.addSubview(self.lblTitle);
//ボタン
self.btnHelp = UIButton()
self.btnHelp.titleLabel?.font = UIFont.systemFontOfSize(16)
self.btnHelp.frame = CGRectMake(0,5,40,48)
self.btnHelp.layer.masksToBounds = true
self.btnHelp.setTitle("実行", forState: UIControlState.Normal)
self.btnHelp.addTarget(self, action: "onClick:", forControlEvents: .TouchDown)
self.btnHelp.layer.cornerRadius = 3.0
self.btnHelp.backgroundColor = UIColor.hexStr("DF7401", alpha: 255)
self.addSubview(self.btnHelp)
}
/*
ビューを設定する
*/
internal func setView(parView : ViewWidgetCtrl)
{
self.parView = parView
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
/*
要素の位置を調整する
*/
internal func setSize(viewWidth : CGFloat)
{
self.viewWidth = viewWidth
let locationX : CGFloat = CGFloat(viewWidth - viewWidth/4 - 5)
self.btnHelp.frame = CGRectMake(locationX, 5,viewWidth/4,60)
self.lblTitle.frame = CGRectMake(10, 5,viewWidth * 3/4 - 20,50)
}
//============================================================
//
//イベントハンドラ
//
//============================================================
/*
スイッチ選択
*/
internal func onClick(sender: UIButton) {
let myAlert: UIAlertController = UIAlertController(title: "ウィジェット復帰", message: "全てのウィジェットを画面上に復帰させますか?", preferredStyle: .Alert)
let myOkAction = UIAlertAction(title: "実行", style: .Default) { action in
self.parView.app.activityDeskTop.rescueWidgetAll()
print("実行しました。")
}
let myCancelAction = UIAlertAction(title: "キャンセル", style: .Default) { action in
print("中止しました。")
}
myAlert.addAction(myOkAction)
myAlert.addAction(myCancelAction)
self.parView.presentViewController(myAlert, animated: true, completion: nil)
}
}
|
mit
|
403b8888e4f2424f688588dd59ccee01
| 29.277778 | 136 | 0.551545 | 4.174968 | false | false | false | false |
RMizin/PigeonMessenger-project
|
FalconMessenger/Contacts/ContactsController+SearchHandlers.swift
|
1
|
2433
|
//
// ContactsController+SearchHandlers.swift
// Pigeon-project
//
// Created by Roman Mizin on 3/10/18.
// Copyright © 2018 Roman Mizin. All rights reserved.
//
import UIKit
extension ContactsController: UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = nil
setupDataSource()
filteredContacts = contacts
UIView.transition(with: tableView, duration: 0.15, options: .transitionCrossDissolve, animations: {
self.tableView.reloadData()
}, completion: nil)
guard #available(iOS 11.0, *) else {
searchBar.setShowsCancelButton(false, animated: true)
searchBar.resignFirstResponder()
return
}
}
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.keyboardAppearance = ThemeManager.currentTheme().keyboardAppearance
guard #available(iOS 11.0, *) else {
searchBar.setShowsCancelButton(true, animated: true)
return true
}
return true
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
let userObjects = realm.objects(User.self).sorted(byKeyPath: "onlineStatusSortDescriptor", ascending: false)
users = searchText.isEmpty ? userObjects : userObjects.filter("name contains[cd] %@", searchText)
filteredContacts = searchText.isEmpty ? contacts : contacts.filter({ (CNContact) -> Bool in
let contactFullName = CNContact.givenName.lowercased() + " " + CNContact.familyName.lowercased()
return contactFullName.lowercased().contains(searchText.lowercased())
})
UIView.transition(with: tableView, duration: 0.15, options: .transitionCrossDissolve, animations: {
self.tableView.reloadData()
}, completion: nil)
}
}
extension ContactsController { /* hiding keyboard */
override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if #available(iOS 11.0, *) {
searchContactsController?.resignFirstResponder()
searchContactsController?.searchBar.resignFirstResponder()
} else {
searchBar?.resignFirstResponder()
}
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if #available(iOS 11.0, *) {
searchContactsController?.searchBar.endEditing(true)
} else {
self.searchBar?.endEditing(true)
}
}
}
|
gpl-3.0
|
d59177a1fc709a846b5e9538608becfe
| 33.253521 | 110 | 0.725329 | 4.873747 | false | false | false | false |
ainopara/Stage1st-Reader
|
Stage1st/View/Toast.swift
|
1
|
5432
|
//
// Toast.swift
// Stage1st
//
// Created by Zheng Li on 1/11/17.
// Copyright © 2017 Renaissance. All rights reserved.
//
import Ainoaibo
import SnapKit
class Toast: UIWindow {
enum State {
case hidden
case appearing
case presenting
case hiding
}
static var shared = Toast(frame: .zero)
let backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .systemThinMaterial))
let textLabel = UILabel(frame: .zero)
let decorationLine = UIView(frame: .zero)
var state: State = .hidden {
didSet {
S1LogDebug("\(state)")
}
}
var currentHidingToken = ""
override init(frame: CGRect) {
var statusBarFrame = UIApplication.shared.statusBarFrame
statusBarFrame.size.height = statusBarFrame.height + 44.0
super.init(frame: statusBarFrame)
addSubview(backgroundView)
backgroundView.snp.makeConstraints { (make) in
make.edges.equalTo(self)
}
textLabel.textAlignment = .center
textLabel.textColor = AppEnvironment.current.colorManager.colorForKey("reply.text")
backgroundView.contentView.addSubview(textLabel)
textLabel.snp.makeConstraints { (make) in
make.leading.trailing.bottom.equalTo(backgroundView.contentView)
make.height.equalTo(44.0)
}
decorationLine.backgroundColor = AppEnvironment.current.colorManager.colorForKey("reply.text")
addSubview(decorationLine)
decorationLine.snp.makeConstraints { (make) in
make.leading.trailing.bottom.equalTo(self)
make.height.equalTo(1.0 / UIScreen.main.scale)
}
windowLevel = UIWindow.Level.statusBar - 1.0
NotificationCenter.default.addObserver(self,
selector: #selector(didReceiveStatusBarFrameWillChangeNotification(_:)),
name: UIApplication.willChangeStatusBarFrameNotification,
object: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func post(message: String, duration: Duration = .forever, animated: Bool = true) {
makeKeyAndVisible()
self.overrideUserInterfaceStyle = AppEnvironment.current.colorManager.resolvedUserInterfaceStyle.value
switch state {
case .presenting:
textLabel.text = message
hide(after: duration, animated: animated)
case .hidden:
textLabel.text = message
isHidden = false
if animated {
self.state = .appearing
UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 10.0, options: [], animations: {
self.alpha = 1.0
}) { [weak self] (_) in
guard let strongSelf = self else { return }
strongSelf.state = .presenting
strongSelf.hide(after: duration, animated: animated)
}
} else {
self.alpha = 1.0
self.state = .presenting
hide(after: duration, animated: animated)
}
default:
S1LogError("missed \(state)")
}
}
private func hide(after duration: Duration, animated: Bool) {
if case .second(let time) = duration {
let token = UUID().uuidString
self.currentHidingToken = token
DispatchQueue.main.asyncAfter(deadline: .now() + time) { [weak self] in
guard let strongSelf = self else { return }
guard strongSelf.currentHidingToken == token else { return }
strongSelf.hide(animated: animated)
}
}
}
func hide(animated: Bool = true) {
guard state == .presenting || state == .appearing else {
S1LogWarn("Ignoring message hud hide operation with state: \(state)")
return
}
currentHidingToken = ""
if animated {
self.state = .hiding
UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: [], animations: {
self.alpha = 0.0
}, completion: { [weak self] (_) in
guard let strongSelf = self else { return }
strongSelf.state = .hidden
strongSelf.isHidden = true
})
} else {
self.alpha = 0.0
state = .hidden
isHidden = true
}
}
enum Duration: ExpressibleByFloatLiteral {
case second(TimeInterval)
case forever
public init(floatLiteral value: Double) {
self = .second(value)
}
}
@objc func didReceiveStatusBarFrameWillChangeNotification(_ notification: Notification?) {
guard let newFrame = notification?.userInfo?[UIApplication.statusBarFrameUserInfoKey] as? CGRect else {
return
}
let finalFrame = mutate(newFrame) { (value: inout CGRect) in
value.size.height += 44.0
}
UIView.animate(withDuration: 0.3) {
self.frame = finalFrame
self.setNeedsLayout()
self.layoutIfNeeded()
}
}
}
|
bsd-3-clause
|
ffea1e4771b2158b5bd84ec326877968
| 33.157233 | 146 | 0.578162 | 5.066231 | false | false | false | false |
louisdh/lioness
|
Sources/Lioness/AST/Nodes/FunctionNode.swift
|
1
|
3819
|
//
// FunctionNode.swift
// Lioness
//
// Created by Louis D'hauwe on 09/10/2016.
// Copyright © 2016 - 2017 Silver Fox. All rights reserved.
//
import Foundation
public struct FunctionNode: ASTNode {
public let prototype: FunctionPrototypeNode
public let body: BodyNode
public init(prototype: FunctionPrototypeNode, body: BodyNode) {
self.prototype = prototype
self.body = body
}
public func compile(with ctx: BytecodeCompiler, in parent: ASTNode?) throws -> BytecodeBody {
var bytecode = BytecodeBody()
ctx.enterNewScope()
let headerIndex = ctx.nextIndexLabel()
let functionId = ctx.getFunctionId(for: self)
let exitId = try ctx.getExitScopeFunctionId(for: self)
let headerComment = "\(prototype.name)(\(prototype.argumentNames.joined(separator: ", ")))"
let headerInstruction = BytecodeInstruction(label: headerIndex, type: .virtualHeader, arguments: [.index(functionId)], comment: headerComment)
bytecode.append(headerInstruction)
let skipExitInstrLabel = ctx.nextIndexLabel()
let cleanupFunctionCallInstrLabel = ctx.nextIndexLabel()
let exitFunctionInstrLabel = ctx.nextIndexLabel()
ctx.pushFunctionExit(cleanupFunctionCallInstrLabel)
let compiledFunction = try compileFunction(with: ctx)
let exitHeaderLabel = ctx.nextIndexLabel()
let exitHeaderInstruction = BytecodeInstruction(label: exitHeaderLabel, type: .privateVirtualHeader, arguments: [.index(exitId)], comment: "cleanup_\(prototype.name)")
ctx.popFunctionExit()
ctx.addCleanupRegistersToCurrentScope()
let cleanupInstructions = ctx.cleanupRegisterInstructions()
try ctx.leaveCurrentScope()
let cleanupEndLabel = ctx.nextIndexLabel()
let skipExitInstruction = BytecodeInstruction(label: skipExitInstrLabel, type: .skipPast, arguments: [.index(exitFunctionInstrLabel)], comment: "skip exit instruction")
bytecode.append(skipExitInstruction)
let invokeInstruction = BytecodeInstruction(label: cleanupFunctionCallInstrLabel, type: .invokeVirtual, arguments: [.index(exitId)], comment: "cleanup_\(prototype.name)()")
bytecode.append(invokeInstruction)
let exitFunctionInstruction = BytecodeInstruction(label: exitFunctionInstrLabel, type: .exitVirtual, comment: "exit function")
bytecode.append(exitFunctionInstruction)
bytecode.append(contentsOf: compiledFunction)
// Cleanup
bytecode.append(exitHeaderInstruction)
bytecode.append(contentsOf: cleanupInstructions)
bytecode.append(BytecodeInstruction(label: cleanupEndLabel, type: .privateVirtualEnd))
//
let endLabel = ctx.nextIndexLabel()
bytecode.append(BytecodeInstruction(label: endLabel, type: .virtualEnd))
return bytecode
}
private func compileFunction(with ctx: BytecodeCompiler) throws -> BytecodeBody {
var bytecode = BytecodeBody()
for arg in prototype.argumentNames.reversed() {
let label = ctx.nextIndexLabel()
let (varReg, _) = ctx.getRegister(for: arg)
let instruction = BytecodeInstruction(label: label, type: .registerStore, arguments: [.index(varReg)], comment: "\(arg)")
bytecode.append(instruction)
}
bytecode.append(contentsOf: try body.compile(with: ctx, in: self))
if !prototype.returns {
let returnNode = ReturnNode()
bytecode.append(contentsOf: try returnNode.compile(with: ctx, in: self))
}
return bytecode
}
public var childNodes: [ASTNode] {
return [prototype, body]
}
public var description: String {
var str = "FunctionNode(prototype: \(prototype), "
str += "\n \(body.description)"
return str + ")"
}
public var nodeDescription: String? {
return "\(prototype.name)(\(prototype.argumentNames.joined(separator: ", ")))"
}
public var descriptionChildNodes: [ASTChildNode] {
var children = [ASTChildNode]()
children.append(contentsOf: body.descriptionChildNodes)
return children
}
}
|
mit
|
03f590b8fa0bb81b60e3441b445ab4bb
| 27.073529 | 174 | 0.752226 | 3.754179 | false | false | false | false |
kimseongrim/KimSampleCode
|
SCCustomView/CustomView/MyView.swift
|
1
|
3106
|
//
// MyView.swift
// CSCustomView
//
// Created by 金成林 on 15/1/25.
// Copyright (c) 2015年 Kim. All rights reserved.
//
import UIKit
@IBDesignable
class MyView: UIView {
/*******************************
制作方法
File > New > Target... > Framework & Library > Cocoa Touch Framework
storyboard拖拽View到面板上,选择View 后选择Custom Class 指向MyView
*******************************/
/*******************************
View Layer
*******************************/
@IBInspectable var viewBorderWidth: CGFloat = 6 {
didSet {
layer.borderWidth = viewBorderWidth
}
}
@IBInspectable var viewBorderColor: UIColor = UIColor.redColor() {
didSet {
layer.borderColor = viewBorderColor.CGColor
}
}
@IBInspectable var viewCornerRadius: CGFloat = 10 {
didSet {
layer.cornerRadius = viewCornerRadius
}
}
func setCustomLayer() {
// 初始化界面数据
layer.borderWidth = viewBorderWidth
layer.borderColor = viewBorderColor.CGColor
layer.cornerRadius = viewCornerRadius
}
/*******************************
Add custom view
*******************************/
var myButton: UIButton!
@IBInspectable var buttonTitle: String = "Button" {
didSet {
myButton.setTitle(buttonTitle, forState: UIControlState.Normal)
}
}
@IBInspectable var buttonTitleColor: UIColor = UIColor.blackColor() {
didSet {
myButton.setTitleColor(buttonTitleColor, forState: UIControlState.Normal)
}
}
@IBInspectable var buttonFrame: CGRect = CGRectMake(0, 0, 80, 30) {
didSet {
myButton.frame = buttonFrame
}
}
func addCustomButton() {
// 初始化界面数据
myButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
myButton.frame = buttonFrame
myButton.setTitle(buttonTitle, forState: UIControlState.Normal)
myButton.setTitleColor(buttonTitleColor, forState: UIControlState.Normal)
addSubview(myButton)
}
/*******************************
Init
*******************************/
override init(frame: CGRect) {
// call super initializer
super.init(frame: frame)
setCustomLayer()
addCustomButton()
println("init")
}
// 为什么写 required 查看SCSwift 中为什么写 required init(coder aDecoder: NSCoder)
required init(coder aDecoder: NSCoder) {
// call super initializer
super.init(coder: aDecoder)
setCustomLayer()
addCustomButton()
println("Decoder")
}
override func layoutSubviews() {
super.layoutSubviews()
println("layoutSubviews")
}
override func awakeFromNib() {
super.awakeFromNib()
println("awakeFromNib")
}
}
|
gpl-2.0
|
52e4b94ab4dc369ff37d6b15b84ca452
| 25.429825 | 85 | 0.530212 | 5.446655 | false | false | false | false |
howardhsien/Mr-Ride-iOS
|
Mr-Ride/Mr-Ride/Controller/MapViewController.swift
|
1
|
4177
|
//
// MapViewController.swift
// Mr-Ride
//
// Created by howard hsien on 2016/5/31.
// Copyright © 2016年 AppWorks School Hsien. All rights reserved.
//
import UIKit
import MapKit
class MapViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
var regionBoundingRect :MKMapRect?
override func viewDidLoad() {
super.viewDidLoad()
setupMapViewStyle()
setupMap()
}
func setupMapViewStyle() {
view.backgroundColor = UIColor.clearColor()
mapView.layer.cornerRadius = 10
}
func setupMap(){
mapView.delegate = self
mapView.showsUserLocation = true
}
func invalidateUserLocation(){
mapView.showsUserLocation = false
}
func showMapAnnotations(){
mapView.showAnnotations(mapView.annotations, animated: false)
}
func showUserLocation(coordinate: CLLocationCoordinate2D){
let span = MKCoordinateSpanMake(0.005, 0.005)
let region = MKCoordinateRegion(center: coordinate , span: span)
mapView.setRegion(region, animated: true)
}
//TODO: show map poly line sometimes not correct
func addMapPolyline(coordinates coords: UnsafeMutablePointer<CLLocationCoordinate2D>, count: Int){
let polyline = MKPolyline(coordinates: coords, count: count)
// regionBoundingRect = polyline.boundingMapRect
mapView.addOverlay(polyline)
}
func setMapRect(coordinates coords: UnsafeMutablePointer<CLLocationCoordinate2D>, count: Int){
let polyline = MKPolyline(coordinates: coords, count: count)
regionBoundingRect = polyline.boundingMapRect
}
func showMapPolyline() {
if regionBoundingRect != nil{
let edgeInset = UIEdgeInsetsMake(150, 150, 150, 150)
mapView.setVisibleMapRect(regionBoundingRect!,edgePadding: edgeInset ,animated: true)
}
else{
print(classDebugInfo+"showMapPolyline failed")
}
}
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
if overlay is MKPolyline {
polylineRenderer.strokeColor = UIColor.blueColor()
polylineRenderer.lineWidth = 5
return polylineRenderer
}
return polylineRenderer
}
func overlayBoundingMapRect(coords coords: [CLLocationCoordinate2D])-> MKMapRect {
var leftMostLongitude:CLLocationDegrees = 180
var rightMostLongitude:CLLocationDegrees = -180
var topMostLatitude:CLLocationDegrees = -90
var bottomMostLatitude:CLLocationDegrees = 90
for coord in coords{
if coord.longitude < leftMostLongitude{ leftMostLongitude = coord.longitude}
if coord.longitude > rightMostLongitude{ rightMostLongitude = coord.longitude}
if coord.latitude > topMostLatitude { topMostLatitude = coord.latitude }
if coord.latitude < bottomMostLatitude { bottomMostLatitude = coord.latitude}
}
let overlayTopLeftCoordinate = CLLocationCoordinate2D(latitude: topMostLatitude, longitude: leftMostLongitude)
let overlayTopRightCoordinate = CLLocationCoordinate2D(latitude: topMostLatitude, longitude: rightMostLongitude)
let overlayBottomLeftCoordinate = CLLocationCoordinate2D(latitude: bottomMostLatitude, longitude: leftMostLongitude)
let topLeft = MKMapPointForCoordinate(overlayTopLeftCoordinate)
let topRight = MKMapPointForCoordinate(overlayTopRightCoordinate)
let bottomLeft = MKMapPointForCoordinate(overlayBottomLeftCoordinate)
print(classDebugInfo+" topleft:\(topLeft) topRight:\(topRight) bottomLeft:\(bottomLeft)" )
return MKMapRectMake(topLeft.x,
topLeft.y,
fabs(topLeft.x-topRight.x),
fabs(topLeft.y - bottomLeft.y))
}
}
|
mit
|
1ca4f300a3b01aa534a007b25f3e5ffd
| 33.213115 | 124 | 0.658361 | 5.470511 | false | false | false | false |
piv199/LocalisysChat
|
LocalisysChat/Sources/Modules/Common/Chat/Components/Messages/BubbleMessage/Common/LocalisysChatBubbleMessageView.swift
|
1
|
4295
|
//
// LocalisysChatBubbleMessageView.swift
// LocalisysChat
//
// Created by Olexii Pyvovarov on 6/30/17.
// Copyright © 2017 Olexii Pyvovarov. All rights reserved.
//
import UIKit
public enum LocalisysChatMessageOwner {
case me, stranger
}
fileprivate enum LocalisysChatBubbleAlignment {
case left, right
}
fileprivate extension LocalisysChatMessageOwner {
var substrateBackgroundColor: UIColor {
switch self {
case .me: return UIColor(red: 93/255.0, green: 179/255.0, blue: 1.0, alpha: 0.5)
case .stranger: return UIColor(white: 0.83, alpha: 0.5)
}
}
var alignment: LocalisysChatBubbleAlignment {
switch self {
case .me: return .right
case .stranger: return .left
}
}
}
public class LocalisysChatBubbleMessageView: LocalisysChatMessageView {
public dynamic var bubbleMaxWidthPercent: CGFloat = 0.75
public dynamic var bubbleInsets = UIEdgeInsets(top: 3.0, left: 12.0, bottom: 3.0, right: 12.0)
// MARK: - UI
var mainView: LocalisysChatBubbleMessageMainView = LocalisysChatBubbleMessageMainView() {
willSet { mainView.removeFromSuperview() }
didSet { addSubview(mainView) }
}
// MARK: - Lifecycle
public override init(frame: CGRect = .zero) {
super.init(frame: frame)
setupInitialState()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupInitialState()
}
public init(mainView: LocalisysChatBubbleMessageMainView, frame: CGRect = .zero) {
super.init(frame: frame)
self.mainView = mainView
setupInitialState()
}
// MARK: - Setup & Configuration
fileprivate func setupInitialState() {
backgroundColor = .clear
addSubview(mainView)
}
// MARK: - Public properties
public var owner: LocalisysChatMessageOwner = .me {
didSet { layoutSubviews() }
}
// MARK: - Layout
public override func sizeThatFits(_ size: CGSize) -> CGSize {
let estimatedMainViewSize = mainView.sizeThatFits(.init(width: size.width * bubbleMaxWidthPercent, height: size.height))
return CGSize(width: estimatedMainViewSize.width + bubbleInsets.horizontal,
height: estimatedMainViewSize.height + bubbleInsets.vertical)
}
public override func layoutSubviews() {
super.layoutSubviews()
let estimatedMainViewSize = mainView.sizeThatFits(.init(width: bounds.width * bubbleMaxWidthPercent, height: bounds.height))
print("estimatedMainViewSize \(estimatedMainViewSize)")
print("bounds \(bounds)")
let rect: CGRect
switch owner.alignment {
case .left: rect = CGRect(x: bubbleInsets.left, y: bubbleInsets.top,
width: estimatedMainViewSize.width, height: estimatedMainViewSize.height)
case .right: rect = CGRect(x: bounds.width - estimatedMainViewSize.width - bubbleInsets.right,
y: bubbleInsets.top,
width: estimatedMainViewSize.width,
height: estimatedMainViewSize.height)
}
mainView.frame = rect
mainView.layoutSubviews()
setNeedsDisplay()
}
// MARK: - Drawing
public override func draw(_ rect: CGRect) {
super.draw(rect)
guard let canvas = UIGraphicsGetCurrentContext() else { return }
drawSubstrate(canvas: canvas)
}
fileprivate func drawSubstrate(canvas: CGContext) {
let rect: CGRect
switch owner.alignment {
case .left: rect = CGRect(x: bubbleInsets.left, y: bubbleInsets.top,
width: mainView.bounds.width, height: bounds.height - bubbleInsets.vertical)
case .right: rect = CGRect(x: bounds.width - bubbleInsets.right - mainView.bounds.width, y: bubbleInsets.top,
width: mainView.bounds.width, height: bounds.height - bubbleInsets.vertical)
}
canvas.addPath(UIBezierPath(roundedRect: rect, cornerRadius: 12.5).cgPath)
canvas.setFillColor(owner.substrateBackgroundColor.cgColor)
canvas.fillPath()
}
}
extension UIEdgeInsets {
static func +(_ lhs: UIEdgeInsets, _ rhs: UIEdgeInsets) -> UIEdgeInsets {
return UIEdgeInsets(top: lhs.top + rhs.top,
left: lhs.left + rhs.left,
bottom: lhs.bottom + rhs.bottom,
right: lhs.right + rhs.right)
}
}
|
unlicense
|
96170ccde858ca326aa7565f8a5b5899
| 30.115942 | 128 | 0.675361 | 4.298298 | false | false | false | false |
ikemai/ScaledVisibleCellsCollectionView
|
ScaledVisibleCellsCollectionView/ScaledVisibleCellsCollectionView.swift
|
1
|
6185
|
//
// ScaledVisibleCellsCollectionView.swift
// ScaledVisibleCellsCollectionView
//
// Created by Mai Ikeda on 2015/08/22.
// Copyright (c) 2015年 mai_ikeda. All rights reserved.
//
import UIKit
public enum SC_ScaledPattern {
case HorizontalCenter
case HorizontalLeft
case HorizontalRight
case VerticalCenter
case VerticalBottom
case VerticalTop
}
public class ScaledVisibleCellsCollectionView {
static let sharedInstance = ScaledVisibleCellsCollectionView()
var maxScale: CGFloat = 1.0
var minScale: CGFloat = 0.5
var maxAlpha: CGFloat = 1.0
var minAlpha: CGFloat = 0.5
var scaledPattern: SC_ScaledPattern = .VerticalCenter
}
extension UICollectionView {
/**
Please always set
*/
public func setScaledDesginParam(scaledPattern pattern: SC_ScaledPattern, maxScale: CGFloat, minScale: CGFloat, maxAlpha: CGFloat, minAlpha: CGFloat) {
ScaledVisibleCellsCollectionView.sharedInstance.scaledPattern = pattern
ScaledVisibleCellsCollectionView.sharedInstance.maxScale = maxScale
ScaledVisibleCellsCollectionView.sharedInstance.minScale = minScale
ScaledVisibleCellsCollectionView.sharedInstance.maxAlpha = maxAlpha
ScaledVisibleCellsCollectionView.sharedInstance.minAlpha = minAlpha
}
/**
Please call at any time
*/
public func scaledVisibleCells() {
switch ScaledVisibleCellsCollectionView.sharedInstance.scaledPattern {
case .HorizontalCenter, .HorizontalLeft, .HorizontalRight:
scaleCellsForHorizontalScroll(visibleCells())
break
case .VerticalCenter, .VerticalTop, .VerticalBottom:
self.scaleCellsForVerticalScroll(visibleCells())
break
}
}
}
extension UICollectionView {
private func scaleCellsForHorizontalScroll(visibleCells: [UICollectionViewCell]) {
let scalingAreaWidth = bounds.width / 2
let maximumScalingAreaWidth = (bounds.width / 2 - scalingAreaWidth) / 2
for cell in visibleCells {
var distanceFromMainPosition: CGFloat = 0
switch ScaledVisibleCellsCollectionView.sharedInstance.scaledPattern {
case .HorizontalCenter:
distanceFromMainPosition = horizontalCenter(cell)
break
case .HorizontalLeft:
distanceFromMainPosition = abs(cell.frame.midX - contentOffset.x - (cell.bounds.width / 2))
break
case .HorizontalRight:
distanceFromMainPosition = abs(bounds.width / 2 - (cell.frame.midX - contentOffset.x) + (cell.bounds.width / 2))
break
default:
return
}
let preferredAry = scaleCells(distanceFromMainPosition, maximumScalingArea: maximumScalingAreaWidth, scalingArea: scalingAreaWidth)
let preferredScale = preferredAry[0]
let preferredAlpha = preferredAry[1]
cell.transform = CGAffineTransformMakeScale(preferredScale, preferredScale)
cell.alpha = preferredAlpha
}
}
private func scaleCellsForVerticalScroll(visibleCells: [UICollectionViewCell]) {
let scalingAreaHeight = bounds.height / 2
let maximumScalingAreaHeight = (bounds.height / 2 - scalingAreaHeight) / 2
for cell in visibleCells {
var distanceFromMainPosition: CGFloat = 0
switch ScaledVisibleCellsCollectionView.sharedInstance.scaledPattern {
case .VerticalCenter:
distanceFromMainPosition = verticalCenter(cell)
break
case .VerticalBottom:
distanceFromMainPosition = abs(bounds.height - (cell.frame.midY - contentOffset.y + (cell.bounds.height / 2)))
break
case .VerticalTop:
distanceFromMainPosition = abs(cell.frame.midY - contentOffset.y - (cell.bounds.height / 2))
break
default:
return
}
let preferredAry = scaleCells(distanceFromMainPosition, maximumScalingArea: maximumScalingAreaHeight, scalingArea: scalingAreaHeight)
let preferredScale = preferredAry[0]
let preferredAlpha = preferredAry[1]
cell.transform = CGAffineTransformMakeScale(preferredScale, preferredScale)
cell.alpha = preferredAlpha
}
}
private func scaleCells(distanceFromMainPosition: CGFloat, maximumScalingArea: CGFloat, scalingArea: CGFloat) -> [CGFloat] {
var preferredScale: CGFloat = 0.0
var preferredAlpha: CGFloat = 0.0
let maxScale = ScaledVisibleCellsCollectionView.sharedInstance.maxScale
let minScale = ScaledVisibleCellsCollectionView.sharedInstance.minScale
let maxAlpha = ScaledVisibleCellsCollectionView.sharedInstance.maxAlpha
let minAlpha = ScaledVisibleCellsCollectionView.sharedInstance.minAlpha
if distanceFromMainPosition < maximumScalingArea {
// cell in maximum-scaling area
preferredScale = maxScale
preferredAlpha = maxAlpha
} else if distanceFromMainPosition < (maximumScalingArea + scalingArea) {
// cell in scaling area
let multiplier = abs((distanceFromMainPosition - maximumScalingArea) / scalingArea)
preferredScale = maxScale - multiplier * (maxScale - minScale)
preferredAlpha = maxAlpha - multiplier * (maxAlpha - minAlpha)
} else {
// cell in minimum-scaling area
preferredScale = minScale
preferredAlpha = minAlpha
}
return [ preferredScale, preferredAlpha ]
}
}
extension UICollectionView {
private func horizontalCenter(cell: UICollectionViewCell)-> CGFloat {
return abs(bounds.width / 2 - (cell.frame.midX - contentOffset.x))
}
private func verticalCenter(cell: UICollectionViewCell)-> CGFloat {
return abs(bounds.height / 2 - (cell.frame.midY - contentOffset.y))
}
}
|
mit
|
da560eb147b0a4c7c88ea8a2cd6e370e
| 37.893082 | 155 | 0.657771 | 5.40472 | false | false | false | false |
iTSangarDEV/SwiftPlayer
|
Example/SwiftPlayer/QueueTableViewController.swift
|
1
|
4361
|
//
// QueueTableViewController.swift
// SwiftPlayer
//
// Created by Ítalo Sangar on 4/18/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import SwiftPlayer
import AlamofireImage
// MARK: - Section Enum
enum TrackSection: Int {
case NowPlaying = 0
case Next = 1
case Resume = 2
var sections: Int {
return isNext ? 3 : 2
}
var rows: Int {
switch self {
case .NowPlaying:
return 1
case .Next:
return isNext ? SwiftPlayer.nextTracks().count : SwiftPlayer.mainTracks().count
case .Resume:
return SwiftPlayer.mainTracks().count
}
}
var title: String {
switch self {
case .NowPlaying:
return " NOW PLAYING"
case .Next:
let songs = SwiftPlayer.nextTracks().count > 1 ? "SONGS" : "SONG"
return isNext ? " UP NEXT: \(SwiftPlayer.nextTracks().count) \(songs)" : " UP NEXT: FROM \(albumName)"
case .Resume:
return " RESUME: \(albumName)"
}
}
func value(row: Int) -> PlayerTrack? {
switch self {
case .NowPlaying:
if let index = SwiftPlayer.currentTrackIndex() {
return SwiftPlayer.trackAtIndex(index)
}
return nil
case .Next:
return isNext ? SwiftPlayer.nextTracks()[row] : SwiftPlayer.mainTracks()[row]
case .Resume:
return SwiftPlayer.mainTracks()[row]
}
}
func selected(row: Int) {
switch self {
case .NowPlaying:
break
case .Next:
if isNext {
SwiftPlayer.playNextAtIndex(row)
} else {
SwiftPlayer.playMainAtIndex(row)
}
break
case .Resume:
SwiftPlayer.playMainAtIndex(row)
break
}
}
private var albumName: String {
if let name = SwiftPlayer.mainTracks()[0].album?.name {
return name.uppercaseString
} else {
return "Any Album".uppercaseString
}
}
private var isNext: Bool {
return SwiftPlayer.nextTracks().count > 0
}
}
// MARK: - ViewController
class QueueTableViewController: UITableViewController {
var sectionStatus = TrackSection.NowPlaying
override func viewDidLoad() {
super.viewDidLoad()
tableView.reloadData()
SwiftPlayer.queueDelegate(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sectionStatus.sections
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
sectionStatus = TrackSection.init(rawValue: section)!
return sectionStatus.rows
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
sectionStatus = TrackSection.init(rawValue: section)!
return sectionStatus.title
}
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
header.textLabel?.font = UIFont.systemFontOfSize(12, weight: UIFontWeightRegular)
view.tintColor = UIColor.lightGrayColor().colorWithAlphaComponent(0.7)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableView.dequeueReusableCellWithIdentifier("QueueTableViewCell", forIndexPath: indexPath) as! QueueTableViewCell
}
// MARK: Table view delegate
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.respondsToSelector(Selector("setPreservesSuperviewLayoutMargins:")) {
cell.layoutMargins = UIEdgeInsetsZero
cell.preservesSuperviewLayoutMargins = false
}
let cell = cell as! QueueTableViewCell
sectionStatus = TrackSection.init(rawValue: indexPath.section)!
cell.track = sectionStatus.value(indexPath.row)
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
sectionStatus = TrackSection.init(rawValue: indexPath.section)!
sectionStatus.selected(indexPath.row)
}
}
extension QueueTableViewController: SwiftPlayerQueueDelegate {
func queueUpdated() {
tableView.reloadData()
}
}
|
mit
|
c3e86ee3b1d5332fe959c2b59f01be85
| 26.24375 | 132 | 0.695343 | 4.602957 | false | false | false | false |
mitochrome/complex-gestures-demo
|
apps/GestureRecognizer/Carthage/Checkouts/RxSwift/Tests/RxSwiftTests/Observable+MapTests.swift
|
4
|
17884
|
//
// Observable+MapTests.swift
// Tests
//
// Created by Krunoslav Zaher on 4/29/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
import XCTest
import RxSwift
import RxTest
class ObservableMapTest : RxTest {
}
extension ObservableMapTest {
func testMap_Never() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
])
let res = scheduler.start { xs.map { $0 * 2 } }
let correctMessages: [Recorded<Event<Int>>] = [
]
let correctSubscriptions = [
Subscription(200, 1000)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap_Empty() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
completed(300)
])
let res = scheduler.start { xs.map { $0 * 2 } }
let correctMessages = [
completed(300, Int.self)
]
let correctSubscriptions = [
Subscription(200, 300)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap_Range() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
next(220, 1),
next(230, 2),
next(240, 4),
completed(300)
])
let res = scheduler.start { xs.map { $0 * 2 } }
let correctMessages = [
next(210, 0 * 2),
next(220, 1 * 2),
next(230, 2 * 2),
next(240, 4 * 2),
completed(300)
]
let correctSubscriptions = [
Subscription(200, 300)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap_Error() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
next(220, 1),
next(230, 2),
next(240, 4),
error(300, testError)
])
let res = scheduler.start { xs.map { $0 * 2 } }
let correctMessages = [
next(210, 0 * 2),
next(220, 1 * 2),
next(230, 2 * 2),
next(240, 4 * 2),
error(300, testError)
]
let correctSubscriptions = [
Subscription(200, 300)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap_Dispose() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
next(220, 1),
next(230, 2),
next(240, 4),
error(300, testError)
])
let res = scheduler.start(disposed: 290) { xs.map { $0 * 2 } }
let correctMessages = [
next(210, 0 * 2),
next(220, 1 * 2),
next(230, 2 * 2),
next(240, 4 * 2),
]
let correctSubscriptions = [
Subscription(200, 290)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap_SelectorThrows() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
next(220, 1),
next(230, 2),
next(240, 4),
error(300, testError)
])
let res = scheduler.start { xs.map { x throws -> Int in if x < 2 { return x * 2 } else { throw testError } } }
let correctMessages = [
next(210, 0 * 2),
next(220, 1 * 2),
error(230, testError)
]
let correctSubscriptions = [
Subscription(200, 230)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap1_Never() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
])
let res = scheduler.start { xs.mapWithIndex { ($0 + $1) * 2 } }
let correctMessages: [Recorded<Event<Int>>] = [
]
let correctSubscriptions = [
Subscription(200, 1000)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap1_Empty() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
completed(300)
])
let res = scheduler.start { xs.mapWithIndex { ($0 + $1) * 2 } }
let correctMessages = [
completed(300, Int.self)
]
let correctSubscriptions = [
Subscription(200, 300)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap1_Range() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 5),
next(220, 6),
next(230, 7),
next(240, 8),
completed(300)
])
let res = scheduler.start { xs.mapWithIndex { ($0 + $1) * 2 } }
let correctMessages = [
next(210, (5 + 0) * 2),
next(220, (6 + 1) * 2),
next(230, (7 + 2) * 2),
next(240, (8 + 3) * 2),
completed(300)
]
let correctSubscriptions = [
Subscription(200, 300)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap1_Error() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 5),
next(220, 6),
next(230, 7),
next(240, 8),
error(300, testError)
])
let res = scheduler.start { xs.mapWithIndex { ($0 + $1) * 2 } }
let correctMessages = [
next(210, (5 + 0) * 2),
next(220, (6 + 1) * 2),
next(230, (7 + 2) * 2),
next(240, (8 + 3) * 2),
error(300, testError)
]
let correctSubscriptions = [
Subscription(200, 300)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap1_Dispose() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 5),
next(220, 6),
next(230, 7),
next(240, 8),
error(300, testError)
])
let res = scheduler.start(disposed: 290) { xs.mapWithIndex { ($0 + $1) * 2 } }
let correctMessages = [
next(210, (5 + 0) * 2),
next(220, (6 + 1) * 2),
next(230, (7 + 2) * 2),
next(240, (8 + 3) * 2),
]
let correctSubscriptions = [
Subscription(200, 290)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap1_SelectorThrows() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 5),
next(220, 6),
next(230, 7),
next(240, 8),
error(300, testError)
])
let res = scheduler.start { xs.mapWithIndex { x, i throws -> Int in if x < 7 { return ((x + i) * 2) } else { throw testError } } }
let correctMessages = [
next(210, (5 + 0) * 2),
next(220, (6 + 1) * 2),
error(230, testError)
]
let correctSubscriptions = [
Subscription(200, 230)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap_DisposeOnCompleted() {
_ = Observable.just("A")
.map { a in
return a
}
.subscribe(onNext: { _ in
})
}
func testMap1_DisposeOnCompleted() {
_ = Observable.just("A")
.mapWithIndex { (a, i) in
return a
}
.subscribe(onNext: { _ in
})
}
#if TRACE_RESOURCES
func testMapReleasesResourcesOnComplete() {
_ = Observable<Int>.just(1).map { _ in true }.subscribe()
}
func testMap1ReleasesResourcesOnError() {
_ = Observable<Int>.error(testError).map { _ in true }.subscribe()
}
func testMap2ReleasesResourcesOnError() {
_ = Observable<Int>.just(1).map { _ -> Bool in throw testError }.subscribe()
}
func testMapWithIndexReleasesResourcesOnComplete() {
_ = Observable<Int>.just(1).mapWithIndex { _, _ in true }.subscribe()
}
func testMapWithIndex1ReleasesResourcesOnError() {
_ = Observable<Int>.error(testError).mapWithIndex { _, _ in true }.subscribe()
}
func testMapWithIndex2ReleasesResourcesOnError() {
_ = Observable<Int>.just(1).mapWithIndex { _, _ -> Bool in throw testError }.subscribe()
}
#endif
}
// MARK: map compose
extension ObservableMapTest {
func testMapCompose_Never() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
])
let res = scheduler.start { xs.map { $0 * 10 }.map { $0 + 1 } }
let correctMessages: [Recorded<Event<Int>>] = [
]
let correctSubscriptions = [
Subscription(200, 1000)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMapCompose_Empty() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
completed(300)
])
let res = scheduler.start { xs.map { $0 * 10 }.map { $0 + 1 } }
let correctMessages = [
completed(300, Int.self)
]
let correctSubscriptions = [
Subscription(200, 300)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMapCompose_Range() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
next(220, 1),
next(230, 2),
next(240, 4),
completed(300)
])
let res = scheduler.start { xs.map { $0 * 10 }.map { $0 + 1 } }
let correctMessages = [
next(210, 0 * 10 + 1),
next(220, 1 * 10 + 1),
next(230, 2 * 10 + 1),
next(240, 4 * 10 + 1),
completed(300)
]
let correctSubscriptions = [
Subscription(200, 300)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMapCompose_Error() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
next(220, 1),
next(230, 2),
next(240, 4),
error(300, testError)
])
let res = scheduler.start { xs.map { $0 * 10 }.map { $0 + 1 } }
let correctMessages = [
next(210, 0 * 10 + 1),
next(220, 1 * 10 + 1),
next(230, 2 * 10 + 1),
next(240, 4 * 10 + 1),
error(300, testError)
]
let correctSubscriptions = [
Subscription(200, 300)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMapCompose_Dispose() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
next(220, 1),
next(230, 2),
next(240, 4),
error(300, testError)
])
let res = scheduler.start(disposed: 290) { xs.map { $0 * 10 }.map { $0 + 1 } }
let correctMessages = [
next(210, 0 * 10 + 1),
next(220, 1 * 10 + 1),
next(230, 2 * 10 + 1),
next(240, 4 * 10 + 1),
]
let correctSubscriptions = [
Subscription(200, 290)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMapCompose_Selector1Throws() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
next(220, 1),
next(230, 2),
next(240, 4),
error(300, testError)
])
let res = scheduler.start {
xs
.map { x throws -> Int in if x < 2 { return x * 10 } else { throw testError } }
.map { $0 + 1 }
}
let correctMessages = [
next(210, 0 * 10 + 1),
next(220, 1 * 10 + 1),
error(230, testError)
]
let correctSubscriptions = [
Subscription(200, 230)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMapCompose_Selector2Throws() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
next(220, 1),
next(230, 2),
next(240, 4),
error(300, testError)
])
let res = scheduler.start {
xs
.map { $0 * 10 }
.map { x throws -> Int in if x < 20 { return x + 1 } else { throw testError } }
}
let correctMessages = [
next(210, 0 * 10 + 1),
next(220, 1 * 10 + 1),
error(230, testError)
]
let correctSubscriptions = [
Subscription(200, 230)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
#if TRACE_RESOURCES
func testMapCompose_OptimizationIsPerformed() {
let scheduler = TestScheduler(initialClock: 0)
var checked = false
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
])
let res = scheduler.start {
xs
.map { $0 * 10 }
.map { x -> Int in
checked = true
XCTAssertTrue(Resources.numberOfMapOperators == 1)
return x + 1
}
}
let correctMessages = [
next(210, 0 * 10 + 1),
]
let correctSubscriptions = [
Subscription(200, 1000)
]
XCTAssertTrue(checked)
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMapCompose_OptimizationIsNotPerformed() {
let scheduler = TestScheduler(initialClock: 0)
var checked = false
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
])
let res = scheduler.start {
xs
.map { $0 * 10 }
.filter { _ in true }
.map { x -> Int in
checked = true
XCTAssertTrue(Resources.numberOfMapOperators == 2)
return x + 1
}
}
let correctMessages = [
next(210, 0 * 10 + 1),
]
let correctSubscriptions = [
Subscription(200, 1000)
]
XCTAssertTrue(checked)
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
#endif
}
|
mit
|
86009fca38c4b44af9cf799bc7062dd6
| 26.725581 | 138 | 0.485153 | 4.798229 | false | true | false | false |
mcrollin/safecaster
|
safecaster/SCRDashboardViewModel.swift
|
1
|
3077
|
//
// SCRDashboardViewModel.swift
// safecaster
//
// Created by Marc Rollin on 4/10/15.
// Copyright (c) 2015 safecast. All rights reserved.
//
import Foundation
import ReactiveCocoa
import ObjectMapper
class SCRDashboardViewModel: SCRViewModel {
dynamic private(set) var signOut:String!
dynamic private(set) var welcomeMessage:String!
dynamic private(set) var approvedMeasurementCount:String!
dynamic private(set) var importsCount:String!
dynamic private var isAuthenticated:NSNumber!
private(set) var monthlyMeasurementsCounts:[SCRMonthlyMeasurementsCount] = []
lazy var isAuthenticatedUpdated:RACSignal! = {
return self.RACObserve(self, "isAuthenticated")
.filterNil()
.map { return $0.boolValue }
.distinctUntilChanged()
}()
override init() {
super.init()
signOut = "Sign out"
welcomeMessage = "Hi!"
approvedMeasurementCount = "-"
importsCount = "-"
}
}
// MARK: - Reactive signals
extension SCRDashboardViewModel {
func updateUser() {
if let user = SCRUserManager.sharedManager.user {
self.updateUser(user)
user.updateInformation().subscribeNext { _ in
self.updateUser(user)
}
user.updateImports().subscribeNext { _ in
self.updateUser(user)
}
} else {
self.isAuthenticated = NSNumber(bool: false)
}
}
}
// MARK: - Private methods
extension SCRDashboardViewModel {
private func updateUser(user:SCRUser) {
self.isAuthenticated = NSNumber(bool: true)
self.signOut = "Not \(user.name)?"
self.welcomeMessage = "Hi \(user.name)!"
let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
formatter.locale = NSLocale.currentLocale()
if let approvedMeasurementCount = formatter.stringFromNumber(user.approvedMeasurementCount) {
self.approvedMeasurementCount = "\(approvedMeasurementCount)"
}
if let importsCount = formatter.stringFromNumber(user.imports().count) {
self.importsCount = "\(importsCount)"
}
let counts = SCRMonthlyMeasurementsCount.monthlyMeasurementsCounts()
if self.monthlyMeasurementsCountChanged(counts) {
self.monthlyMeasurementsCounts = counts
}
}
private func monthlyMeasurementsCountChanged(counts: [SCRMonthlyMeasurementsCount]) -> Bool {
if self.monthlyMeasurementsCounts.count != counts.count {
return true
}
for i in 0..<counts.count {
if self.monthlyMeasurementsCounts[i].count != counts[i].count
|| self.monthlyMeasurementsCounts[i].month != counts[i].month {
return true
}
}
return false
}
}
|
cc0-1.0
|
7ce703505d0a2e52ed38fab44c34d1e1
| 30.080808 | 101 | 0.60091 | 5.003252 | false | false | false | false |
cuappdev/podcast-ios
|
old/Podcast/DateFormatter+.swift
|
1
|
1683
|
//
// DateFormatter+.swift
// Podcast
//
// Created by Natasha Armbrust on 3/2/17.
// Copyright © 2017 Cornell App Development. All rights reserved.
//
import Foundation
//Acknowledgements: code from CUAppDev Tempo
extension DateFormatter {
@nonobjc static let parsingDateFormatter: DateFormatter = {
$0.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'"
$0.timeZone = TimeZone(secondsFromGMT: 0)
$0.locale = Locale(identifier: "en_US")
return $0
}(DateFormatter())
@nonobjc static let restAPIDateFormatter: DateFormatter = {
$0.dateFormat = "yyyy-MM-dd'T'HH:mm:ss+zz:zz"
$0.timeZone = TimeZone(secondsFromGMT: 0)
$0.locale = Locale(identifier: "en_US")
return $0
}(DateFormatter())
@nonobjc static let simpleDateFormatter: DateFormatter = {
$0.dateFormat = "M.dd.YY"
return $0
}(DateFormatter())
@nonobjc static let yearMonthDayFormatter: DateFormatter = {
$0.dateFormat = "yyyy-MM-dd"
$0.locale = Locale(identifier: "en_US_POSIX")
return $0
}(DateFormatter())
@nonobjc static let slashYearMonthDayFormatter: DateFormatter = {
$0.dateFormat = "yyyy/MM/dd"
$0.locale = Locale(identifier: "en_US_POSIX")
return $0
}(DateFormatter())
@nonobjc static let monthFormatter: DateFormatter = {
$0.dateFormat = "MMM"
return $0
}(DateFormatter())
@nonobjc static let postHistoryDateFormatter: DateFormatter = {
$0.dateFormat = "MMM d, yyyy"
$0.locale = Locale(identifier: "en_US_POSIX")
return $0
}(DateFormatter())
}
|
mit
|
0ad16b81b69ca3390da0344bd9446663
| 29.035714 | 69 | 0.611772 | 3.995249 | false | false | false | false |
szotp/Arrange
|
ArrangeTests/ArrangeTests.swift
|
1
|
7171
|
//
// ArrangeTests.swift
// ArrangeTests
//
// Created by krzat on 29/10/16.
// Copyright © 2016 krzat. All rights reserved.
//
import XCTest
import Arrange
class BigView : UIView {}
extension CGRect {
func assertEqual(to expected : CGRect, file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(self, expected, file:file, line:line)
}
}
class ArrangeTests: 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 testOneToOne(_ arrangement : [ArrangementItem], expected : CGRect, file: StaticString = #file, line: UInt = #line) {
let view = bigView()
let subview = smallView()
view.arrange(arrangement, subview)
view.layoutIfNeeded()
XCTAssertEqual(subview.frame, expected, file:file, line:line)
}
func testPadding() {
testOneToOne([.fill(1)], expected: CGRect(x: 1, y: 1, width: 98, height: 98))
testOneToOne([.fill(-1)], expected: CGRect(x: -1, y: -1, width: 102, height: 102))
testOneToOne([.left(1), .top(1)], expected: CGRect(x: 1, y: 1, width: 10, height: 10))
testOneToOne([.right(1), .bottom(1)], expected: CGRect(x: 89, y: 89, width: 10, height: 10))
}
func testScrollable() {
let view = UIView()
let height = view.heightAnchor.constraint(equalToConstant: 110)
//height.priority = UILayoutPriorityRequired-1
height.isActive = true
let container = bigView().arrange(
[.scrollable],
view
)
let scrollView = container.subviews.first as? UIScrollView
container.layoutIfNeeded()
XCTAssertNotNil(scrollView)
XCTAssertEqual(view.frame, CGRect(x: 0, y: 0, width: 100, height: 110))
XCTAssertEqual(scrollView!.frame, CGRect(x: 0, y: 0, width: 100, height: 100))
XCTAssertTrue(scrollView!.subviews.contains(view.superview!) || scrollView!.subviews.contains(view))
}
func testDefaultStacking() {
let top = smallView()
let middle = unsizedView()
let bottom = smallView()
let container = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)).arrange(
[],
top,
middle,
bottom
)
container.layoutIfNeeded()
XCTAssertEqual(top.frame, CGRect(x: 0, y: 0, width: 100, height: 10))
XCTAssertEqual(middle.frame, CGRect(x: 0, y: 10, width: 100, height: 80))
XCTAssertEqual(bottom.frame, CGRect(x: 0, y: 90, width: 100, height: 10))
}
func bigView() -> UIView {
return BigView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
}
func smallView() -> UIView {
let subview = UIView()
let width = subview.widthAnchor.constraint(equalToConstant: 10)
width.priority = UILayoutPriorityDefaultLow
width.isActive = true
let height = subview.heightAnchor.constraint(equalToConstant: 10)
height.priority = UILayoutPriorityDefaultLow
height.isActive = true
return subview
}
func unsizedView() -> UIView {
return UIView()
}
func testOverlay() {
let a = unsizedView()
let b = unsizedView()
let container = bigView()
container.arrange([.overlaying], a,b)
container.layoutIfNeeded()
XCTAssertEqual(a.frame, container.bounds)
XCTAssertEqual(b.frame, container.bounds)
}
func testEqualize() {
let a = unsizedView()
let b = unsizedView()
let container = bigView()
do {
container.arrange(
[.equalSizes],
a,
b
)
container.layoutIfNeeded()
XCTAssertEqual(a.frame, CGRect(x: 0, y: 0, width: 100, height: 50))
XCTAssertEqual(b.frame, CGRect(x: 0, y: 50, width: 100, height: 50))
}
do {
container.arrange(
[.equalSizes, .horizontal],
a,
b
)
container.layoutIfNeeded()
XCTAssertEqual(a.frame, CGRect(x: 0, y: 0, width: 50, height: 100))
XCTAssertEqual(b.frame, CGRect(x: 50, y: 0, width: 50, height: 100))
}
}
func testCentered() {
testOneToOne(
[.centered],
expected: CGRect(x: 45, y: 45, width: 10, height: 10)
)
testOneToOne(
[.centeredVertically, .left(0)],
expected: CGRect(x: 0, y: 45, width: 10, height: 10)
)
testOneToOne(
[.centeredHorizontally, .top(0)],
expected: CGRect(x: 45, y: 0, width: 10, height: 10)
)
}
func testStyle() {
let view = UILabel().style{
$0.text = "x"
}
XCTAssertEqual(view.text, "x")
}
func testTopAndSides() {
let big = bigView()
let small = smallView()
big.arrange([.topAndSides(0)], small)
big.layoutIfNeeded()
XCTAssertEqual(small.frame, CGRect(x: 0, y: 0, width: 100, height: 10))
}
func testCustomExtension() {
let view = bigView()
view.arrange([.hidden])
assert(view.isHidden)
}
func testViewControllerArrange() {
let viewController = UIViewController()
viewController.view = bigView()
let view = smallView()
viewController.arrange([.topAndSides(0)], view)
viewController.view.layoutIfNeeded()
XCTAssertEqual(view.superview, viewController.view)
XCTAssertEqual(view.frame, CGRect(x: 0, y: 0, width: 100, height: 10))
//smallView should be aligned to layoutGuides, but offsets will not be visible in the test
}
func testCustomAnchor() {
let big = bigView()
let center = smallView()
big.arrange([.centered], center)
let other = smallView()
let closure : Arrangement.Closure = {
$0.bottomAnchor = center.topAnchor
}
big.arrange([.before(closure)], other)
big.layoutIfNeeded()
XCTAssertEqual(other.frame, CGRect(x: 0, y: 0, width: 100, height: 45))
}
func testStackViewCustomization() {
let big = bigView()
let a = smallView()
let b = smallView()
let closure : Arrangement.Closure = {
$0.stackView?.spacing = 20
}
big.arrange([.after(closure), .equalSizes], a, b)
big.layoutIfNeeded()
XCTAssertEqual(a.frame, CGRect(x: 0, y: 0, width: 100, height: 40))
}
}
extension ArrangementItem {
static var hidden : ArrangementItem {
return .after({ context in
context.superview.isHidden = true
})
}
}
|
mit
|
eb5fa08b42a09b677ede372100182ca8
| 28.875 | 125 | 0.562622 | 4.311485 | false | true | false | false |
eviathan/Salt
|
Salt/Models/Grid.swift
|
1
|
457
|
//
// Grid.swift
// Salt
//
// Created by Brian on 03/04/2017.
// Copyright © 2017 Iko. All rights reserved.
//
import Foundation
class Grid {
var snapToGrid: Bool = true
var isTriplet: Bool = false
var isFixed: Bool = true
var zoom: Double = 1.0
}
//<FixedNumerator Value="1" />
//<FixedDenominator Value="16" />
//<GridIntervalPixel Value="20" />
//<Ntoles Value="2" />
//<SnapToGrid Value="true" />
//<Fixed Value="false" />
|
apache-2.0
|
4e90d326f4dcd4bd0a81e5b05cc109e2
| 18 | 46 | 0.620614 | 3.211268 | false | false | false | false |
evgenyneu/Auk
|
Auk/AukPageIndicatorContainer.swift
|
1
|
4110
|
import UIKit
/// View containing a UIPageControl object that shows the dots for present pages.
final class AukPageIndicatorContainer: UIView {
deinit {
pageControl?.removeTarget(self, action: #selector(AukPageIndicatorContainer.didTapPageControl(_:)),
for: UIControl.Event.valueChanged)
}
var didTapPageControlCallback: ((Int)->())?
var pageControl: UIPageControl? {
get {
if subviews.count == 0 { return nil }
return subviews[0] as? UIPageControl
}
}
// Layouts the view, creates and layouts the page control
func setup(_ settings: AukSettings, scrollView: UIScrollView) {
styleContainer(settings)
AukPageIndicatorContainer.layoutContainer(self, settings: settings, scrollView: scrollView)
let pageControl = createPageControl(settings)
AukPageIndicatorContainer.layoutPageControl(pageControl, superview: self, settings: settings)
updateVisibility()
}
// Update the number of pages showing in the page control
func updateNumberOfPages(_ numberOfPages: Int) {
pageControl?.numberOfPages = numberOfPages
updateVisibility()
}
// Update the current page in the page control
func updateCurrentPage(_ currentPageIndex: Int) {
pageControl?.currentPage = currentPageIndex
}
private func styleContainer(_ settings: AukSettings) {
backgroundColor = settings.pageControl.backgroundColor
layer.cornerRadius = CGFloat(settings.pageControl.cornerRadius)
}
private static func layoutContainer(_ pageIndicatorContainer: AukPageIndicatorContainer,
settings: AukSettings, scrollView: UIScrollView) {
if let superview = pageIndicatorContainer.superview {
pageIndicatorContainer.translatesAutoresizingMaskIntoConstraints = false
// Align bottom of the page view indicator with the bottom of the scroll view
iiAutolayoutConstraints.alignSameAttributes(pageIndicatorContainer, toItem: scrollView,
constraintContainer: superview, attribute: NSLayoutConstraint.Attribute.bottom,
margin: CGFloat(-settings.pageControl.marginToScrollViewBottom))
// Center the page view indicator horizontally in relation to the scroll view
iiAutolayoutConstraints.alignSameAttributes(pageIndicatorContainer, toItem: scrollView,
constraintContainer: superview, attribute: NSLayoutConstraint.Attribute.centerX, margin: 0)
}
}
private func createPageControl(_ settings: AukSettings) -> UIPageControl {
let pageControl = UIPageControl()
if #available(*, iOS 9.0) {
// iOS 9+
} else {
// When using right-to-left language, flip the page control horizontally in iOS 8 and earlier.
// That will make it highlight the rightmost dot for the first page.
if RightToLeft.isRightToLeft(self) {
pageControl.transform = CGAffineTransform(scaleX: -1, y: 1)
}
}
pageControl.addTarget(self, action: #selector(AukPageIndicatorContainer.didTapPageControl(_:)),
for: UIControl.Event.valueChanged)
pageControl.pageIndicatorTintColor = settings.pageControl.pageIndicatorTintColor
pageControl.currentPageIndicatorTintColor = settings.pageControl.currentPageIndicatorTintColor
addSubview(pageControl)
return pageControl
}
@objc func didTapPageControl(_ control: UIPageControl) {
if let currentPage = pageControl?.currentPage {
didTapPageControlCallback?(currentPage)
}
}
private static func layoutPageControl(_ pageControl: UIPageControl, superview: UIView,
settings: AukSettings) {
pageControl.translatesAutoresizingMaskIntoConstraints = false
iiAutolayoutConstraints.fillParent(pageControl, parentView: superview,
margin: settings.pageControl.innerPadding.width, vertically: false)
iiAutolayoutConstraints.fillParent(pageControl, parentView: superview,
margin: settings.pageControl.innerPadding.height, vertically: true)
}
private func updateVisibility() {
if let pageControl = pageControl {
self.isHidden = pageControl.numberOfPages < 2
}
}
}
|
mit
|
9c6ae8a7487c7cbec5c574f19d0bd75d
| 36.363636 | 103 | 0.736496 | 5.48 | false | false | false | false |
vi4m/Zewo
|
Modules/Venice/Sources/Venice/FallibleChannel/FallibleChannel.swift
|
1
|
4125
|
import CLibvenice
public struct FallibleChannelGenerator<T> : IteratorProtocol {
internal let channel: FallibleReceivingChannel<T>
public mutating func next() -> ChannelResult<T>? {
return channel.receiveResult()
}
}
public enum ChannelResult<T> {
case value(T)
case error(Error)
public func success(_ closure: (T) -> Void) {
switch self {
case .value(let value): closure(value)
default: break
}
}
public func failure(_ closure: (Error) -> Void) {
switch self {
case .error(let error): closure(error)
default: break
}
}
}
public final class FallibleChannel<T> : Sequence {
private let channel: chan
public var closed: Bool = false
private var buffer: [ChannelResult<T>] = []
public let bufferSize: Int
public convenience init() {
self.init(bufferSize: 0)
}
public init(bufferSize: Int) {
self.bufferSize = bufferSize
self.channel = mill_chmake_(bufferSize, "FallibleChannel init")
}
deinit {
mill_chclose_(channel, "FallibleChannel deinit")
}
/// Reference that can only send values.
public lazy var sendingChannel: FallibleSendingChannel<T> = FallibleSendingChannel(self)
/// Reference that can only receive values.
public lazy var receivingChannel: FallibleReceivingChannel<T> = FallibleReceivingChannel(self)
/// Creates a generator.
public func makeIterator() -> FallibleChannelGenerator<T> {
return FallibleChannelGenerator(channel: receivingChannel)
}
/// Closes the channel. When a channel is closed it cannot receive values anymore.
public func close() {
guard !closed else { return }
closed = true
mill_chdone_(channel, "Channel close")
}
/// Send a result to the channel.
public func send(_ result: ChannelResult<T>) {
if !closed {
buffer.append(result)
mill_chs_(channel, "FallibleChannel sendResult")
}
}
/// Send a value to the channel.
public func send(_ value: T) {
if !closed {
let result = ChannelResult<T>.value(value)
buffer.append(result)
mill_chs_(channel, "FallibleChannel send")
}
}
func send(_ value: T, clause: UnsafeMutableRawPointer, index: Int) {
if !closed {
let result = ChannelResult<T>.value(value)
buffer.append(result)
mill_choose_out_(clause, channel, Int32(index))
}
}
/// Send an error to the channel.
public func send(_ error: Error) {
if !closed {
let result = ChannelResult<T>.error(error)
buffer.append(result)
mill_chs_(channel, "FallibleChannel send")
}
}
func send(_ error: Error, clause: UnsafeMutableRawPointer, index: Int) {
if !closed {
let result = ChannelResult<T>.error(error)
buffer.append(result)
mill_choose_out_(clause, channel, Int32(index))
}
}
/// Receive a value from channel.
@discardableResult
public func receive() throws -> T? {
if closed && buffer.isEmpty {
return nil
}
mill_chr_(channel, "FallibleChannel receive")
if let value = getResultFromBuffer() {
switch value {
case .value(let v): return v
case .error(let e): throw e
}
} else {
return nil
}
}
/// Receive a result from channel.
@discardableResult
public func receiveResult() -> ChannelResult<T>? {
if closed && buffer.isEmpty {
return nil
}
mill_chr_(channel, "FallibleChannel receiveResult")
return getResultFromBuffer()
}
func registerReceive(_ clause: UnsafeMutableRawPointer, index: Int) {
mill_choose_in_(clause, channel, Int32(index))
}
func getResultFromBuffer() -> ChannelResult<T>? {
if closed && buffer.isEmpty {
return nil
}
return buffer.removeFirst()
}
}
|
mit
|
ce1fb8577e06f9ad24ee7b82733d1c7a
| 27.061224 | 98 | 0.594667 | 4.445043 | false | false | false | false |
AimobierCocoaPods/OddityUI
|
Classes/Resources/WaitTipsView/WaitLoadProtcol.swift
|
1
|
4115
|
//
// WaitLoadProtcol.swift
// Journalism
//
// Created by Mister on 16/6/13.
// Copyright © 2016年 aimobier. All rights reserved.
//
import UIKit
import SnapKit
protocol WaitLoadProtcol {}
extension WaitLoadProtcol where Self:UIViewController{
// 显示完成删除不感兴趣的新闻
func showNoInterest(_ imgName:String = "About",title:String="将减少此类推荐",height:CGFloat = 59,width:CGFloat = 178){
let shareNoInterest = NoInterestView(frame: CGRect.zero)
shareNoInterest.alpha = 1
self.view.addSubview(shareNoInterest)
shareNoInterest.imageView.image = UIImage.OddityImageByName(imgName)
shareNoInterest.label.text = title
shareNoInterest.snp_makeConstraints { (make) in
make.height.equalTo(height)
make.width.equalTo(width)
make.center.equalTo(self.view.snp_center)
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: {
UIView.animate(withDuration: 0.5, animations: {
shareNoInterest.alpha = 0
}, completion: { (_) in
shareNoInterest.removeFromSuperview()
})
})
}
}
extension WaitLoadProtcol where Self:NewFeedListViewController{
// 显示等待视图
func showWaitLoadView(){
if self.waitView == nil {
self.waitView = WaitView.shareWaitView
}
self.view.addSubview(self.waitView )
self.waitView.snp.makeConstraints { (make) in
make.margins.equalTo(UIEdgeInsets.zero)
}
}
// 隐藏等待视图
func hiddenWaitLoadView(){
if self.waitView != nil {
self.waitView.removeFromSuperview()
self.waitView = nil
}
}
}
extension WaitLoadProtcol where Self:DetailViewController{
// 显示等待视图
func showWaitLoadView(){
if self.waitView == nil {
self.waitView = WaitView.shareWaitView
}
self.view.addSubview(self.waitView )
self.waitView.snp.makeConstraints { (make) in
make.margins.equalTo(UIEdgeInsets.zero)
}
}
// 隐藏等待视图
func hiddenWaitLoadView(){
if self.waitView != nil {
self.waitView.removeFromSuperview()
self.waitView = nil
}
}
}
extension WaitLoadProtcol where Self:SpecialViewController{
// 显示等待视图
func showWaitLoadView(){
if self.waitView == nil {
self.waitView = WaitView.shareWaitView
}
self.view.addSubview(self.waitView )
self.waitView.snp.makeConstraints { (make) in
make.top.equalTo(64)
make.bottom.equalTo(0)
make.left.equalTo(0)
make.right.equalTo(0)
}
}
// 隐藏等待视图
func hiddenWaitLoadView(){
if self.waitView != nil {
self.waitView.removeFromSuperview()
self.waitView = nil
}
}
}
extension WaitLoadProtcol where Self:AdsWebViewController{
// 显示等待视图
func showWaitLoadView(){
if self.waitView == nil {
self.waitView = WaitView.shareWaitView
}
self.view.addSubview(self.waitView )
self.waitView.snp.makeConstraints { (make) in
make.top.equalTo(64)
make.bottom.equalTo(0)
make.left.equalTo(0)
make.right.equalTo(0)
}
}
// 隐藏等待视图
func hiddenWaitLoadView(){
if self.waitView != nil {
self.waitView.removeFromSuperview()
self.waitView = nil
}
}
}
|
mit
|
6b016d40589a9c18b60fdb89491910c5
| 22.251462 | 143 | 0.540241 | 4.502831 | false | false | false | false |
Ribeiro/PapersPlease
|
Classes/ValidationUnit.swift
|
1
|
5328
|
//
// ValidationUnit.swift
// PapersPlease
//
// Created by Brett Walker on 7/3/14.
// Copyright (c) 2014 Poet & Mountain, LLC. All rights reserved.
//
import Foundation
import UIKit
let ValidationUnitUpdateNotification:String = "ValidationUnitUpdateNotification"
class ValidationUnit {
var registeredValidationTypes:[ValidatorType] = []
var errors = [String:[String]]()
var identifier = ""
var valid:Bool = false
var enabled:Bool = true
let validationQueue:dispatch_queue_t
var lastTextValue:String = ""
init(validatorTypes:[ValidatorType]=[], identifier:String, initialText:String="") {
self.validationQueue = dispatch_queue_create("com.poetmountain.ValidationUnitQueue", DISPATCH_QUEUE_SERIAL)
self.registeredValidationTypes = validatorTypes
self.identifier = identifier
self.lastTextValue = initialText
for type:ValidatorType in self.registeredValidationTypes {
if (type.sendsUpdates) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("validationUnitStatusUpdatedNotification:"), name: ValidatorUpdateNotification, object: type)
type.isTextValid(self.lastTextValue)
}
}
}
func dealloc() {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: Validation methods
func registerValidatorType (validatorType:ValidatorType) {
self.registeredValidationTypes.append(validatorType)
}
func clearValidatorTypes () {
self.registeredValidationTypes.removeAll()
}
func validationComplete () {
// first remove any old errors
self.errors.removeAll()
var total_errors = [String:[String:[String]]]()
if (!self.valid) {
for validator_type:ValidatorType in self.registeredValidationTypes {
if (!validator_type.valid) {
self.errors[validator_type.dynamicType.type()] = validator_type.validationStates
}
}
total_errors = ["errors" : self.errors]
}
NSNotificationCenter.defaultCenter().postNotificationName(ValidationUnitUpdateNotification, object: self, userInfo: total_errors)
}
func validateText(text:String) {
if (self.enabled) {
dispatch_async(self.validationQueue, {
[weak self] in
if let strong_self = self {
// add up the number of valid validation tests (coercing each Bool result to an Int)
let num_valid = strong_self.registeredValidationTypes.reduce(0) { (lastValue, type:ValidatorType) in
lastValue + Int(type.isTextValid(text))
}
// use the number of total validations to set a global validation status
let type_count = strong_self.registeredValidationTypes.count
(num_valid == type_count) ? (strong_self.valid = true) : (strong_self.valid = false)
// set the current text value to be the last value to prepare for the next validation request
strong_self.lastTextValue = text
// send notification (on main queue, there be UI work)
dispatch_async(dispatch_get_main_queue(), {
strong_self.validationComplete()
})
}
})
}
}
// MARK: Utility methods
func validatorTypeForIdentifier(identifier:String) -> ValidatorType? {
var validator_type: ValidatorType?
for type:ValidatorType in self.registeredValidationTypes {
if (type.identifier == identifier) {
validator_type = type
break
}
}
return validator_type
}
// MARK: Notifications
@objc func textDidChangeNotification(notification:NSNotification) {
if (notification.name == UITextFieldTextDidChangeNotification) {
let text_field:UITextField = notification.object as! UITextField
self.validateText(text_field.text)
} else if (notification.name == UITextViewTextDidChangeNotification) {
let text_view:UITextView = notification.object as! UITextView
self.validateText(text_view.text)
}
}
@objc func validationUnitStatusUpdatedNotification(notification:NSNotification) {
if (self.enabled) {
if let user_info = notification.userInfo {
if let status_num:NSNumber = user_info["status"] as? NSNumber {
let is_valid: Bool = status_num.boolValue ?? false
if (is_valid) {
self.validateText(self.lastTextValue)
} else {
self.valid = false
self.validationComplete()
}
}
}
}
}
}
|
mit
|
809088345ef460741db16f570d0cda48
| 31.693252 | 183 | 0.567005 | 5.38726 | false | false | false | false |
yajeka/PS
|
PS/AddPatnerController.swift
|
1
|
1618
|
//
// AddPatnerController.swift
// PS
//
// Created by Yauheni Yarotski on 19.03.16.
// Copyright © 2016 hackathon. All rights reserved.
//
import UIKit
class AddPatnerController: UIViewController {
@IBOutlet weak var addPhotoButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
title = "App partner"
view.backgroundColor = UIColor(patternImage: UIImage(named: "background")!)
addPhotoButtonConfig()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func addPhotoButtonConfig() {
// if let image = addPhotoButton.imageView?.image {
addPhotoButton.layer.cornerRadius = 40
addPhotoButton.layer.masksToBounds = true
addPhotoButton.layer.borderWidth = 3
addPhotoButton.layer.borderColor = UIColor.whiteColor().CGColor
addPhotoButtonChangeImage(UIImage(named: "girl")!)
// }
}
func addPhotoButtonChangeImage(newImage:UIImage) {
addPhotoButton.setImage(newImage, forState: .Normal)
addPhotoButton.setBackgroundImage(newImage, forState: .Normal)
}
@IBAction func doneButtonPressed(sender: UIBarButtonItem) {
let storyboard = UIStoryboard(name: "Master", bundle: nil)
let vc = storyboard.instantiateInitialViewController()
vc?.hidesBottomBarWhenPushed = false
presentViewController(vc!, animated: true, completion: {
})
}
}
|
lgpl-3.0
|
11ebdeda93ee7e12a9ee33eb29471ff6
| 26.87931 | 83 | 0.641311 | 5.267101 | false | false | false | false |
danielsaidi/Vandelay
|
Sources/Vandelay/ExportResult.swift
|
1
|
1063
|
//
// ExportResult.swift
// Vandelay
//
// Created by Daniel Saidi on 2016-05-30.
// Copyright © 2016 Daniel Saidi. All rights reserved.
//
import Foundation
/**
This struct represents the result of an export operation.
It specifies the export method, current state as well as an optional error and export url.
*/
public struct ExportResult {
public init(method: ExportMethod, state: ExportState, error: Error? = nil) {
self.method = method
self.state = state
self.error = error
self.filePath = nil
}
public init(method: ExportMethod, error: Error) {
self.method = method
self.state = .failed
self.error = error
self.filePath = nil
}
public init(method: ExportMethod, filePath: String) {
self.method = method
self.state = .completed
self.error = nil
self.filePath = filePath
}
public let method: ExportMethod
public let state: ExportState
public let error: Error?
public let filePath: String?
}
|
mit
|
066d1325b8f65f3e2ac0d9cffb8a06f1
| 23.697674 | 91 | 0.63371 | 4.248 | false | false | false | false |
EclipseSoundscapes/EclipseSoundscapes
|
EclipseSoundscapes/Features/Walkthrough/Cells/PageCell.swift
|
1
|
4698
|
//
// PageCell.swift
// EclipseSoundscapes
//
// Created by Arlindo Goncalves on 5/10/20.
//
// Copyright © 2020 Arlindo Goncalves.
// 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/].
//
// For Contact email: [email protected]
import UIKit
class PageCell: UICollectionViewCell {
static let InfoHeight = UIScreen.main.bounds.height/3 + 15
var page: Page? {
didSet {
guard let page = page else {
return
}
let imageName = page.imageName
imageView.image = UIImage(named: imageName)
let color = UIColor(white: 0.2, alpha: 1)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attributedText = NSMutableAttributedString(string: page.title, attributes: [NSAttributedString.Key.font: UIFont.getDefautlFont(.meduium, size: 20), NSAttributedString.Key.foregroundColor: color, NSAttributedString.Key.paragraphStyle: paragraphStyle])
attributedText.append(NSAttributedString(string: "\n\n\(page.message)", attributes: [NSAttributedString.Key.font: UIFont.getDefautlFont(.meduium, size: 14), NSAttributedString.Key.foregroundColor: color]))
let paragraphStyle2 = NSMutableParagraphStyle()
paragraphStyle2.alignment = .center
let start = page.title.count
let length = attributedText.string.count - start
attributedText.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle2, range: NSRange(location: start, length: length))
infoView.content = attributedText
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
let imageView: UIImageView = {
let iv = UIImageView()
iv.contentMode = .scaleAspectFill
iv.clipsToBounds = true
return iv
}()
let infoView : WalkthroughContentView = {
var view = WalkthroughContentView()
view.backgroundColor = .lightGray
return view
}()
let lineSeparatorView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(white: 0.9, alpha: 1)
return view
}()
func setupViews() {
addSubview(imageView)
addSubview(infoView)
addSubview(lineSeparatorView)
imageView.anchorToTop(topAnchor, left: leftAnchor, bottom: infoView.topAnchor, right: rightAnchor)
infoView.anchor(left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, heightConstant: PageCell.InfoHeight)
lineSeparatorView.anchorToTop(nil, left: leftAnchor, bottom: infoView.topAnchor, right: rightAnchor)
lineSeparatorView.heightAnchor.constraint(equalToConstant: 1).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class WalkthroughContentView: UIView {
var content: NSAttributedString? {
didSet {
self.contentTextView.attributedText = content
}
}
var contentTextView : UITextView = {
var tv = UITextView()
tv.textContainerInset = UIEdgeInsets(top: 10, left: 10, bottom: 5, right: 10)
tv.isEditable = false
tv.backgroundColor = UIColor(r: 249, g: 249, b: 249)
tv.accessibilityTraits = [UIAccessibilityTraits.staticText, UIAccessibilityTraits.header]
return tv
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(contentTextView)
contentTextView.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
gpl-3.0
|
5880907df3db89bdebd55560325eb04a
| 35.130769 | 266 | 0.64488 | 4.94942 | false | false | false | false |
alessandro-martin/SimpleSideController
|
SimpleSideController/Source/Helpers.swift
|
1
|
1917
|
//
// Helpers.swift
// SimpleSideController
//
// Created by Alessandro Martin on 21/08/16.
// Copyright © 2016 Alessandro Martin. All rights reserved.
//
import UIKit
extension UIView {
func isRightToLeftLanguage() -> Bool {
if #available(iOS 9.0, *) {
return UIView.userInterfaceLayoutDirection(for: self.semanticContentAttribute) == .rightToLeft
} else {
return NSLocale.characterDirection(forLanguage: NSLocale.preferredLanguages[0]) == .rightToLeft
}
}
func displayShadow(opacity: CGFloat = 1.0, animation duration: CFTimeInterval = 0.25) {
self.setShadowOpacity(to: opacity, animation: duration)
}
func hideShadow(animation duration: CFTimeInterval = 0.25) {
self.setShadowOpacity(to: 0.0, animation: duration)
}
private func setShadowOpacity(to toValue: CGFloat, animation duration: CFTimeInterval) {
let anim = CABasicAnimation(keyPath: "shadowOpacity")
anim.fromValue = self.layer.shadowOpacity
anim.toValue = toValue
anim.duration = duration
self.layer.add(anim, forKey: "shadowOpacity")
self.layer.shadowOpacity = Float(toValue)
}
}
extension UIViewController {
var simpleSideController: SimpleSideController? {
get {
return simpleSideController(for: self)
}
}
private func simpleSideController(for viewController: UIViewController?) -> SimpleSideController? {
guard let viewController = viewController else { return nil }
switch viewController {
case let viewController as SimpleSideController:
return viewController
default:
return simpleSideController(for: viewController.parent)
}
}
}
func clamp<T: Comparable>(lowerBound lower: T, value: T, upperBound: T) -> T {
return max(min(value, upperBound), lower)
}
|
mit
|
6ee76e89dc83925af2a886c95600ffbe
| 31.474576 | 107 | 0.663883 | 4.875318 | false | false | false | false |
czechboy0/swift-package-crawler
|
Sources/StatisticsUpdater/main.swift
|
1
|
2920
|
import Utils
import Redbird
import Foundation
import Templater
func updateStats(db: Redbird) throws {
let templatePath = #file.parentDirectory().addPathComponents("StatTemplate.md")
let template = try String(contentsOfFile: templatePath)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.string(from: NSDate())
let monthFormatter = NSDateFormatter()
monthFormatter.dateFormat = "MMMM yyyy"
let growthMonth = monthFormatter.string(from: NSDate())
let swift_versions_stat = try readStat(db: db, name: "swift_versions_stat")
let number_of_dependencies_histogram_stat = try readStat(db: db, name: "number_of_dependencies_histogram_stat")
let most_popular_direct_dependencies_stat = try readStat(db: db, name: "most_popular_direct_dependencies_stat")
let most_popular_transitive_dependencies_stat = try readStat(db: db, name: "most_popular_transitive_dependencies_stat")
let most_popular_authors_direct_dependencies_stat = try readStat(db: db, name: "most_popular_authors_direct_dependencies_stat")
let most_popular_authors_transitive_dependencies_stat = try readStat(db: db, name: "most_popular_authors_transitive_dependencies_stat")
let packageCount = try readStat(db: db, name: "package_count")
let context = [
"swift_versions_stat": swift_versions_stat,
"last_updated_date": date,
"analyzed_package_count": packageCount,
"growth_rate": "30",
"growth_month" : growthMonth,
"number_of_dependencies_histogram_stat": number_of_dependencies_histogram_stat,
"most_popular_direct_dependencies_stat": most_popular_direct_dependencies_stat,
"most_popular_transitive_dependencies_stat": most_popular_transitive_dependencies_stat,
"most_popular_authors_direct_dependencies_stat": most_popular_authors_direct_dependencies_stat,
"most_popular_authors_transitive_dependencies_stat": most_popular_authors_transitive_dependencies_stat
]
let report = try Template(template).fill(with: context)
print("Generated markdown report")
let statsRoot = try cacheRootPath()
.parentDirectory()
.addPathComponents("swiftpm-packages-statistics")
let reportPath = statsRoot
.addPathComponents("README.md")
try report.write(toFile: reportPath, atomically: true, encoding: NSUTF8StringEncoding)
try ifChangesCommitAndPush(repoPath: statsRoot)
}
do {
print("StatisticsUpdater starting")
//you need to have a redis-server running at 127.0.0.1 port 6379
let db = try Redbird()
try updateStats(db: db)
print("StatisticsUpdater finished")
} catch {
print(error)
exit(1)
}
|
mit
|
703bcfe9056b01009e724becc429b1df
| 42.58209 | 139 | 0.675 | 4.281525 | false | false | false | false |
annieqton/picsfeed
|
Picsfeed/Picsfeed/GalleryCollectionViewLayout.swift
|
1
|
1205
|
//
// GalleryCollectionViewLayout.swift
// Picsfeed
//
// Created by Annie Ton-Nu on 3/29/17.
// Copyright © 2017 Annie Ton-Nu. All rights reserved.
//
import UIKit
class GalleryCollectionViewLayout: UICollectionViewFlowLayout {
var columns = 2
let spacing: CGFloat = 1.0 //will still look clean on smaller device, system determines points
var screenWidth : CGFloat {
return UIScreen.main.bounds.width
}
var itemWidth : CGFloat {
let availableScreen = screenWidth - (CGFloat(self.columns) * self.spacing)
return availableScreen / CGFloat(self.columns)
}
init(columns: Int = 2) {
self.columns = columns
super.init() //reason for this here because we need to assign all of it's variables first before we change the values. Patern: start with child, initialize parent, then change
self.minimumLineSpacing = spacing
self.minimumInteritemSpacing = spacing
self.itemSize = CGSize(width: itemWidth, height: itemWidth)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
f7aea433c2a940608cbe5f2475cdb983
| 27 | 185 | 0.64701 | 4.684825 | false | false | false | false |
material-motion/material-motion-swift
|
src/operators/foundation/_map.swift
|
2
|
2644
|
/*
Copyright 2016-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import UIKit
extension MotionObservableConvertible {
/**
Transform the items emitted by an Observable by applying a function to each item.
This operator is meant to be used when building other operators.
*/
public func _map<U>(transformVelocity: Bool = false, transform: @escaping (T) -> U) -> MotionObservable<U> {
return _nextOperator(operation: { value, next in
next(transform(value))
}, coreAnimation: { event, coreAnimation in
let transformedInitialVelocity: Any?
switch event {
case .add(let info):
if let initialVelocity = info.initialVelocity {
transformedInitialVelocity = transformVelocity ? transform(initialVelocity as! T) : initialVelocity
} else {
transformedInitialVelocity = nil
}
let copy = info.animation.copy() as! CAPropertyAnimation
switch copy {
case let basicAnimation as CABasicAnimation:
if let fromValue = basicAnimation.fromValue {
basicAnimation.fromValue = transform(fromValue as! T)
}
if let toValue = basicAnimation.toValue {
basicAnimation.toValue = transform(toValue as! T)
}
if let byValue = basicAnimation.byValue {
basicAnimation.byValue = transform(byValue as! T)
}
var modified = info
modified.animation = basicAnimation
modified.initialVelocity = transformedInitialVelocity
coreAnimation?(.add(modified))
case let keyframeAnimation as CAKeyframeAnimation:
keyframeAnimation.values = keyframeAnimation.values?.map { transform($0 as! T) }
var modified = info
modified.animation = keyframeAnimation
modified.initialVelocity = transformedInitialVelocity
coreAnimation?(.add(modified))
default:
assertionFailure("Unsupported animation type: \(type(of: info.animation))")
}
default:
coreAnimation?(event)
}
})
}
}
|
apache-2.0
|
543992b5f3ac5af1edc33d2638149459
| 34.72973 | 110 | 0.680408 | 5.153996 | false | false | false | false |
yanagiba/swift-lint
|
Sources/Lint/Rule/NCSSRule.swift
|
2
|
2973
|
/*
Copyright 2017 Ryuichi Laboratories and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import Source
import AST
import Metric
class NCSSRule : RuleBase, ASTVisitorRule {
static let ThresholdKey = "NCSS"
static let DefaultThreshold = 30
let name = "High Non-Commenting Source Statements"
let identifier = "high_ncss"
let fileName = "NCSSRule.swift"
var description: String? {
return """
This rule counts number of lines for a method by
counting Non Commenting Source Statements (NCSS).
NCSS only takes actual statements into consideration,
in other words, ignores empty statements, empty blocks,
closing brackets or semicolons after closing brackets.
Meanwhile, a statement that is broken into multiple lines contribute only one count.
"""
}
var examples: [String]? {
return [
"""
func example() // 1
{
if (1) // 2
{
}
else // 3
{
}
}
""",
]
}
var thresholds: [String: String]? {
return [
NCSSRule.ThresholdKey:
"The high NCSS method reporting threshold, default value is \(NCSSRule.DefaultThreshold)."
]
}
let severity = Issue.Severity.major
let category = Issue.Category.readability
private func getThreshold(of sourceRange: SourceRange) -> Int {
return getConfiguration(
forKey: NCSSRule.ThresholdKey,
atLineNumber: sourceRange.start.line,
orDefault: NCSSRule.DefaultThreshold)
}
private func emitIssue(_ ncss: Int, _ sourceRange: SourceRange) {
let threshold = getThreshold(of: sourceRange)
guard ncss > threshold else {
return
}
emitIssue(
sourceRange,
description: "Method of \(ncss) NCSS exceeds limit of \(threshold)")
}
func visit(_ funcDecl: FunctionDeclaration) throws -> Bool {
emitIssue(funcDecl.ncssCount, funcDecl.sourceRange)
return true
}
func visit(_ initDecl: InitializerDeclaration) throws -> Bool {
emitIssue(initDecl.ncssCount, initDecl.sourceRange)
return true
}
func visit(_ deinitDecl: DeinitializerDeclaration) throws -> Bool {
emitIssue(deinitDecl.ncssCount, deinitDecl.sourceRange)
return true
}
func visit(_ subscriptDecl: SubscriptDeclaration) throws -> Bool {
emitIssue(subscriptDecl.ncssCount, subscriptDecl.sourceRange)
return true
}
}
|
apache-2.0
|
e0c8f7c05388e70bcd9e711ccd251482
| 28.147059 | 98 | 0.682476 | 4.511381 | false | false | false | false |
sessuru/CVCalendar
|
CVCalendar Demo/CVCalendar Demo/ViewController.swift
|
1
|
13537
|
//
// ViewController.swift
// CVCalendar Demo
//
// Created by Мак-ПК on 1/3/15.
// Copyright (c) 2015 GameApp. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
struct Color {
static let selectedText = UIColor.white
static let text = UIColor.black
static let textDisabled = UIColor.gray
static let selectionBackground = UIColor(red: 0.2, green: 0.2, blue: 1.0, alpha: 1.0)
static let sundayText = UIColor(red: 1.0, green: 0.2, blue: 0.2, alpha: 1.0)
static let sundayTextDisabled = UIColor(red: 1.0, green: 0.6, blue: 0.6, alpha: 1.0)
static let sundaySelectionBackground = sundayText
}
// MARK: - Properties
@IBOutlet weak var calendarView: CVCalendarView!
@IBOutlet weak var menuView: CVCalendarMenuView!
@IBOutlet weak var monthLabel: UILabel!
@IBOutlet weak var daysOutSwitch: UISwitch!
fileprivate var randomNumberOfDotMarkersForDay = [Int]()
var shouldShowDaysOut = true
var animationFinished = true
var selectedDay:DayView!
var currentCalendar: Calendar?
override func awakeFromNib() {
let timeZoneBias = 480 // (UTC+08:00)
currentCalendar = Calendar.init(identifier: .gregorian)
if let timeZone = TimeZone.init(secondsFromGMT: -timeZoneBias * 60) {
currentCalendar?.timeZone = timeZone
}
}
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
if let currentCalendar = currentCalendar {
monthLabel.text = CVDate(date: Date(), calendar: currentCalendar).globalDescription
}
randomizeDotMarkers()
}
@IBAction func removeCircleAndDot(sender: AnyObject) {
if let dayView = selectedDay {
calendarView.contentController.removeCircleLabel(dayView)
if dayView.date.day < randomNumberOfDotMarkersForDay.count {
randomNumberOfDotMarkersForDay[dayView.date.day] = 0
}
calendarView.contentController.refreshPresentedMonth()
}
}
@IBAction func refreshMonth(sender: AnyObject) {
calendarView.contentController.refreshPresentedMonth()
randomizeDotMarkers()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
calendarView.commitCalendarViewUpdate()
menuView.commitMenuViewUpdate()
}
private func randomizeDotMarkers() {
randomNumberOfDotMarkersForDay = [Int]()
for _ in 0...31 {
randomNumberOfDotMarkersForDay.append(Int(arc4random_uniform(3) + 1))
}
}
}
// MARK: - CVCalendarViewDelegate & CVCalendarMenuViewDelegate
extension ViewController: CVCalendarViewDelegate, CVCalendarMenuViewDelegate {
/// Required method to implement!
func presentationMode() -> CalendarMode {
return .monthView
}
/// Required method to implement!
func firstWeekday() -> Weekday {
return .sunday
}
// MARK: Optional methods
func calendar() -> Calendar? {
return currentCalendar
}
func dayOfWeekTextColor(by weekday: Weekday) -> UIColor {
return weekday == .sunday ? UIColor(red: 1.0, green: 0, blue: 0, alpha: 1.0) : UIColor.white
}
func shouldShowWeekdaysOut() -> Bool {
return shouldShowDaysOut
}
func shouldAnimateResizing() -> Bool {
return true // Default value is true
}
private func shouldSelectDayView(dayView: DayView) -> Bool {
return arc4random_uniform(3) == 0 ? true : false
}
func shouldAutoSelectDayOnMonthChange() -> Bool {
return false
}
func didSelectDayView(_ dayView: CVCalendarDayView, animationDidFinish: Bool) {
selectedDay = dayView
}
func shouldSelectRange() -> Bool {
return true
}
func didSelectRange(from startDayView: DayView, to endDayView: DayView) {
print("RANGE SELECTED: \(startDayView.date.commonDescription) to \(endDayView.date.commonDescription)")
}
func presentedDateUpdated(_ date: CVDate) {
if monthLabel.text != date.globalDescription && self.animationFinished {
let updatedMonthLabel = UILabel()
updatedMonthLabel.textColor = monthLabel.textColor
updatedMonthLabel.font = monthLabel.font
updatedMonthLabel.textAlignment = .center
updatedMonthLabel.text = date.globalDescription
updatedMonthLabel.sizeToFit()
updatedMonthLabel.alpha = 0
updatedMonthLabel.center = self.monthLabel.center
let offset = CGFloat(48)
updatedMonthLabel.transform = CGAffineTransform(translationX: 0, y: offset)
updatedMonthLabel.transform = CGAffineTransform(scaleX: 1, y: 0.1)
UIView.animate(withDuration: 0.35, delay: 0, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.animationFinished = false
self.monthLabel.transform = CGAffineTransform(translationX: 0, y: -offset)
self.monthLabel.transform = CGAffineTransform(scaleX: 1, y: 0.1)
self.monthLabel.alpha = 0
updatedMonthLabel.alpha = 1
updatedMonthLabel.transform = CGAffineTransform.identity
}) { _ in
self.animationFinished = true
self.monthLabel.frame = updatedMonthLabel.frame
self.monthLabel.text = updatedMonthLabel.text
self.monthLabel.transform = CGAffineTransform.identity
self.monthLabel.alpha = 1
updatedMonthLabel.removeFromSuperview()
}
self.view.insertSubview(updatedMonthLabel, aboveSubview: self.monthLabel)
}
}
func topMarker(shouldDisplayOnDayView dayView: CVCalendarDayView) -> Bool {
return true
}
func weekdaySymbolType() -> WeekdaySymbolType {
return .short
}
func selectionViewPath() -> ((CGRect) -> (UIBezierPath)) {
return { UIBezierPath(rect: CGRect(x: 0, y: 0, width: $0.width, height: $0.height)) }
}
func shouldShowCustomSingleSelection() -> Bool {
return false
}
func preliminaryView(viewOnDayView dayView: DayView) -> UIView {
let circleView = CVAuxiliaryView(dayView: dayView, rect: dayView.frame, shape: CVShape.circle)
circleView.fillColor = .colorFromCode(0xCCCCCC)
return circleView
}
func preliminaryView(shouldDisplayOnDayView dayView: DayView) -> Bool {
if (dayView.isCurrentDay) {
return true
}
return false
}
func supplementaryView(viewOnDayView dayView: DayView) -> UIView {
dayView.setNeedsLayout()
dayView.layoutIfNeeded()
let π = Double.pi
let ringLayer = CAShapeLayer()
let ringLineWidth: CGFloat = 4.0
let ringLineColour = UIColor.blue
let newView = UIView(frame: dayView.frame)
let diameter = (min(newView.bounds.width, newView.bounds.height))
let radius = diameter / 2.0 - ringLineWidth
newView.layer.addSublayer(ringLayer)
ringLayer.fillColor = nil
ringLayer.lineWidth = ringLineWidth
ringLayer.strokeColor = ringLineColour.cgColor
let centrePoint = CGPoint(x: newView.bounds.width/2.0, y: newView.bounds.height/2.0)
let startAngle = CGFloat(-π/2.0)
let endAngle = CGFloat(π * 2.0) + startAngle
let ringPath = UIBezierPath(arcCenter: centrePoint,
radius: radius,
startAngle: startAngle,
endAngle: endAngle,
clockwise: true)
ringLayer.path = ringPath.cgPath
ringLayer.frame = newView.layer.bounds
return newView
}
func supplementaryView(shouldDisplayOnDayView dayView: DayView) -> Bool {
guard let currentCalendar = currentCalendar else {
return false
}
var components = Manager.componentsForDate(Foundation.Date(), calendar: currentCalendar)
/* For consistency, always show supplementaryView on the 3rd, 13th and 23rd of the current month/year. This is to check that these expected calendar days are "circled". There was a bug that was circling the wrong dates. A fix was put in for #408 #411.
Other month and years show random days being circled as was done previously in the Demo code.
*/
if dayView.date.year == components.year &&
dayView.date.month == components.month {
if (dayView.date.day == 3 || dayView.date.day == 13 || dayView.date.day == 23) {
print("Circle should appear on " + dayView.date.commonDescription)
return true
}
return false
} else {
if (Int(arc4random_uniform(3)) == 1) {
return true
}
return false
}
}
func dayOfWeekTextColor() -> UIColor {
return UIColor.white
}
func dayOfWeekBackGroundColor() -> UIColor {
return UIColor.orange
}
func disableScrollingBeforeDate() -> Date {
return Date()
}
func maxSelectableRange() -> Int {
return 14
}
func earliestSelectableDate() -> Date {
return Date()
}
func latestSelectableDate() -> Date {
var dayComponents = DateComponents()
dayComponents.day = 70
let calendar = Calendar(identifier: .gregorian)
if let lastDate = calendar.date(byAdding: dayComponents, to: Date()) {
return lastDate
} else {
return Date()
}
}
}
// MARK: - CVCalendarViewAppearanceDelegate
extension ViewController: CVCalendarViewAppearanceDelegate {
func dayLabelWeekdayDisabledColor() -> UIColor {
return UIColor.lightGray
}
func dayLabelPresentWeekdayInitallyBold() -> Bool {
return false
}
func spaceBetweenDayViews() -> CGFloat {
return 0
}
func dayLabelFont(by weekDay: Weekday, status: CVStatus, present: CVPresent) -> UIFont { return UIFont.systemFont(ofSize: 14) }
func dayLabelColor(by weekDay: Weekday, status: CVStatus, present: CVPresent) -> UIColor? {
switch (weekDay, status, present) {
case (_, .selected, _), (_, .highlighted, _): return Color.selectedText
case (.sunday, .in, _): return Color.sundayText
case (.sunday, _, _): return Color.sundayTextDisabled
case (_, .in, _): return Color.text
default: return Color.textDisabled
}
}
func dayLabelBackgroundColor(by weekDay: Weekday, status: CVStatus, present: CVPresent) -> UIColor? {
switch (weekDay, status, present) {
case (.sunday, .selected, _), (.sunday, .highlighted, _): return Color.sundaySelectionBackground
case (_, .selected, _), (_, .highlighted, _): return Color.selectionBackground
default: return nil
}
}
}
// MARK: - IB Actions
extension ViewController {
@IBAction func switchChanged(sender: UISwitch) {
calendarView.changeDaysOutShowingState(shouldShow: sender.isOn)
shouldShowDaysOut = sender.isOn
}
@IBAction func todayMonthView() {
calendarView.toggleCurrentDayView()
}
/// Switch to WeekView mode.
@IBAction func toWeekView(sender: AnyObject) {
calendarView.changeMode(.weekView)
}
/// Switch to MonthView mode.
@IBAction func toMonthView(sender: AnyObject) {
calendarView.changeMode(.monthView)
}
@IBAction func loadPrevious(sender: AnyObject) {
calendarView.loadPreviousView()
}
@IBAction func loadNext(sender: AnyObject) {
calendarView.loadNextView()
}
}
// MARK: - Convenience API Demo
extension ViewController {
func toggleMonthViewWithMonthOffset(offset: Int) {
guard let currentCalendar = currentCalendar else {
return
}
var components = Manager.componentsForDate(Foundation.Date(), calendar: currentCalendar) // from today
components.month! += offset
let resultDate = currentCalendar.date(from: components)!
self.calendarView.toggleViewWithDate(resultDate)
}
func didShowNextMonthView(_ date: Date) {
guard let currentCalendar = currentCalendar else {
return
}
let components = Manager.componentsForDate(date, calendar: currentCalendar) // from today
print("Showing Month: \(components.month!)")
}
func didShowPreviousMonthView(_ date: Date) {
guard let currentCalendar = currentCalendar else {
return
}
let components = Manager.componentsForDate(date, calendar: currentCalendar) // from today
print("Showing Month: \(components.month!)")
}
}
|
mit
|
1ebd14ab0834734ab0a6f41ee6704326
| 31.288783 | 260 | 0.606697 | 5.173614 | false | false | false | false |
mattdaw/SwiftBoard
|
SwiftBoard/CollectionViews/GestureHit.swift
|
1
|
1954
|
//
// GestureHit.swift
// SwiftBoard
//
// Created by Matt Daw on 2014-11-24.
// Copyright (c) 2014 Matt Daw. All rights reserved.
//
import Foundation
protocol GestureHit {}
class CollectionViewGestureHit: GestureHit {
let collectionView: ListViewModelCollectionView
let locationInCollectionView: CGPoint
init(collectionView initCollectionView: ListViewModelCollectionView, locationInCollectionView initViewLocation: CGPoint) {
collectionView = initCollectionView
locationInCollectionView = initViewLocation
}
}
class CellGestureHit: GestureHit {
let collectionViewHit: CollectionViewGestureHit
let cell: ItemViewModelCell
let locationInCell: CGPoint
let itemViewModel: ItemViewModel
init(collectionViewHit initHit: CollectionViewGestureHit, cell initCell: ItemViewModelCell, locationInCell initCellLocation: CGPoint, itemViewModel initItem: ItemViewModel) {
collectionViewHit = initHit
cell = initCell
locationInCell = initCellLocation
itemViewModel = initItem
}
}
class AppGestureHit: CellGestureHit, GestureHit {
let appViewModel: AppViewModel
init(collectionViewHit initHit: CollectionViewGestureHit, cell initCell: ItemViewModelCell, locationInCell initCellLocation: CGPoint, appViewModel initApp: AppViewModel) {
appViewModel = initApp
super.init(collectionViewHit: initHit, cell: initCell, locationInCell: initCellLocation, itemViewModel: initApp)
}
}
class FolderGestureHit: CellGestureHit, GestureHit {
let folderViewModel: FolderViewModel
init(collectionViewHit initHit: CollectionViewGestureHit, cell initCell: ItemViewModelCell, locationInCell initCellLocation: CGPoint, folderViewModel initFolder: FolderViewModel) {
folderViewModel = initFolder
super.init(collectionViewHit: initHit, cell: initCell, locationInCell: initCellLocation, itemViewModel: initFolder)
}
}
|
mit
|
c152b9f2183758cdd09257bd557fc929
| 35.867925 | 184 | 0.76868 | 4.824691 | false | false | false | false |
nathawes/swift
|
stdlib/public/Darwin/Foundation/Publishers+KeyValueObserving.swift
|
9
|
7787
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Only support 64bit
#if !(os(iOS) && (arch(i386) || arch(arm)))
@_exported import Foundation // Clang module
import Combine
// The following protocol is so that we can reference `Self` in the Publisher
// below. This is based on a trick used in the the standard library's
// implementation of `NSObject.observe(key path)`
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public protocol _KeyValueCodingAndObservingPublishing {}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension NSObject: _KeyValueCodingAndObservingPublishing {}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension _KeyValueCodingAndObservingPublishing where Self: NSObject {
/// Publish values when the value identified by a KVO-compliant keypath changes.
///
/// - Parameters:
/// - keyPath: The keypath of the property to publish.
/// - options: Key-value observing options.
/// - Returns: A publisher that emits elements each time the property’s value changes.
public func publisher<Value>(for keyPath: KeyPath<Self, Value>,
options: NSKeyValueObservingOptions = [.initial, .new])
-> NSObject.KeyValueObservingPublisher<Self, Value> {
return NSObject.KeyValueObservingPublisher(object: self, keyPath: keyPath, options: options)
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension NSObject.KeyValueObservingPublisher {
/// Returns a publisher that emits values when a KVO-compliant property changes.
///
/// - Returns: A key-value observing publisher.
public func didChange()
-> Publishers.Map<NSObject.KeyValueObservingPublisher<Subject, Value>, Void> {
return map { _ in () }
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension NSObject {
/// A publisher that emits events when the value of a KVO-compliant property changes.
public struct KeyValueObservingPublisher<Subject: NSObject, Value> : Equatable {
public let object: Subject
public let keyPath: KeyPath<Subject, Value>
public let options: NSKeyValueObservingOptions
public init(
object: Subject,
keyPath: KeyPath<Subject, Value>,
options: NSKeyValueObservingOptions
) {
self.object = object
self.keyPath = keyPath
self.options = options
}
public static func == (
lhs: KeyValueObservingPublisher,
rhs: KeyValueObservingPublisher
) -> Bool {
return lhs.object === rhs.object
&& lhs.keyPath == rhs.keyPath
&& lhs.options == rhs.options
}
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension NSObject.KeyValueObservingPublisher: Publisher {
public typealias Output = Value
public typealias Failure = Never
public func receive<S: Subscriber>(subscriber: S) where S.Input == Output, S.Failure == Failure {
let s = NSObject.KVOSubscription(object, keyPath, options, subscriber)
subscriber.receive(subscription: s)
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension NSObject {
private final class KVOSubscription<Subject: NSObject, Value>: Subscription, CustomStringConvertible, CustomReflectable, CustomPlaygroundDisplayConvertible {
private var observation: NSKeyValueObservation? // GuardedBy(lock)
private var demand: Subscribers.Demand // GuardedBy(lock)
// for configurations that care about '.initial' we need to 'cache' the value to account for backpressure, along with whom to send it to
//
// TODO: in the future we might want to consider interjecting a temporary publisher that does this, so that all KVO subscriptions don't incur the cost.
private var receivedInitial: Bool // GuardedBy(lock)
private var last: Value? // GuardedBy(lock)
private var subscriber: AnySubscriber<Value, Never>? // GuardedBy(lock)
private let lock = Lock()
// This lock can only be held for the duration of downstream callouts
private let downstreamLock = RecursiveLock()
var description: String { return "KVOSubscription" }
var customMirror: Mirror {
lock.lock()
defer { lock.unlock() }
return Mirror(self, children: [
"observation": observation as Any,
"demand": demand
])
}
var playgroundDescription: Any { return description }
init<S: Subscriber>(
_ object: Subject,
_ keyPath: KeyPath<Subject, Value>,
_ options: NSKeyValueObservingOptions,
_ subscriber: S)
where
S.Input == Value,
S.Failure == Never
{
demand = .max(0)
receivedInitial = false
self.subscriber = AnySubscriber(subscriber)
observation = object.observe(
keyPath,
options: options
) { [weak self] obj, _ in
guard let self = self else {
return
}
let value = obj[keyPath: keyPath]
self.lock.lock()
if self.demand > 0, let sub = self.subscriber {
self.demand -= 1
self.lock.unlock()
self.downstreamLock.lock()
let additional = sub.receive(value)
self.downstreamLock.unlock()
self.lock.lock()
self.demand += additional
self.lock.unlock()
} else {
// Drop the value, unless we've asked for .initial, and this
// is the first value.
if self.receivedInitial == false && options.contains(.initial) {
self.last = value
self.receivedInitial = true
}
self.lock.unlock()
}
}
}
deinit {
lock.cleanupLock()
downstreamLock.cleanupLock()
}
func request(_ d: Subscribers.Demand) {
lock.lock()
demand += d
if demand > 0, let v = last, let sub = subscriber {
demand -= 1
last = nil
lock.unlock()
downstreamLock.lock()
let additional = sub.receive(v)
downstreamLock.unlock()
lock.lock()
demand += additional
} else {
demand -= 1
last = nil
}
lock.unlock()
}
func cancel() {
lock.lock()
guard let o = observation else {
lock.unlock()
return
}
lock.unlock()
observation = nil
subscriber = nil
last = nil
o.invalidate()
}
}
}
#endif /* !(os(iOS) && (arch(i386) || arch(arm))) */
|
apache-2.0
|
1f484211dcc54e323f0f859236708202
| 36.071429 | 161 | 0.560051 | 4.939721 | false | false | false | false |
apple/swift-corelibs-foundation
|
Darwin/Foundation-swiftoverlay/Locale.swift
|
1
|
19705
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
@_implementationOnly import _FoundationOverlayShims
/**
`Locale` encapsulates information about linguistic, cultural, and technological conventions and standards. Examples of information encapsulated by a locale include the symbol used for the decimal separator in numbers and the way dates are formatted.
Locales are typically used to provide, format, and interpret information about and according to the user's customs and preferences. They are frequently used in conjunction with formatters. Although you can use many locales, you usually use the one associated with the current user.
*/
public struct Locale : Hashable, Equatable, ReferenceConvertible {
public typealias ReferenceType = NSLocale
public typealias LanguageDirection = NSLocale.LanguageDirection
fileprivate var _wrapped : NSLocale
private var _autoupdating : Bool
/// Returns a locale which tracks the user's current preferences.
///
/// If mutated, this Locale will no longer track the user's preferences.
///
/// - note: The autoupdating Locale will only compare equal to another autoupdating Locale.
public static var autoupdatingCurrent : Locale {
return Locale(adoptingReference: __NSLocaleAutoupdating() as! NSLocale, autoupdating: true)
}
/// Returns the user's current locale.
public static var current : Locale {
return Locale(adoptingReference: __NSLocaleCurrent() as! NSLocale, autoupdating: false)
}
@available(*, unavailable, message: "Consider using the user's locale or nil instead, depending on use case")
public static var system : Locale { fatalError() }
// MARK: -
//
/// Return a locale with the specified identifier.
public init(identifier: String) {
_wrapped = NSLocale(localeIdentifier: identifier)
_autoupdating = false
}
fileprivate init(reference: __shared NSLocale) {
_wrapped = reference.copy() as! NSLocale
if __NSLocaleIsAutoupdating(reference) {
_autoupdating = true
} else {
_autoupdating = false
}
}
private init(adoptingReference reference: NSLocale, autoupdating: Bool) {
_wrapped = reference
_autoupdating = autoupdating
}
// MARK: -
//
/// Returns a localized string for a specified identifier.
///
/// For example, in the "en" locale, the result for `"es"` is `"Spanish"`.
public func localizedString(forIdentifier identifier: String) -> String? {
return _wrapped.displayName(forKey: .identifier, value: identifier)
}
/// Returns a localized string for a specified language code.
///
/// For example, in the "en" locale, the result for `"es"` is `"Spanish"`.
public func localizedString(forLanguageCode languageCode: String) -> String? {
return _wrapped.displayName(forKey: .languageCode, value: languageCode)
}
/// Returns a localized string for a specified region code.
///
/// For example, in the "en" locale, the result for `"fr"` is `"France"`.
public func localizedString(forRegionCode regionCode: String) -> String? {
return _wrapped.displayName(forKey: .countryCode, value: regionCode)
}
/// Returns a localized string for a specified script code.
///
/// For example, in the "en" locale, the result for `"Hans"` is `"Simplified Han"`.
public func localizedString(forScriptCode scriptCode: String) -> String? {
return _wrapped.displayName(forKey: .scriptCode, value: scriptCode)
}
/// Returns a localized string for a specified variant code.
///
/// For example, in the "en" locale, the result for `"POSIX"` is `"Computer"`.
public func localizedString(forVariantCode variantCode: String) -> String? {
return _wrapped.displayName(forKey: .variantCode, value: variantCode)
}
/// Returns a localized string for a specified `Calendar.Identifier`.
///
/// For example, in the "en" locale, the result for `.buddhist` is `"Buddhist Calendar"`.
public func localizedString(for calendarIdentifier: Calendar.Identifier) -> String? {
// NSLocale doesn't export a constant for this
let result = CFLocaleCopyDisplayNameForPropertyValue(unsafeBitCast(_wrapped, to: CFLocale.self), .calendarIdentifier, Calendar._toNSCalendarIdentifier(calendarIdentifier).rawValue as CFString) as String?
return result
}
/// Returns a localized string for a specified ISO 4217 currency code.
///
/// For example, in the "en" locale, the result for `"USD"` is `"US Dollar"`.
/// - seealso: `Locale.isoCurrencyCodes`
public func localizedString(forCurrencyCode currencyCode: String) -> String? {
return _wrapped.displayName(forKey: .currencyCode, value: currencyCode)
}
/// Returns a localized string for a specified ICU collation identifier.
///
/// For example, in the "en" locale, the result for `"phonebook"` is `"Phonebook Sort Order"`.
public func localizedString(forCollationIdentifier collationIdentifier: String) -> String? {
return _wrapped.displayName(forKey: .collationIdentifier, value: collationIdentifier)
}
/// Returns a localized string for a specified ICU collator identifier.
public func localizedString(forCollatorIdentifier collatorIdentifier: String) -> String? {
return _wrapped.displayName(forKey: .collatorIdentifier, value: collatorIdentifier)
}
// MARK: -
//
/// Returns the identifier of the locale.
public var identifier: String {
return _wrapped.localeIdentifier
}
/// Returns the language code of the locale, or nil if has none.
///
/// For example, for the locale "zh-Hant-HK", returns "zh".
public var languageCode: String? {
return _wrapped.object(forKey: .languageCode) as? String
}
/// Returns the region code of the locale, or nil if it has none.
///
/// For example, for the locale "zh-Hant-HK", returns "HK".
public var regionCode: String? {
// n.b. this is called countryCode in ObjC
if let result = _wrapped.object(forKey: .countryCode) as? String {
if result.isEmpty {
return nil
} else {
return result
}
} else {
return nil
}
}
/// Returns the script code of the locale, or nil if has none.
///
/// For example, for the locale "zh-Hant-HK", returns "Hant".
public var scriptCode: String? {
return _wrapped.object(forKey: .scriptCode) as? String
}
/// Returns the variant code for the locale, or nil if it has none.
///
/// For example, for the locale "en_POSIX", returns "POSIX".
public var variantCode: String? {
if let result = _wrapped.object(forKey: .variantCode) as? String {
if result.isEmpty {
return nil
} else {
return result
}
} else {
return nil
}
}
/// Returns the exemplar character set for the locale, or nil if has none.
public var exemplarCharacterSet: CharacterSet? {
return _wrapped.object(forKey: .exemplarCharacterSet) as? CharacterSet
}
/// Returns the calendar for the locale, or the Gregorian calendar as a fallback.
public var calendar: Calendar {
// NSLocale should not return nil here
if let result = _wrapped.object(forKey: .calendar) as? Calendar {
return result
} else {
return Calendar(identifier: .gregorian)
}
}
/// Returns the collation identifier for the locale, or nil if it has none.
///
/// For example, for the locale "en_US@collation=phonebook", returns "phonebook".
public var collationIdentifier: String? {
return _wrapped.object(forKey: .collationIdentifier) as? String
}
/// Returns true if the locale uses the metric system.
///
/// -seealso: MeasurementFormatter
public var usesMetricSystem: Bool {
// NSLocale should not return nil here, but just in case
if let result = (_wrapped.object(forKey: .usesMetricSystem) as? NSNumber)?.boolValue {
return result
} else {
return false
}
}
/// Returns the decimal separator of the locale.
///
/// For example, for "en_US", returns ".".
public var decimalSeparator: String? {
return _wrapped.object(forKey: .decimalSeparator) as? String
}
/// Returns the grouping separator of the locale.
///
/// For example, for "en_US", returns ",".
public var groupingSeparator: String? {
return _wrapped.object(forKey: .groupingSeparator) as? String
}
/// Returns the currency symbol of the locale.
///
/// For example, for "zh-Hant-HK", returns "HK$".
public var currencySymbol: String? {
return _wrapped.object(forKey: .currencySymbol) as? String
}
/// Returns the currency code of the locale.
///
/// For example, for "zh-Hant-HK", returns "HKD".
public var currencyCode: String? {
return _wrapped.object(forKey: .currencyCode) as? String
}
/// Returns the collator identifier of the locale.
public var collatorIdentifier: String? {
return _wrapped.object(forKey: .collatorIdentifier) as? String
}
/// Returns the quotation begin delimiter of the locale.
///
/// For example, returns `“` for "en_US", and `「` for "zh-Hant-HK".
public var quotationBeginDelimiter: String? {
return _wrapped.object(forKey: .quotationBeginDelimiterKey) as? String
}
/// Returns the quotation end delimiter of the locale.
///
/// For example, returns `”` for "en_US", and `」` for "zh-Hant-HK".
public var quotationEndDelimiter: String? {
return _wrapped.object(forKey: .quotationEndDelimiterKey) as? String
}
/// Returns the alternate quotation begin delimiter of the locale.
///
/// For example, returns `‘` for "en_US", and `『` for "zh-Hant-HK".
public var alternateQuotationBeginDelimiter: String? {
return _wrapped.object(forKey: .alternateQuotationBeginDelimiterKey) as? String
}
/// Returns the alternate quotation end delimiter of the locale.
///
/// For example, returns `’` for "en_US", and `』` for "zh-Hant-HK".
public var alternateQuotationEndDelimiter: String? {
return _wrapped.object(forKey: .alternateQuotationEndDelimiterKey) as? String
}
// MARK: -
//
/// Returns a list of available `Locale` identifiers.
public static var availableIdentifiers: [String] {
return NSLocale.availableLocaleIdentifiers
}
/// Returns a list of available `Locale` language codes.
public static var isoLanguageCodes: [String] {
return NSLocale.isoLanguageCodes
}
/// Returns a list of available `Locale` region codes.
public static var isoRegionCodes: [String] {
// This was renamed from Obj-C
return NSLocale.isoCountryCodes
}
/// Returns a list of available `Locale` currency codes.
public static var isoCurrencyCodes: [String] {
return NSLocale.isoCurrencyCodes
}
/// Returns a list of common `Locale` currency codes.
public static var commonISOCurrencyCodes: [String] {
return NSLocale.commonISOCurrencyCodes
}
/// Returns a list of the user's preferred languages.
///
/// - note: `Bundle` is responsible for determining the language that your application will run in, based on the result of this API and combined with the languages your application supports.
/// - seealso: `Bundle.preferredLocalizations(from:)`
/// - seealso: `Bundle.preferredLocalizations(from:forPreferences:)`
public static var preferredLanguages: [String] {
return NSLocale.preferredLanguages
}
/// Returns a dictionary that splits an identifier into its component pieces.
public static func components(fromIdentifier string: String) -> [String : String] {
return NSLocale.components(fromLocaleIdentifier: string)
}
/// Constructs an identifier from a dictionary of components.
public static func identifier(fromComponents components: [String : String]) -> String {
return NSLocale.localeIdentifier(fromComponents: components)
}
/// Returns a canonical identifier from the given string.
public static func canonicalIdentifier(from string: String) -> String {
return NSLocale.canonicalLocaleIdentifier(from: string)
}
/// Returns a canonical language identifier from the given string.
public static func canonicalLanguageIdentifier(from string: String) -> String {
return NSLocale.canonicalLanguageIdentifier(from: string)
}
/// Returns the `Locale` identifier from a given Windows locale code, or nil if it could not be converted.
public static func identifier(fromWindowsLocaleCode code: Int) -> String? {
return NSLocale.localeIdentifier(fromWindowsLocaleCode: UInt32(code))
}
/// Returns the Windows locale code from a given identifier, or nil if it could not be converted.
public static func windowsLocaleCode(fromIdentifier identifier: String) -> Int? {
let result = NSLocale.windowsLocaleCode(fromLocaleIdentifier: identifier)
if result == 0 {
return nil
} else {
return Int(result)
}
}
/// Returns the character direction for a specified language code.
public static func characterDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection {
return NSLocale.characterDirection(forLanguage: isoLangCode)
}
/// Returns the line direction for a specified language code.
public static func lineDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection {
return NSLocale.lineDirection(forLanguage: isoLangCode)
}
// MARK: -
@available(*, unavailable, renamed: "init(identifier:)")
public init(localeIdentifier: String) { fatalError() }
@available(*, unavailable, renamed: "identifier")
public var localeIdentifier: String { fatalError() }
@available(*, unavailable, renamed: "localizedString(forIdentifier:)")
public func localizedString(forLocaleIdentifier localeIdentifier: String) -> String { fatalError() }
@available(*, unavailable, renamed: "availableIdentifiers")
public static var availableLocaleIdentifiers: [String] { fatalError() }
@available(*, unavailable, renamed: "components(fromIdentifier:)")
public static func components(fromLocaleIdentifier string: String) -> [String : String] { fatalError() }
@available(*, unavailable, renamed: "identifier(fromComponents:)")
public static func localeIdentifier(fromComponents dict: [String : String]) -> String { fatalError() }
@available(*, unavailable, renamed: "canonicalIdentifier(from:)")
public static func canonicalLocaleIdentifier(from string: String) -> String { fatalError() }
@available(*, unavailable, renamed: "identifier(fromWindowsLocaleCode:)")
public static func localeIdentifier(fromWindowsLocaleCode lcid: UInt32) -> String? { fatalError() }
@available(*, unavailable, renamed: "windowsLocaleCode(fromIdentifier:)")
public static func windowsLocaleCode(fromLocaleIdentifier localeIdentifier: String) -> UInt32 { fatalError() }
@available(*, unavailable, message: "use regionCode instead")
public var countryCode: String { fatalError() }
@available(*, unavailable, message: "use localizedString(forRegionCode:) instead")
public func localizedString(forCountryCode countryCode: String) -> String { fatalError() }
@available(*, unavailable, renamed: "isoRegionCodes")
public static var isoCountryCodes: [String] { fatalError() }
// MARK: -
//
public func hash(into hasher: inout Hasher) {
if _autoupdating {
hasher.combine(false)
} else {
hasher.combine(true)
hasher.combine(_wrapped)
}
}
public static func ==(lhs: Locale, rhs: Locale) -> Bool {
if lhs._autoupdating || rhs._autoupdating {
return lhs._autoupdating == rhs._autoupdating
} else {
return lhs._wrapped.isEqual(rhs._wrapped)
}
}
}
extension Locale : CustomDebugStringConvertible, CustomStringConvertible, CustomReflectable {
private var _kindDescription : String {
if self == Locale.autoupdatingCurrent {
return "autoupdatingCurrent"
} else if self == Locale.current {
return "current"
} else {
return "fixed"
}
}
public var customMirror : Mirror {
var c: [(label: String?, value: Any)] = []
c.append((label: "identifier", value: identifier))
c.append((label: "kind", value: _kindDescription))
return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
}
public var description: String {
return "\(identifier) (\(_kindDescription))"
}
public var debugDescription : String {
return "\(identifier) (\(_kindDescription))"
}
}
extension Locale : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSLocale {
return _wrapped
}
public static func _forceBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) {
if !_conditionallyBridgeFromObjectiveC(input, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) -> Bool {
result = Locale(reference: input)
return true
}
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSLocale?) -> Locale {
var result: Locale?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension NSLocale : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as Locale)
}
}
extension Locale : Codable {
private enum CodingKeys : Int, CodingKey {
case identifier
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let identifier = try container.decode(String.self, forKey: .identifier)
self.init(identifier: identifier)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.identifier, forKey: .identifier)
}
}
|
apache-2.0
|
1697dbf61f676f88bc59bab9c9cb51f4
| 38.299401 | 282 | 0.655645 | 5.054942 | false | false | false | false |
exyte/Macaw-Examples
|
HealthStat/HealthStat/CubicCurveAlgorithm.swift
|
1
|
6133
|
//
// BezierAlgorithm.swift
// TestExample
//
// Created by Julia Bulantseva on 27/10/16.
// Copyright © 2016 Julia Bulantseva. All rights reserved.
//
import Foundation
import UIKit
struct CubicCurveSegment
{
let controlPoint1: CGPoint
let controlPoint2: CGPoint
}
class CubicCurveAlgorithm
{
private var firstControlPoints: [CGPoint?] = []
private var secondControlPoints: [CGPoint?] = []
func controlPointsFromPoints(dataPoints: [CGPoint]) -> [CubicCurveSegment] {
firstControlPoints.removeAll()
secondControlPoints.removeAll()
//Number of Segments
let count = dataPoints.count - 1
//P0, P1, P2, P3 are the points for each segment, where P0 & P3 are the knots and P1, P2 are the control points.
if count == 1 {
let P0 = dataPoints[0]
let P3 = dataPoints[1]
//Calculate First Control Point
//3P1 = 2P0 + P3
let P1x = (2*P0.x + P3.x)/3
let P1y = (2*P0.y + P3.y)/3
firstControlPoints.append(CGPoint(x: P1x, y: P1y))
//Calculate second Control Point
//P2 = 2P1 - P0
let P2x = (2*P1x - P0.x)
let P2y = (2*P1y - P0.y)
secondControlPoints.append(CGPoint(x: P2x, y: P2y))
} else {
firstControlPoints = Array(repeating: nil, count: count)
var rhsArray = [CGPoint]()
//Array of Coefficients
var a = [Double]()
var b = [Double]()
var c = [Double]()
for i in 0 ..< count {
var rhsValueX: CGFloat = 0
var rhsValueY: CGFloat = 0
let P0 = dataPoints[i];
let P3 = dataPoints[i+1];
if i==0 {
a.append(0)
b.append(2)
c.append(1)
//rhs for first segment
rhsValueX = P0.x + 2*P3.x;
rhsValueY = P0.y + 2*P3.y;
} else if i == count-1 {
a.append(2)
b.append(7)
c.append(0)
//rhs for last segment
rhsValueX = 8*P0.x + P3.x;
rhsValueY = 8*P0.y + P3.y;
} else {
a.append(1)
b.append(4)
c.append(1)
rhsValueX = 4*P0.x + 2*P3.x;
rhsValueY = 4*P0.y + 2*P3.y;
}
rhsArray.append(CGPoint(x: rhsValueX, y: rhsValueY))
}
//Solve Ax=B. Use Tridiagonal matrix algorithm a.k.a Thomas Algorithm
for i in 1 ..< count {
let rhsValueX = rhsArray[i].x
let rhsValueY = rhsArray[i].y
let prevRhsValueX = rhsArray[i-1].x
let prevRhsValueY = rhsArray[i-1].y
let m = a[i]/b[i-1]
let b1 = b[i] - m * c[i-1];
b[i] = b1
let r2x = rhsValueX.f - m * prevRhsValueX.f
let r2y = rhsValueY.f - m * prevRhsValueY.f
rhsArray[i] = CGPoint(x: r2x, y: r2y)
}
//Get First Control Points
//Last control Point
let lastControlPointX = rhsArray[count-1].x.f/b[count-1]
let lastControlPointY = rhsArray[count-1].y.f/b[count-1]
firstControlPoints[count-1] = CGPoint(x: lastControlPointX, y: lastControlPointY)
var i = count-2
while i >= 0 {
if let nextControlPoint = firstControlPoints[i+1] {
let controlPointX = (rhsArray[i].x.f - c[i] * nextControlPoint.x.f)/b[i]
let controlPointY = (rhsArray[i].y.f - c[i] * nextControlPoint.y.f)/b[i]
firstControlPoints[i] = CGPoint(x: controlPointX, y: controlPointY)
}
i -= 1
}
//Compute second Control Points from first
for i in 0 ..< count {
if i == count-1 {
let P3 = dataPoints[i+1]
guard let P1 = firstControlPoints[i] else{
continue
}
let controlPointX = (P3.x + P1.x)/2
let controlPointY = (P3.y + P1.y)/2
secondControlPoints.append(CGPoint(x: controlPointX, y: controlPointY))
} else {
let P3 = dataPoints[i+1]
guard let nextP1 = firstControlPoints[i+1] else {
continue
}
let controlPointX = 2*P3.x - nextP1.x
let controlPointY = 2*P3.y - nextP1.y
secondControlPoints.append(CGPoint(x: controlPointX, y: controlPointY))
}
}
}
var controlPoints = [CubicCurveSegment]()
for i in 0 ..< count {
if let firstControlPoint = firstControlPoints[i],
let secondControlPoint = secondControlPoints[i] {
let segment = CubicCurveSegment(controlPoint1: firstControlPoint, controlPoint2: secondControlPoint)
controlPoints.append(segment)
}
}
return controlPoints
}
}
extension CGFloat {
var f: Double {
return Double(self)
}
}
|
mit
|
c2641295c2c9670f66718cf8f4c14ede
| 31.967742 | 120 | 0.427919 | 4.518791 | false | false | false | false |
FTChinese/iPhoneApp
|
FT Academy/PlaySpeech.swift
|
1
|
11833
|
//
// PlaySpeech.swift
// FT中文网
//
// Created by ZhangOliver on 2017/3/26.
// Copyright © 2017年 Financial Times Ltd. All rights reserved.
//
import UIKit
import AVKit
import AVFoundation
import MediaPlayer
// MARK: Further Reading: http://www.appcoda.com/text-to-speech-ios-tutorial/
// MARK: - Use singleton pattern to pass speech data between view controllers. It's better in in term of code style than prepare segue.
class SpeechContent {
static let sharedInstance = SpeechContent()
var body = [String: String]()
}
// MARK: - Remove HTML Tags from the Text
extension String {
private func deleteHTMLTag(_ tag:String) -> String {
return self.replacingOccurrences(of: "(?i)</?\(tag)\\b[^<]*>", with: "", options: .regularExpression)
}
func deleteHTMLTags(_ tags:[String]) -> String {
var mutableString = self
for tag in tags {
mutableString = mutableString.deleteHTMLTag(tag)
}
return mutableString
}
}
class PlaySpeech: UIViewController, AVSpeechSynthesizerDelegate,UIPopoverPresentationControllerDelegate {
private lazy var mySpeechSynthesizer:AVSpeechSynthesizer? = nil
private lazy var audioText: NSMutableAttributedString? = nil
private var audioLanguage = ""
private var eventCategory = ""
private var audioTitle = "FT中文网"
private lazy var previouseRange: NSRange? = nil
let speechDefaultVoice = SpeechDefaultVoice()
@IBOutlet weak var buttonPlayPause: UIBarButtonItem!
@IBAction func pauseSpeech(_ sender: UIBarButtonItem) {
var image = UIImage(named: "PauseButton")
if let mySpeechSynthesizer = mySpeechSynthesizer {
if mySpeechSynthesizer.isPaused == false && mySpeechSynthesizer.isSpeaking == false {
if let titleAndText = audioText?.string {
let mySpeechUtterance:AVSpeechUtterance = AVSpeechUtterance(string: titleAndText)
mySpeechUtterance.voice = AVSpeechSynthesisVoice(language: audioLanguage)
mySpeechSynthesizer.speak(mySpeechUtterance)
mySpeechSynthesizer.continueSpeaking()
}
} else if mySpeechSynthesizer.isPaused == false {
mySpeechSynthesizer.pauseSpeaking(at: .word)
image = UIImage(named: "PlayButton")
} else {
mySpeechSynthesizer.continueSpeaking()
}
}
buttonPlayPause.image = image
}
@IBAction func stopSpeech(_ sender: UIBarButtonItem) {
mySpeechSynthesizer?.stopSpeaking(at: .word)
mySpeechSynthesizer = nil
//print ("speech should stop now! ")
self.dismiss(animated: true, completion: nil)
}
@IBAction func setSpeechOptions(_ sender: UIBarButtonItem) {
//self.performSegue(withIdentifier: "Speech Settings", sender: sender)
// MARK: Use story board to avoid memory leak
let popoverVC = storyboard?.instantiateViewController(withIdentifier: "Speech Settings")
if let popover = popoverVC {
popover.modalPresentationStyle = .popover
present(popover, animated: true, completion: {
// MARK: - Setting the iPad popover arrow to pink. Only works in a completion handler.
self.popoverPresentationController?.backgroundColor = UIColor(netHex: 0xFFF1E0)
})
}
}
@IBOutlet weak var bodytext: UITextView!
deinit {
print ("deinit PlaySpeech successfully")
}
override func loadView() {
super.loadView()
parseAudioMessage()
enableBackGroundMode()
displayText()
// MARK: - listen to notifications about preference change
NotificationCenter.default.addObserver(
forName: Notification.Name(rawValue:"Replay Needed"),
object: nil,
queue: nil) { [weak self] notification in
self?.replay(notification: notification)
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
private func replay(notification:Notification) -> Void {
mySpeechSynthesizer?.stopSpeaking(at: .word)
parseAudioMessage()
if let titleAndText = audioText?.string {
let mySpeechUtterance:AVSpeechUtterance = AVSpeechUtterance(string: titleAndText)
mySpeechUtterance.voice = AVSpeechSynthesisVoice(language: audioLanguage)
mySpeechSynthesizer?.speak(mySpeechUtterance)
buttonPlayPause.image = UIImage(named: "PauseButton")
}
}
private func parseAudioMessage() {
let body = SpeechContent.sharedInstance.body
if let language = body["language"], let text = body["text"], let title = body["title"], let eventCategory = body["eventCategory"] {
let speechLanguage = speechDefaultVoice.getVoiceByLanguage(language)
self.audioLanguage = speechLanguage
self.eventCategory = eventCategory
self.audioTitle = title
let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.paragraphSpacing = 20
let titleAttributes = [
NSForegroundColorAttributeName: UIColor.black,
NSFontAttributeName: UIFont.boldSystemFont(ofSize: 22),
NSParagraphStyleAttributeName:titleParagraphStyle
]
let bodyParagraphStyle = NSMutableParagraphStyle()
bodyParagraphStyle.paragraphSpacing = 20
bodyParagraphStyle.lineSpacing = 10
let bodyAttributes = [
NSForegroundColorAttributeName: UIColor.black,
NSFontAttributeName: UIFont.systemFont(ofSize: 18),
NSParagraphStyleAttributeName:bodyParagraphStyle,
]
let titleAttrString = NSMutableAttributedString(
string: title,
attributes: titleAttributes
)
// MARK: - Use deliminator so that the utterance will pause after the title
let deliminatorAttributes = [
NSForegroundColorAttributeName: UIColor(netHex:0xFFF1E0),
NSFontAttributeName: UIFont.systemFont(ofSize: 0)
]
// MARK: - If it's Chinese, use "。", otherwise use ". "
let delimitorPeriodString: String
if language == "ch" {
delimitorPeriodString = "。"
} else {
delimitorPeriodString = ". "
}
let deliminatorAttrString = NSMutableAttributedString(
string: "\(delimitorPeriodString)\r\n",
attributes: deliminatorAttributes
)
let textFromHTML = text
.replacingOccurrences(of: "[\r\n]", with: "", options: .regularExpression, range: nil)
.replacingOccurrences(of: "(</p><p>)+", with: "\r\n", options: .regularExpression, range: nil)
let bodyAttrString = NSMutableAttributedString(
string: textFromHTML.deleteHTMLTags(["a","p","div","img","span","b","i"]),
attributes: bodyAttributes
)
let fullBodyAttrString = NSMutableAttributedString()
fullBodyAttrString.append(titleAttrString)
fullBodyAttrString.append(deliminatorAttrString)
fullBodyAttrString.append(bodyAttrString)
audioText = fullBodyAttrString
}
}
private func textToSpeech(_ text: NSMutableAttributedString, language: String) {
// MARK: - Continue audio even when device is set to mute
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
// MARK: - Continue audio when device is in background
try? AVAudioSession.sharedInstance().setActive(true)
mySpeechSynthesizer = AVSpeechSynthesizer()
let titleAndText = text.string
let mySpeechUtterance:AVSpeechUtterance = AVSpeechUtterance(string: titleAndText)
// MARK: Set lguange. Chinese is zh-CN
mySpeechUtterance.voice = AVSpeechSynthesisVoice(language: language)
// mySpeechUtterance.rate = 1.0
mySpeechSynthesizer?.delegate = self
mySpeechSynthesizer?.speak(mySpeechUtterance)
//MARK: - Update the Lock Screen Image
NowPlayingCenter().updateInfo(
title: audioTitle,
artist: "FT中文网",
albumArt: UIImage(named: "cover.jpg"),
currentTime: 0,
mediaLength: 0,
PlaybackRate: 1.0
)
}
private func enableBackGroundMode() {
// MARK: Receive Messages from Lock Screen
UIApplication.shared.beginReceivingRemoteControlEvents();
MPRemoteCommandCenter.shared().playCommand.addTarget {[weak self] event in
print("resume music")
self?.mySpeechSynthesizer?.continueSpeaking()
return .success
}
MPRemoteCommandCenter.shared().pauseCommand.addTarget {[weak self] event in
print ("pause speech")
self?.mySpeechSynthesizer?.pauseSpeaking(at: .word)
return .success
}
// MPRemoteCommandCenter.shared().nextTrackCommand.addTarget {event in
// print ("next audio")
// return .success
// }
// MPRemoteCommandCenter.shared().previousTrackCommand.addTarget {event in
// print ("previous audio")
// return .success
// }
}
private func displayText() {
if let audioText = audioText {
self.bodytext.attributedText = audioText
self.bodytext.scrollRangeToVisible(NSRange(location:0, length:0))
textToSpeech(audioText, language: audioLanguage)
}
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {
if let mutableAttributedString = audioText {
if let previouseRange = previouseRange {
mutableAttributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.black, range: previouseRange)
}
mutableAttributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor(netHex:0xF6801A), range: characterRange)
self.bodytext.attributedText = mutableAttributedString
self.bodytext.scrollRangeToVisible(characterRange)
}
previouseRange = characterRange
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
if let mutableAttributedString = audioText {
if let previouseRange = previouseRange {
mutableAttributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.black, range: previouseRange)
self.bodytext.attributedText = mutableAttributedString
self.bodytext.scrollRangeToVisible(previouseRange)
}
}
let body = SpeechContent.sharedInstance.body
if let language = body["language"], let title = body["title"] {
if let rootViewController = UIApplication.shared.windows[0].rootViewController as? ViewController {
let jsCode = "ga('send','event','\(eventCategory)', 'Finish', '\(language): \(title.replacingOccurrences(of: "'", with: ""))');"
rootViewController.webView.evaluateJavaScript(jsCode) { (result, error) in
}
}
}
let image = UIImage(named: "PlayButton")
buttonPlayPause.image = image
}
}
|
mit
|
fd3e1a0aa2203aaa8aed5e7223a32fd0
| 41.171429 | 148 | 0.629573 | 5.530679 | false | false | false | false |
huonw/swift
|
test/SILGen/nested_generics.swift
|
3
|
14703
|
// RUN: %target-swift-emit-silgen -module-name nested_generics -enable-sil-ownership -Xllvm -sil-full-demangle -parse-as-library %s | %FileCheck %s
// RUN: %target-swift-emit-sil -module-name nested_generics -enable-sil-ownership -Xllvm -sil-full-demangle -parse-as-library %s > /dev/null
// RUN: %target-swift-emit-sil -module-name nested_generics -enable-sil-ownership -Xllvm -sil-full-demangle -O -parse-as-library %s > /dev/null
// RUN: %target-swift-emit-ir -module-name nested_generics -enable-sil-ownership -Xllvm -sil-full-demangle -parse-as-library %s > /dev/null
// TODO:
// - test generated SIL -- mostly we're just testing mangling here
// - class_method calls
// - witness_method calls
// - inner generic parameters on protocol requirements
// - generic parameter list on method in nested type
// - types nested inside unconstrained extensions of generic types
protocol Pizza : class {
associatedtype Topping
}
protocol HotDog {
associatedtype Condiment
}
protocol CuredMeat {}
// Generic nested inside generic
struct Lunch<T : Pizza> where T.Topping : CuredMeat {
struct Dinner<U : HotDog> where U.Condiment == Deli<Pepper>.Mustard {
let firstCourse: T
let secondCourse: U?
var leftovers: T
var transformation: (T) -> U
func coolCombination(t: T.Topping, u: U.Condiment) {
func nestedGeneric<X, Y>(x: X, y: Y) -> (X, Y) {
return (x, y)
}
_ = nestedGeneric(x: t, y: u)
}
}
}
// CHECK-LABEL: // nested_generics.Lunch.Dinner.coolCombination(t: A.Topping, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()
// CHECK-LABEL: sil hidden @$S15nested_generics5LunchV6DinnerV15coolCombination1t1uy7ToppingQz_AA4DeliC7MustardOyAA6PepperV_GtF : $@convention(method) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard> (@in_guaranteed T.Topping, Deli<Pepper>.Mustard, @in_guaranteed Lunch<T>.Dinner<U>) -> ()
// CHECK-LABEL: // nestedGeneric #1 <A><A1><A2, B2 where A: nested_generics.Pizza, A1: nested_generics.HotDog, A.Topping: nested_generics.CuredMeat, A1.Condiment == nested_generics.Deli<nested_generics.Pepper>.Mustard>(x: A2, y: B2) -> (A2, B2) in nested_generics.Lunch.Dinner.coolCombination(t: A.Topping, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()
// CHECK-LABEL: sil private @$S15nested_generics5LunchV6DinnerV15coolCombination1t1uy7ToppingQz_AA4DeliC7MustardOyAA6PepperV_GtF0A7GenericL_1x1yqd0___qd0_0_tqd0___qd0_0_tAA5PizzaRzAA6HotDogRd__AA9CuredMeatAJRQAQ9CondimentRtd__r__0_lF : $@convention(thin) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard><X, Y> (@in_guaranteed X, @in_guaranteed Y) -> (@out X, @out Y)
// CHECK-LABEL: // nested_generics.Lunch.Dinner.init(firstCourse: A, secondCourse: Swift.Optional<A1>, leftovers: A, transformation: (A) -> A1) -> nested_generics.Lunch<A>.Dinner<A1>
// CHECK-LABEL: sil hidden @$S15nested_generics5LunchV6DinnerV11firstCourse06secondF09leftovers14transformationAEyx_qd__Gx_qd__Sgxqd__xctcfC : $@convention(method) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard> (@owned T, @in Optional<U>, @owned T, @owned @callee_guaranteed (@guaranteed T) -> @out U, @thin Lunch<T>.Dinner<U>.Type) -> @out Lunch<T>.Dinner<U>
// Non-generic nested inside generic
class Deli<Spices> : CuredMeat {
class Pepperoni : CuredMeat {}
struct Sausage : CuredMeat {}
enum Mustard {
case Yellow
case Dijon
case DeliStyle(Spices)
}
}
// CHECK-LABEL: // nested_generics.Deli.Pepperoni.init() -> nested_generics.Deli<A>.Pepperoni
// CHECK-LABEL: sil hidden @$S15nested_generics4DeliC9PepperoniCAEyx_Gycfc : $@convention(method) <Spices> (@owned Deli<Spices>.Pepperoni) -> @owned Deli<Spices>.Pepperoni
// Typealiases referencing outer generic parameters
struct Pizzas<Spices> {
class NewYork : Pizza {
typealias Topping = Deli<Spices>.Pepperoni
}
class DeepDish : Pizza {
typealias Topping = Deli<Spices>.Sausage
}
}
class HotDogs {
struct Bratwurst : HotDog {
typealias Condiment = Deli<Pepper>.Mustard
}
struct American : HotDog {
typealias Condiment = Deli<Pepper>.Mustard
}
}
// Local type in extension of type in another module
extension String {
func foo() {
// CHECK-LABEL: // init(material: A) -> Cheese #1 in (extension in nested_generics):Swift.String.foo() -> ()<A> in Cheese #1 in (extension in nested_generics):Swift.String.foo() -> ()
// CHECK-LABEL: sil private @$SSS15nested_genericsE3fooyyF6CheeseL_V8materialADyxGx_tcfC
struct Cheese<Milk> {
let material: Milk
}
let _ = Cheese(material: "cow")
}
}
// Local type in extension of type in same module
extension HotDogs {
func applyRelish() {
// CHECK-LABEL: // init(material: A) -> Relish #1 in nested_generics.HotDogs.applyRelish() -> ()<A> in Relish #1 in nested_generics.HotDogs.applyRelish() -> ()
// CHECK-LABEL: sil private @$S15nested_generics7HotDogsC11applyRelishyyF0F0L_V8materialAFyxGx_tcfC
struct Relish<Material> {
let material: Material
}
let _ = Relish(material: "pickles")
}
}
struct Pepper {}
struct ChiliFlakes {}
// CHECK-LABEL: // nested_generics.eatDinnerGeneric<A, B where A: nested_generics.Pizza, B: nested_generics.HotDog, A.Topping: nested_generics.CuredMeat, B.Condiment == nested_generics.Deli<nested_generics.Pepper>.Mustard>(d: inout nested_generics.Lunch<A>.Dinner<B>, t: A.Topping, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()
// CHECK-LABEL: sil hidden @$S15nested_generics16eatDinnerGeneric1d1t1uyAA5LunchV0D0Vyx_q_Gz_7ToppingQzAA4DeliC7MustardOyAA6PepperV_GtAA5PizzaRzAA6HotDogR_AA9CuredMeatALRQAS9CondimentRt_r0_lF : $@convention(thin) <T, U where T : Pizza, U : HotDog, T.Topping : CuredMeat, U.Condiment == Deli<Pepper>.Mustard> (@inout Lunch<T>.Dinner<U>, @in_guaranteed T.Topping, Deli<Pepper>.Mustard) -> ()
func eatDinnerGeneric<T, U>(d: inout Lunch<T>.Dinner<U>, t: T.Topping, u: U.Condiment) {
// Method call
_ = d.coolCombination(t: t, u: u)
// Read a let, store into var
d.leftovers = d.firstCourse
// Read a var
let _ = d.secondCourse
// Call property of function type
_ = d.transformation(d.leftovers)
}
// Overloading concrete function with different bound generic arguments in parent type
// CHECK-LABEL: // nested_generics.eatDinnerConcrete(d: inout nested_generics.Lunch<nested_generics.Pizzas<nested_generics.ChiliFlakes>.NewYork>.Dinner<nested_generics.HotDogs.American>, t: nested_generics.Deli<nested_generics.ChiliFlakes>.Pepperoni, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()
// CHECK-LABEL: sil hidden @$S15nested_generics17eatDinnerConcrete1d1t1uyAA5LunchV0D0VyAA6PizzasV7NewYorkCyAA11ChiliFlakesV_G_AA7HotDogsC8AmericanVGz_AA4DeliC9PepperoniCyAO_GAW7MustardOyAA6PepperV_GtF : $@convention(thin) (@inout Lunch<Pizzas<ChiliFlakes>.NewYork>.Dinner<HotDogs.American>, @guaranteed Deli<ChiliFlakes>.Pepperoni, Deli<Pepper>.Mustard) -> ()
func eatDinnerConcrete(d: inout Lunch<Pizzas<ChiliFlakes>.NewYork>.Dinner<HotDogs.American>,
t: Deli<ChiliFlakes>.Pepperoni,
u: Deli<Pepper>.Mustard) {
// Method call
_ = d.coolCombination(t: t, u: u)
// Read a let, store into var
d.leftovers = d.firstCourse
// Read a var
let _ = d.secondCourse
// Call property of function type
_ = d.transformation(d.leftovers)
}
// CHECK-LABEL: // reabstraction thunk helper from @escaping @callee_guaranteed (@guaranteed nested_generics.Pizzas<nested_generics.ChiliFlakes>.NewYork) -> (@out nested_generics.HotDogs.American) to @escaping @callee_guaranteed (@guaranteed nested_generics.Pizzas<nested_generics.ChiliFlakes>.NewYork) -> (@unowned nested_generics.HotDogs.American)
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S15nested_generics6PizzasV7NewYorkCyAA11ChiliFlakesV_GAA7HotDogsC8AmericanVIeggr_AhLIeggd_TR : $@convention(thin) (@guaranteed Pizzas<ChiliFlakes>.NewYork, @guaranteed @callee_guaranteed (@guaranteed Pizzas<ChiliFlakes>.NewYork) -> @out HotDogs.American) -> HotDogs.American
// CHECK-LABEL: // nested_generics.eatDinnerConcrete(d: inout nested_generics.Lunch<nested_generics.Pizzas<nested_generics.Pepper>.NewYork>.Dinner<nested_generics.HotDogs.American>, t: nested_generics.Deli<nested_generics.Pepper>.Pepperoni, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()
// CHECK-LABEL: sil hidden @$S15nested_generics17eatDinnerConcrete1d1t1uyAA5LunchV0D0VyAA6PizzasV7NewYorkCyAA6PepperV_G_AA7HotDogsC8AmericanVGz_AA4DeliC9PepperoniCyAO_GAW7MustardOyAO_GtF : $@convention(thin) (@inout Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>, @guaranteed Deli<Pepper>.Pepperoni, Deli<Pepper>.Mustard) -> ()
func eatDinnerConcrete(d: inout Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>,
t: Deli<Pepper>.Pepperoni,
u: Deli<Pepper>.Mustard) {
// Method call
_ = d.coolCombination(t: t, u: u)
// Read a let, store into var
d.leftovers = d.firstCourse
// Read a var
let _ = d.secondCourse
// Call property of function type
_ = d.transformation(d.leftovers)
}
// CHECK-LABEL: // reabstraction thunk helper from @escaping @callee_guaranteed (@guaranteed nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@out nested_generics.HotDogs.American) to @escaping @callee_guaranteed (@guaranteed nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@unowned nested_generics.HotDogs.American)
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S15nested_generics6PizzasV7NewYorkCyAA6PepperV_GAA7HotDogsC8AmericanVIeggr_AhLIeggd_TR : $@convention(thin) (@guaranteed Pizzas<Pepper>.NewYork, @guaranteed @callee_guaranteed (@guaranteed Pizzas<Pepper>.NewYork) -> @out HotDogs.American) -> HotDogs.American
// CHECK-LABEL: // closure #1 (nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> nested_generics.HotDogs.American in nested_generics.calls() -> ()
// CHECK-LABEL: sil private @$S15nested_generics5callsyyFAA7HotDogsC8AmericanVAA6PizzasV7NewYorkCyAA6PepperV_GcfU_ : $@convention(thin) (@guaranteed Pizzas<Pepper>.NewYork) -> HotDogs.American
func calls() {
let firstCourse = Pizzas<Pepper>.NewYork()
let secondCourse = HotDogs.American()
var dinner = Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>(
firstCourse: firstCourse,
secondCourse: secondCourse,
leftovers: firstCourse,
transformation: { _ in HotDogs.American() })
let topping = Deli<Pepper>.Pepperoni()
let condiment1 = Deli<Pepper>.Mustard.Dijon
let condiment2 = Deli<Pepper>.Mustard.DeliStyle(Pepper())
eatDinnerGeneric(d: &dinner, t: topping, u: condiment1)
eatDinnerConcrete(d: &dinner, t: topping, u: condiment2)
}
protocol ProtocolWithGenericRequirement {
associatedtype T
associatedtype U
func method<V>(t: T, u: U, v: V) -> (T, U, V)
}
class OuterRing<T> {
class InnerRing<U> : ProtocolWithGenericRequirement {
func method<V>(t: T, u: U, v: V) -> (T, U, V) {
return (t, u, v)
}
}
}
class SubclassOfInner<T, U> : OuterRing<T>.InnerRing<U> {
override func method<V>(t: T, u: U, v: V) -> (T, U, V) {
return super.method(t: t, u: u, v: v)
}
}
// CHECK-LABEL: // reabstraction thunk helper from @escaping @callee_guaranteed (@guaranteed nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@unowned nested_generics.HotDogs.American) to @escaping @callee_guaranteed (@guaranteed nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@out nested_generics.HotDogs.American)
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S15nested_generics6PizzasV7NewYorkCyAA6PepperV_GAA7HotDogsC8AmericanVIeggd_AhLIeggr_TR : $@convention(thin) (@guaranteed Pizzas<Pepper>.NewYork, @guaranteed @callee_guaranteed (@guaranteed Pizzas<Pepper>.NewYork) -> HotDogs.American) -> @out HotDogs.American
// CHECK-LABEL: sil private [transparent] [thunk] @$S15nested_generics9OuterRingC05InnerD0Cyx_qd__GAA30ProtocolWithGenericRequirementA2aGP6method1t1u1v1TQz_1UQzqd__tAN_APqd__tlFTW : $@convention(witness_method: ProtocolWithGenericRequirement) <τ_0_0><τ_1_0><τ_2_0> (@in_guaranteed τ_0_0, @in_guaranteed τ_1_0, @in_guaranteed τ_2_0, @in_guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0) {
// CHECK: bb0([[T:%[0-9]+]] : @trivial $*τ_0_0, [[U:%[0-9]+]] : @trivial $*τ_1_0, [[V:%[0-9]+]] : @trivial $*τ_2_0, [[TOut:%[0-9]+]] : @trivial $*τ_0_0, [[UOut:%[0-9]+]] : @trivial $*τ_1_0, [[VOut:%[0-9]+]] : @trivial $*τ_2_0, [[SELF:%[0-9]+]] : @trivial $*OuterRing<τ_0_0>.InnerRing<τ_1_0>):
// CHECK: [[SELF_COPY_VAL:%[0-9]+]] = load_borrow [[SELF]] : $*OuterRing<τ_0_0>.InnerRing<τ_1_0>
// CHECK: [[METHOD:%[0-9]+]] = class_method [[SELF_COPY_VAL]] : $OuterRing<τ_0_0>.InnerRing<τ_1_0>, #OuterRing.InnerRing.method!1 : <T><U><V> (OuterRing<T>.InnerRing<U>) -> (T, U, V) -> (T, U, V), $@convention(method) <τ_0_0><τ_1_0><τ_2_0> (@in_guaranteed τ_0_0, @in_guaranteed τ_1_0, @in_guaranteed τ_2_0, @guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0)
// CHECK: apply [[METHOD]]<τ_0_0, τ_1_0, τ_2_0>([[T]], [[U]], [[V]], [[TOut]], [[UOut]], [[VOut]], [[SELF_COPY_VAL]]) : $@convention(method) <τ_0_0><τ_1_0><τ_2_0> (@in_guaranteed τ_0_0, @in_guaranteed τ_1_0, @in_guaranteed τ_2_0, @guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0)
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: end_borrow [[SELF_COPY_VAL]] from [[SELF]]
// CHECK: return [[RESULT]] : $()
// CHECK: sil_witness_table hidden <Spices> Deli<Spices>.Pepperoni: CuredMeat module nested_generics {
// CHECK: }
// CHECK: sil_witness_table hidden <Spices> Deli<Spices>.Sausage: CuredMeat module nested_generics {
// CHECK: }
// CHECK: sil_witness_table hidden <Spices> Deli<Spices>: CuredMeat module nested_generics {
// CHECK: }
// CHECK: sil_witness_table hidden <Spices> Pizzas<Spices>.NewYork: Pizza module nested_generics {
// CHECK: associated_type Topping: Deli<Spices>.Pepperoni
// CHECK: }
// CHECK: sil_witness_table hidden <Spices> Pizzas<Spices>.DeepDish: Pizza module nested_generics {
// CHECK: associated_type Topping: Deli<Spices>.Sausage
// CHECK: }
// CHECK: sil_witness_table hidden HotDogs.Bratwurst: HotDog module nested_generics {
// CHECK: associated_type Condiment: Deli<Pepper>.Mustard
// CHECK: }
// CHECK: sil_witness_table hidden HotDogs.American: HotDog module nested_generics {
// CHECK: associated_type Condiment: Deli<Pepper>.Mustard
// CHECK: }
|
apache-2.0
|
dcdd7f21d7647b4918bd392226b9b03b
| 55.149425 | 423 | 0.715319 | 3.317112 | false | false | false | false |
nikriek/gesundheit.space
|
NotYet/Evidence.swift
|
1
|
1130
|
//
// Evidence.swift
// NotYet
//
// Created by Niklas Riekenbrauck on 26.11.16.
// Copyright © 2016 Niklas Riekenbrauck. All rights reserved.
//
import Foundation
final class Evidence: ResponseObjectSerializable, ResponseCollectionSerializable {
var id: Int
var measurementName: String
var measurementValue: Double
var cohortMeasurementValue: Double
var url: String?
required init?(response: HTTPURLResponse, representation: Any) {
guard let representation = representation as? [String: Any],
let id = representation["id"] as? Int,
let measurementName = representation["measurement_name"] as? String,
let measurementValue = representation["measurement_value"] as? Double,
let cohortMeasurementValue = representation["cohort_measurement_value"] as? Double else {
return nil
}
self.id = id
self.measurementName = measurementName
self.measurementValue = measurementValue
self.cohortMeasurementValue = cohortMeasurementValue
self.url = representation["url"] as? String
}
}
|
mit
|
44db9aa4b8739aa8f12f15cfb1723812
| 34.28125 | 101 | 0.681134 | 4.684647 | false | false | false | false |
haranicle/SwiftTestingSample
|
SwiftTestingSample/Item.swift
|
1
|
859
|
//
// Item.swift
// SwiftTestingSample
//
// Created by haranicle on 2014/07/11.
// Copyright (c) 2014年 haranicle. All rights reserved.
//
import Foundation
class Item : NSObject {
var id:String = ""
var title:String
var price:Int
var type:String
init(title:String, price:Int, type:String){
self.title = title
self.price = price
self.type = type
// self.id = generateId()
}
func generateId() -> String {
return "id-\(type)-\(title)"
}
func totalPrice(count:Int) -> Int {
return price * count
}
override func isEqual(other: AnyObject!) -> Bool {
if(other.id == id && other.title == title && other.price == price && other.type == type) {
return true
}
return false
}
}
|
mit
|
42ee78f384514416edebf649b70137f4
| 18.953488 | 98 | 0.533256 | 3.967593 | false | false | false | false |
Jnosh/swift
|
test/Generics/unbound.swift
|
5
|
2549
|
// RUN: %target-typecheck-verify-swift
// Verify the use of unbound generic types. They are permitted in
// certain places where type inference can fill in the generic
// arguments, and banned everywhere else.
// --------------------------------------------------
// Places where generic arguments are always required
// --------------------------------------------------
struct Foo<T> { // expected-note 3{{generic type 'Foo' declared here}}
struct Wibble { }
}
class Dict<K, V> { } // expected-note{{generic type 'Dict' declared here}} expected-note{{generic type 'Dict' declared here}} expected-note{{generic type 'Dict' declared here}}
// The underlying type of a typealias can only have unbound generic arguments
// at the top level.
typealias F = Foo // OK
typealias FW = Foo.Wibble // expected-error{{reference to generic type 'Foo' requires arguments in <...>}}
typealias FFW = () -> Foo // expected-error{{reference to generic type 'Foo' requires arguments in <...>}}
typealias OFW = Optional<() -> Foo> // expected-error{{reference to generic type 'Foo' requires arguments in <...>}}
// Cannot inherit from a generic type without arguments.
class MyDict : Dict { } // expected-error{{reference to generic type 'Dict' requires arguments in <...>}}
// Cannot create variables of a generic type without arguments.
// FIXME: <rdar://problem/14238814> would allow it for local variables
// only
var x : Dict // expected-error{{reference to generic type 'Dict' requires arguments in <...>}}
// Cannot create parameters of generic type without arguments.
func f(x: Dict) {} // expected-error{{reference to generic type 'Dict' requires arguments in <...>}}
class GC<T, U> {
init() {}
func f() -> GC {
let gc = GC()
return gc
}
}
extension GC {
func g() -> GC {
let gc = GC()
return gc
}
}
class SomeClassWithInvalidMethod {
func method<T>() { // expected-error {{generic parameter 'T' is not used in function signature}}
self.method()
}
}
// <rdar://problem/20792596> QoI: Cannot invoke with argument list (T), expected an argument list of (T)
protocol r20792596P {}
// expected-note @+1 {{in call to function 'foor20792596'}}
func foor20792596<T: r20792596P>(x: T) -> T {
return x
}
func callfoor20792596<T>(x: T) -> T {
return foor20792596(x) // expected-error {{generic parameter 'T' could not be inferred}}
}
// <rdar://problem/31181895> parameter "not used in function signature" when part of a superclass constraint
struct X1<T> {
func bar<U>() where T: X2<U> {}
}
class X2<T> {}
|
apache-2.0
|
77ff4f83989a8f5697723c69a826d767
| 32.986667 | 176 | 0.661436 | 3.833083 | false | false | false | false |
rayho/CodePathTwitter
|
CodePathTwitter/LaunchController.swift
|
1
|
2458
|
//
// LaunchController.swift
// CodePathTwitter
//
// Created by Ray Ho on 9/29/14.
// Copyright (c) 2014 Prime Rib Software. All rights reserved.
//
import UIKit
class LaunchController: UIViewController {
var signInButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Subscribe to events
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onAuthSuccess:", name: TWTR_NOTIF_AUTH_SUCCESS, object: nil)
// Load views
self.view.backgroundColor = UIColor.whiteColor()
signInButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
signInButton.setTranslatesAutoresizingMaskIntoConstraints(false)
signInButton.setTitle("Sign In", forState: UIControlState.Normal)
signInButton.addTarget(self, action: "signIn:", forControlEvents: UIControlEvents.TouchUpInside)
signInButton.titleLabel!.numberOfLines = 0
self.view.addSubview(signInButton)
self.view.layoutIfNeeded()
let viewDictionary = ["signInButton": signInButton]
self.view.addConstraint(NSLayoutConstraint(item: signInButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: signInButton, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Determine whether we should:
// Ask user to log in (not logged in yet)
// -- OR --
// Jump to home timeline (already logged in)
if (TWTR.isAuthorized()) {
NSLog("Already signed in.")
signInButton.hidden = true
launchTimeline()
} else {
NSLog("Not signed in.")
signInButton.hidden = false
}
}
func signIn(sender: AnyObject) {
NSLog("Signing in ...")
TWTR.requestAuth()
}
func onAuthSuccess(sender: AnyObject) {
NSLog("Signed in.")
launchTimeline()
}
func launchTimeline() {
NSLog("Launching timeline ...")
TimelineController.launch(self)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
|
mit
|
d7d9e313f0bfd3b031cae04af6c53850
| 34.623188 | 229 | 0.66965 | 5.00611 | false | false | false | false |
swiftde/27-CoreLocation
|
CoreLocation-Tutorial/CoreLocation-Tutorial/ViewController.swift
|
2
|
2212
|
//
// ViewController.swift
// CoreLocation-Tutorial
//
// Created by Benjamin Herzog on 06.09.14.
// Copyright (c) 2014 Benjamin Herzog. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var latitudeLabel: UILabel!
@IBOutlet weak var longitudeLabel: UILabel!
@IBOutlet weak var adressLabel: UILabel!
@IBOutlet weak var button: UIButton!
var manager = CLLocationManager()
var geocoder = CLGeocoder()
var placeMark: CLPlacemark?
// MARK: - ViewController-Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
manager.requestAlwaysAuthorization()
}
// MARK: - CLLocationManagerDelegate
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("ERROR: \(error.localizedDescription)")
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
println("new Location: \(manager.location)")
let currentLocation = manager.location
if currentLocation != nil {
latitudeLabel.text = "\(currentLocation.coordinate.latitude)"
longitudeLabel.text = "\(currentLocation.coordinate.longitude)"
geocoder.reverseGeocodeLocation(currentLocation, completionHandler: {
placemarks, error in
if error == nil && placemarks.count > 0 {
self.placeMark = placemarks.last as? CLPlacemark
self.adressLabel.text = "\(self.placeMark!.thoroughfare)\n\(self.placeMark!.postalCode) \(self.placeMark!.locality)\n\(self.placeMark!.country)"
self.manager.stopUpdatingLocation()
self.button.enabled = true
}
})
}
}
// MARK: - IBActions
@IBAction func buttonPressed(sender: AnyObject) {
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.startUpdatingLocation()
button.enabled = false
}
}
|
gpl-2.0
|
43e248c4f67cd2fb5f02e75c721d5f12
| 23.307692 | 164 | 0.624322 | 5.657289 | false | false | false | false |
devyu/FileViewer
|
FileViewer/ViewController.swift
|
1
|
5541
|
//
// ViewController.swift
// FileViewer
//
// Created by mac on 12/10/15.
// Copyright © 2015 JY. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var statusLabel: NSTextField!
@IBOutlet weak var tableView: NSTableView!
let sizeFormatter = NSByteCountFormatter()
var directory:Directory?
var directoryItems:[Metadata]?
var sortOrder = Directory.FileOrder.Name
var sortAscending = true
override func viewDidLoad() {
super.viewDidLoad()
statusLabel.stringValue = ""
tableView.setDataSource(self)
tableView.setDelegate(self)
// note: Double-click notifications are sent as an anction to the view target. Recive those notifications in the view controller, you need to set the table view 'target' and 'doubleAction' properties.
// This tell table view that the view coontroller will become the target for this actions, and then it sets the method that will be called after a double-click.
tableView.target = self
tableView.doubleAction = "tableViewDoubleClick:"
// Creat the sort descriptions:
let descriptionName = NSSortDescriptor(key: Directory.FileOrder.Name.rawValue, ascending: true)
let descriptionDate = NSSortDescriptor(key: Directory.FileOrder.Date.rawValue, ascending: true)
let descriptionSize = NSSortDescriptor(key: Directory.FileOrder.Size.rawValue, ascending: true)
// Add the sort description for the every colum by setting its 'sortDescriptorPrototype'
tableView.tableColumns[0].sortDescriptorPrototype = descriptionName
tableView.tableColumns[1].sortDescriptorPrototype = descriptionDate
tableView.tableColumns[2].sortDescriptorPrototype = descriptionSize
}
override var representedObject: AnyObject? {
didSet {
if let url = representedObject as? NSURL {
// print("Represented object: \(url)")
directory = Directory(folderURL: url)
reloadFileList()
}
}
}
func reloadFileList() {
directoryItems = directory?.contentsOrderedBy(sortOrder, ascending: sortAscending)
tableView.reloadData()
}
func updateStatus() {
let text: String
let itemsSelected = tableView.selectedRowIndexes.count
if directoryItems == nil { text = "" }
else if itemsSelected == 0 { text = "\(directoryItems!.count) items" }
else { text = "\(itemsSelected) of \(directoryItems!.count) selected" }
statusLabel.stringValue = text
}
// MARK: tableView double-click action method
func tableViewDoubleClick(sender: AnyObject) {
// 1. If the table view selection is empty, or 'tableView.selectedRow' value equal to -1
guard tableView.selectedRow >= 0 , let item = directoryItems?[tableView.selectedRow]
else { return }
// 2. If the item is a folder, it set a representedObject property to the item's url. The the table view refreshs to show the contents of that folder.
if item.isFolder {
self.representedObject = item.url;
} else {
// 3. If the item is a file, it open it in the defalut application by calling NSWorkspace method 'openUrl:'
NSWorkspace.sharedWorkspace().openURL(item.url)
}
}
}
// MARK: NSTableViewDataSource
extension ViewController: NSTableViewDataSource {
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return directoryItems?.count ?? 0
}
// MARK: When the user clicks on any column header, the table view will call the data source
func tableView(tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
// 1. Retrieves the first sort descriptor that corresponds to the column header clicked by the user.
guard let sortDescriptor = tableView.sortDescriptors.first else { return }
if let order = Directory.FileOrder(rawValue: sortDescriptor.key!) {
// 2. Assigns the 'sortOrder' and 'sortAscending' propertis of the view controller, and tell table view reload the data
sortOrder = order
sortAscending = sortDescriptor.ascending
reloadFileList()
}
reloadFileList()
}
}
// MARK: NSTableViewDelegate
extension ViewController: NSTableViewDelegate {
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
var image: NSImage?
var text: String = ""
var cellIdentifier: String = ""
// 1: If there is no date to display, it return no cell
guard let item = directoryItems?[row] else { return nil }
// 2: Based on the column where the cell will display(Name, Date, Size), it sets the cell identifier, text and imageg
if tableColumn == tableView.tableColumns[0] {
image = item.icon
text = item.name
cellIdentifier = "NameCellID"
} else if tableColumn == tableView.tableColumns[1] {
text = item.date.description
cellIdentifier = "DateCellID"
} else if tableColumn == tableView.tableColumns[2] {
text = item.isFolder ? "--" : sizeFormatter.stringFromByteCount(item.size)
cellIdentifier = "SizeCellID"
}
// 3: Creats or reuses a cell with that identifier.
if let cell = tableView.makeViewWithIdentifier(cellIdentifier, owner: nil) as? NSTableCellView {
cell.textField?.stringValue = text
cell.imageView?.image = image ?? nil
return cell
}
return nil
}
func tableViewSelectionDidChange(notification: NSNotification) {
updateStatus()
}
}
|
mit
|
7c41fcbe5bad35dd6827ab720009a013
| 29.949721 | 204 | 0.698917 | 4.788245 | false | false | false | false |
blomma/stray
|
stray/CloudKitStack.swift
|
1
|
4396
|
//
// Created by Mikael Hultgren on 2016-10-06.
// Copyright © 2016 Artsoftheinsane. All rights reserved.
//
import Foundation
import CloudKit
class CloudKitStack {
let queue: DispatchQueue = DispatchQueue(label: "com.artsoftheinsane.cloudsync", qos: .userInitiated)
func sync(
insertedRecords: [CKRecord]?,
updatedRecords: [CKRecord]?,
deletedRecords: [CKRecordID]?) {
queue.async { [weak self] in
self?.run(
insertedRecords: insertedRecords,
updatedRecords: updatedRecords,
deletedRecords: deletedRecords)
}
}
private func run(insertedRecords: [CKRecord]? = nil, updatedRecords: [CKRecord]? = nil, deletedRecords: [CKRecordID]? = nil) {
DLog("insertedRecords: \(String(describing: insertedRecords)) - updatedRecords: \(String(describing: updatedRecords)) - deletedRecords: \(String(describing: deletedRecords))")
let database = CKContainer.default().privateCloudDatabase
let modifyRecordZonesOperation = CKModifyRecordZonesOperation()
let insertRecordsOperation = CKModifyRecordsOperation()
insertRecordsOperation.recordsToSave = insertedRecords
insertRecordsOperation.modifyRecordsCompletionBlock = {
(savedRecords, deletedRecordIDs, error) in
DLog("insertRecordsOperation: \(String(describing: savedRecords)) - \(String(describing: deletedRecordIDs)) - \(String(describing: error))")
}
insertRecordsOperation.addDependency(modifyRecordZonesOperation)
let fetchRecordsOperation = CKFetchRecordsOperation()
fetchRecordsOperation.addDependency(insertRecordsOperation)
// Insert
if let insertedRecords = insertedRecords, insertedRecords.count > 0 {
var expectedZoneNames = Set(insertedRecords.map {
$0.recordID.zoneID.zoneName
})
let fetchAllRecordZonesOperation = CKFetchRecordZonesOperation.fetchAllRecordZonesOperation()
fetchAllRecordZonesOperation.fetchRecordZonesCompletionBlock = { (recordZonesByZoneID, error) in
DLog("fetchAllRecordZonesOperation: \(String(describing: recordZonesByZoneID)) - \(String(describing: error))")
if let zones = recordZonesByZoneID {
let serverZoneNames = Set(zones.map { $0.key.zoneName })
expectedZoneNames.subtract(serverZoneNames)
}
let missingZones = expectedZoneNames.map { CKRecordZone(zoneName: $0) }
modifyRecordZonesOperation.recordZonesToSave = missingZones
}
database.add(fetchAllRecordZonesOperation)
}
database.add(modifyRecordZonesOperation)
database.add(insertRecordsOperation)
// update
if let updatedRecords = updatedRecords, updatedRecords.count > 0 {
let updatedRecordIDs = updatedRecords
.map({ $0.recordID })
let completion = { (records: [CKRecordID : CKRecord]?, error: Error?) in
if let error = error as? CKError {
DLog("updatedRecordsCompletion: error: \(String(describing: error))")
switch error.code {
case .networkUnavailable:
guard let retryAfterSeconds = error.retryAfterSeconds else {
return
}
let deadlineTime = DispatchTime.now() + retryAfterSeconds
self.queue.asyncAfter(deadline: deadlineTime, execute: {
self.run(updatedRecords: updatedRecords)
})
default:
break
}
}
guard let records = records else { return }
// TODO: Check what happens if we try to fetch a record that doesnt exist
var recordsToSave = [CKRecord]()
for record in updatedRecords {
if let fetchedRecord: CKRecord = records[record.recordID] {
for key in record.allKeys() {
fetchedRecord[key] = record[key]
}
recordsToSave.append(fetchedRecord)
}
}
let updateRecordsOperation = CKModifyRecordsOperation()
updateRecordsOperation.recordsToSave = recordsToSave
updateRecordsOperation.modifyRecordsCompletionBlock = {
(savedRecords, deletedRecordIDs, error) in
DLog("updateRecordsOperation: \(String(describing: savedRecords)) - \(String(describing: deletedRecordIDs)) - \(String(describing: error))")
}
database.add(updateRecordsOperation)
}
fetchRecordsOperation.recordIDs = updatedRecordIDs
fetchRecordsOperation.fetchRecordsCompletionBlock = completion
fetchRecordsOperation.perRecordCompletionBlock = {
(record, recordID, error) in
DLog("fetchRecordsOperation: \(String(describing: record)) - \(String(describing: recordID)) - \(String(describing: error))")
}
database.add(fetchRecordsOperation)
}
}
}
|
gpl-3.0
|
220cf7f522716e28aa9594425c36b4e6
| 35.625 | 177 | 0.739022 | 4.189704 | false | false | false | false |
yume190/JSONDecodeKit
|
Sources/JSONDecodeKit/JSONEncodable.swift
|
1
|
3345
|
////
//// JSONEncodable.swift
//// JSONDecodeKit
////
//// Created by Yume on 2017/7/4.
//// Copyright © 2017年 Yume. All rights reserved.
////
//
//import Foundation
//
//public protocol JSONEncodable {
// static func encode(_ json:Self) -> String
//}
//
//public struct JSONEncoder {
// public static func encode(strings:String? ...) -> String {
// let result = strings.flatMap {$0}.joined(separator: ",")
// return "{" + result + "}"
// }
//}
//
//extension JSONEncoder {
// public static func encodeSingle<T:PrimitiveType>(value:T,key:String) -> String {
// let _value = encodeToString(value: value)
// return "\(key.debugDescription):\(_value)"
// }
//
// public static func encodeOptional<T:PrimitiveType>(value:T?,key:String) -> String? {
// guard let _value = value else {return nil}
// return encodeSingle(value: _value, key: key)
// }
//
// public static func encodeArray<T:PrimitiveType>(value:[T]) -> String {
// return "[\(value.flatMap(encodeToString).joined(separator: ","))]"
// }
//
// public static func encodeArray<T:PrimitiveType>(value:[T],key:String) -> String {
// let _value = encodeArray(value: value)
// return "\(key.debugDescription):\(_value)"
// }
//
// public static func encodeToString<T:PrimitiveType>(value:T) -> String {
// if let v = value as? String {
// return v.debugDescription
// } else {
// return "\(value)"
// }
// }
//}
//
//extension String {
// static public func <| <T:PrimitiveType>(value:T,key:String) -> String {
// return JSONEncoder.encodeSingle(value: value, key: key)
// }
//
// static public func <|? <T:PrimitiveType>(value:T?,key:String) -> String? {
// return JSONEncoder.encodeOptional(value: value, key: key)
// }
//
// static public func <|| <T:PrimitiveType>(value:[T],key:String) -> String {
// return JSONEncoder.encodeArray(value: value, key: key)
// }
//}
//
//extension JSONEncoder {
// public static func encodeSingle<T:JSONEncodable>(value:T,key:String) -> String {
// let _value = T.encode(value)
// return "\(key.debugDescription):\(_value)"
// }
//
// public static func encodeOptional<T:JSONEncodable>(value:T?,key:String) -> String? {
// guard let _value = value else {return nil}
// return encodeSingle(value: _value, key: key)
// }
//
// public static func encodeArray<T:JSONEncodable>(value:[T]) -> String {
// let values:[String] = value.flatMap(T.encode)
// return "[" + values.joined(separator: ",") + "]"
// }
//
// public static func encodeArray<T:JSONEncodable>(value:[T],key:String) -> String {
// let _value = encodeArray(value: value)
// return "\(key.debugDescription):\(_value)"
// }
//}
//
//extension String {
// static public func <| <T:JSONEncodable>(value:T,key:String) -> String {
// return JSONEncoder.encodeSingle(value: value, key: key)
// }
//
// static public func <|? <T:JSONEncodable>(value:T?,key:String) -> String? {
// return JSONEncoder.encodeOptional(value: value, key: key)
// }
//
// static public func <|| <T:JSONEncodable>(value:[T],key:String) -> String {
// return JSONEncoder.encodeArray(value: value, key: key)
// }
//}
|
mit
|
b4eca627cf47787f09b4173c38ed6957
| 32.42 | 90 | 0.595452 | 3.540254 | false | false | false | false |
colincameron/Hex-Colour-Clock
|
Hex Colour Clock/AppDelegate.swift
|
1
|
2561
|
//
// AppDelegate.swift
// Hex Colour Clock
//
// Created by Colin Cameron on 02/03/2015.
// Copyright (c) 2015 Colin Cameron. All rights reserved.
//
import Cocoa
extension String {
subscript(range: Range<Int>) -> String {
return self[advance(startIndex, range.startIndex)..<advance(startIndex, range.endIndex)];
}
func toHexColor() -> NSColor {
func hexToCGFloat(color: String) -> CGFloat {
var result: CUnsignedInt = 0;
let scanner: NSScanner = NSScanner(string: color);
scanner.scanHexInt(&result);
return CGFloat(result) / 255;
}
let red = hexToCGFloat(self[1...2]);
let green = hexToCGFloat(self[3...4]);
let blue = hexToCGFloat(self[5...6]);
return NSColor(calibratedRed: red, green: green, blue: blue, alpha: 1);
}
}
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var timeLabel: NSTextField!
@IBOutlet weak var alwaysOnTopMenuItem: NSMenuItem!
var dateFormatter: NSDateFormatter!
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
window.movableByWindowBackground = true;
dateFormatter = NSDateFormatter();
dateFormatter.dateFormat = "#HHmmss";
let timer = NSTimer(timeInterval:1, target: self, selector: "updateDisplay", userInfo: nil, repeats: true);
NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes);
updateDisplay();
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
func updateDisplay() {
let date = NSDate();
let timeString = dateFormatter.stringFromDate(date);
dispatch_async(dispatch_get_main_queue()) {
self.timeLabel.stringValue = timeString;
self.window.backgroundColor = timeString.toHexColor();
}
}
@IBAction func changeAlwaysOnTop(sender: AnyObject) {
if (alwaysOnTopMenuItem.state == NSOnState) {
alwaysOnTopMenuItem.state = NSOffState;
window.level = Int(CGWindowLevelForKey(Int32(kCGNormalWindowLevelKey)));
} else {
alwaysOnTopMenuItem.state = NSOnState;
window.level = Int(CGWindowLevelForKey(Int32(kCGStatusWindowLevelKey)));
}
}
}
|
mit
|
23fb3582a4d3423794aebf7e72246b3d
| 30.617284 | 115 | 0.632175 | 4.953578 | false | false | false | false |
michalkonturek/ScreenBrightness
|
Example/Tests/ScreenBrightnessTests.swift
|
1
|
4539
|
//
// ScreenBrightnessTests.swift
// ScreenBrightness
//
// Copyright (c) 2016 Michal Konturek <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
@testable import ScreenBrightness
class ScreenBrightnessTests: XCTestCase {
var sut: ScreenBrightness!
var fakeScreen = FakeScreen()
let fakeCenter = FakeNotificationCenter()
let fakeDelegate = FakeDelegate()
var didCall = false
override func setUp() {
super.setUp()
self.fakeDelegate.onDidChange = { self.didCall = true }
self.sut = ScreenBrightness(screen: self.fakeScreen, notificationCenter: self.fakeCenter)
self.sut.delegate = self.fakeDelegate
}
func test_init() {
XCTAssertNotNil(self.sut)
XCTAssertNotNil(self.sut.notificationCenter)
XCTAssertNotNil(self.sut.notificationCenter)
XCTAssertTrue(self.sut === self.fakeCenter.observer)
XCTAssertTrue(self.sut.screen === self.fakeCenter.object)
XCTAssertEqual(self.sut.threshold, 0.5)
}
func test_isLight() {
self.sut.threshold = 0.2
self.fakeScreen.brightness = 0.1
XCTAssertFalse(self.sut.isLight)
self.fakeScreen.brightness = 0.2
XCTAssertFalse(self.sut.isLight)
self.fakeScreen.brightness = 0.21
XCTAssertTrue(self.sut.isLight)
}
func test_onScreenBrightnessDidChange_didChangeToLight() {
// given
XCTAssertFalse(self.didCall)
// when
self.fakeScreen.brightness = 0.6
self.fakeCenter.postNotificationName(UIScreenBrightnessDidChangeNotification, object: nil)
// then
XCTAssertTrue(self.didCall)
XCTAssertTrue(self.sut.isLight)
XCTAssertEqual(self.sut.brightness, 0.6)
}
func test_onScreenBrightnessDidChange_didChangeToDark() {
// given
XCTAssertFalse(self.didCall)
// when
self.fakeScreen.brightness = 0.4
self.fakeCenter.postNotificationName(UIScreenBrightnessDidChangeNotification, object: nil)
// then
XCTAssertTrue(self.didCall)
XCTAssertFalse(self.sut.isLight)
XCTAssertEqual(self.sut.brightness, 0.4)
}
}
class FakeDelegate: ScreenBrightnessMonitoring {
var onDidChange: (() -> ())?
internal func screenBrightnessDidChange() {
self.onDidChange!()
}
}
class FakeScreen: UIScreen {
var value: CGFloat = 0
override var brightness: CGFloat {
get { return value }
set {
value = newValue
}
}
}
class FakeNotificationCenter: NSNotificationCenter {
internal var didRemoveObserver: Bool = false
internal weak var observer: AnyObject!
internal weak var object: AnyObject?
var selector: Selector!
override init () {}
override func addObserver(observer: AnyObject, selector aSelector: Selector, name aName: String?, object anObject: AnyObject?) {
self.observer = observer
self.selector = aSelector
self.object = anObject
}
override func removeObserver(observer: AnyObject) {
if self.observer === observer {
self.didRemoveObserver = true
}
}
override func postNotificationName(aName: String, object anObject: AnyObject?) {
self.observer.performSelector(self.selector)
}
}
|
mit
|
911981adca618e8c2899bbee63b4cd5e
| 30.741259 | 132 | 0.666226 | 4.723205 | false | true | false | false |
uraimo/Swift-Playgrounds
|
2017-05-07-ConcurrencyInSwift.playground/Pages/GCD.xcplaygroundpage/Contents.swift
|
1
|
4674
|
/*:
## All About Concurrency in Swift - Part 1: The Present Playground
Read the post at [uraimo.com](https://ww.uraimo.com/2017/05/07/all-about-concurrency-in-swift-1-the-present/)
*/
//: [Previous - Primitives](@previous)
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
/*:
# GCD - Grand Central Dispatch
*/
/*:
### Dispatch Queues
A Thread pool that executes your jobs submitted as closures
*/
//: Create a new queue or use one of the default queues
let serialQueue = DispatchQueue(label: "com.uraimo.Serial1") //attributes: .serial
let concurrentQueue = DispatchQueue(label: "com.uraimo.Concurrent1", attributes: .concurrent)
let mainQueue = DispatchQueue.main
let globalDefault = DispatchQueue.global()
let backgroundQueue = DispatchQueue.global(qos: .background)
let serialQueueHighPriority = DispatchQueue(label: "com.uraimo.SerialH", qos: .userInteractive)
//: Executing closures on a specific queue
globalDefault.async {
print("Async on MainQ, first?")
}
globalDefault.sync {
print("Sync in MainQ, second?")
}
DispatchQueue.global(qos: .background).async {
// Some background work here
DispatchQueue.main.async {
// It's time to update the UI
print("UI updated on main queue")
}
}
//: Delayed execution
globalDefault.asyncAfter(deadline: .now() + .seconds(3)) {
print("After 3 seconds")
}
//: Shortcut for multiple concurrent calls
globalDefault.sync {
DispatchQueue.concurrentPerform(iterations: 5) {
print("\($0) times")
}
}
//: Execution with a final completion barrier
concurrentQueue.async {
DispatchQueue.concurrentPerform(iterations: 20) { (id:Int) in
sleep(1)
print("Async on concurrentQueue, 5 times: "+String(id))
}
}
concurrentQueue.async (flags: .barrier) {
print("All 5 concurrent tasks completed")
}
//: Dispatch_once and Singletons
//: Leveraging atomic initialization property of variables
func runMe() {
struct Inner {
static let i: () = {
print("Once!")
}()
}
Inner.i
}
runMe()
runMe()
runMe()
//: With a proper extension to DispatchQueue
public extension DispatchQueue {
private static var _onceTokens = [Int]()
private static var internalQueue = DispatchQueue(label: "dispatchqueue.once")
public class func once(token: Int, closure: ()->Void) {
internalQueue.sync {
if _onceTokens.contains(token) {
return
}else{
_onceTokens.append(token)
}
closure()
}
}
}
let t = 1
DispatchQueue.once(token: t) {
print("only once!")
}
DispatchQueue.once(token: t) {
print("Two times!?")
}
DispatchQueue.once(token: t) {
print("Three times!!?")
}
//: DispatchGroups, group together jobs on different queues
let mygroup = DispatchGroup()
for i in 0..<5 {
globalDefault.async(group: mygroup){
sleep(UInt32(i))
print("Group async on globalDefault:"+String(i))
}
}
//: A notification is triggered when all jobs complete or ....
print("Waiting for completion...")
mygroup.notify(queue: globalDefault) {
print("Notify received, done waiting.")
}
mygroup.wait()
print("Done waiting.")
//: When there are no more members in the group
print("Waiting again for completion...")
mygroup.notify(queue: mainQueue) {
print("Notify received, done waiting on mainQueue.")
}
for i in 0..<5 {
mygroup.enter()
sleep(UInt32(i))
print("Group async on mainQueue:"+String(i))
mygroup.leave()
}
//: Inactive DispatchQueue
let inactiveQueue = DispatchQueue(label: "com.uraimo.inactiveQueue", attributes: [.concurrent, .initiallyInactive])
inactiveQueue.async {
print("Done!")
}
print("Not yet...")
inactiveQueue.activate()
print("Gone!")
//: DispatchWorkItems
let workItem = DispatchWorkItem {
print("Done!")
}
workItem.perform()
workItem.notify(queue: DispatchQueue.main) {
print("Notify on Main Queue!")
}
globalDefault.async(execute: workItem)
//workItem.cancel()
//workItem.wait()
//: DispatchSemaphore
let sem = DispatchSemaphore(value: 2)
// The semaphore will be held by groups of two pool threads
globalDefault.sync {
DispatchQueue.concurrentPerform(iterations: 10) { (id:Int) in
sem.wait(timeout: DispatchTime.distantFuture)
sleep(1)
print(String(id)+" acquired semaphore.")
sem.signal()
}
}
//: Dispatch assertions, assertions to verify that we are on the right queue
// Uncomment to crash!
//dispatchPrecondition(condition: .notOnQueue(mainQueue))
//: [Next - NSOperationQueue](@next)
|
mit
|
7f62c8a5c08590d6fdf115c22ca7d2ef
| 19.959641 | 115 | 0.673513 | 3.950972 | false | false | false | false |
paketehq/ios
|
Pakete/PackageTrackHistoryTableViewCell.swift
|
1
|
6381
|
//
// PackageTrackHistoryTableViewCell.swift
// Pakete
//
// Created by Royce Albert Dy on 13/03/2016.
// Copyright © 2016 Pakete. All rights reserved.
//
import UIKit
class PackageTrackHistoryTableViewCell: UITableViewCell {
static let reuseIdentifier = "PackageTrackHistoryCell"
let dateLabel = UILabel()
let statusLabel = UILabel()
fileprivate var didSetupConstraints = false
fileprivate let lineView = UIView()
fileprivate let circleView = UIView()
fileprivate let lineSeparatorView = UIView()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
self.backgroundColor = ColorPalette.BlackHaze
self.layer.rasterizationScale = UIScreen.main.scale
self.layer.shouldRasterize = true
self.lineView.translatesAutoresizingMaskIntoConstraints = false
self.lineView.backgroundColor = ColorPalette.LavenderGray
self.contentView.addSubview(self.lineView)
self.circleView.translatesAutoresizingMaskIntoConstraints = false
self.circleView.backgroundColor = ColorPalette.SeaGreenMedium
self.circleView.layer.cornerRadius = 5.0
self.contentView.addSubview(self.circleView)
self.dateLabel.translatesAutoresizingMaskIntoConstraints = false
self.dateLabel.font = UIFont.systemFont(ofSize: 12.0)
self.dateLabel.textColor = .gray
self.dateLabel.adjustFontToRealIPhoneSize = true
self.contentView.addSubview(self.dateLabel)
self.statusLabel.translatesAutoresizingMaskIntoConstraints = false
self.statusLabel.font = UIFont.systemFont(ofSize: 14.0)
self.statusLabel.numberOfLines = 0
self.statusLabel.adjustFontToRealIPhoneSize = true
self.contentView.addSubview(self.statusLabel)
self.lineSeparatorView.translatesAutoresizingMaskIntoConstraints = false
self.lineSeparatorView.backgroundColor = ColorPalette.LavenderGray
self.contentView.addSubview(self.lineSeparatorView)
}
override func updateConstraints() {
if !self.didSetupConstraints {
NSLayoutConstraint.activate([
NSLayoutConstraint(item: self.lineView, attribute: .top, relatedBy: .equal, toItem: self.contentView, attribute: .top, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: self.lineView, attribute: .bottom, relatedBy: .equal, toItem: self.contentView, attribute: .bottom, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: self.lineView, attribute: .leading, relatedBy: .equal, toItem: self.contentView, attribute: .leading, multiplier: 1.0, constant: 15.0),
NSLayoutConstraint(item: self.lineView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 1.0),
NSLayoutConstraint(item: self.circleView, attribute: .centerY, relatedBy: .equal, toItem: self.dateLabel, attribute: .bottom, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: self.circleView, attribute: .centerX, relatedBy: .equal, toItem: self.lineView, attribute: .centerX, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: self.circleView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 10.0),
NSLayoutConstraint(item: self.circleView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 10.0),
NSLayoutConstraint(item: self.dateLabel, attribute: .top, relatedBy: .equal, toItem: self.contentView, attribute: .top, multiplier: 1.0, constant: 10.0),
NSLayoutConstraint(item: self.dateLabel, attribute: .leading, relatedBy: .equal, toItem: self.lineView, attribute: .leading, multiplier: 1.0, constant: 15.0),
NSLayoutConstraint(item: self.dateLabel, attribute: .trailing, relatedBy: .equal, toItem: self.contentView, attribute: .trailing, multiplier: 1.0, constant: -15.0),
NSLayoutConstraint(item: self.statusLabel, attribute: .top, relatedBy: .equal, toItem: self.dateLabel, attribute: .bottom, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: self.statusLabel, attribute: .leading, relatedBy: .equal, toItem: self.lineView, attribute: .leading, multiplier: 1.0, constant: 15.0),
NSLayoutConstraint(item: self.statusLabel, attribute: .trailing, relatedBy: .equal, toItem: self.contentView, attribute: .trailing, multiplier: 1.0, constant: -15.0),
NSLayoutConstraint(item: self.statusLabel, attribute: .bottom, relatedBy: .equal, toItem: self.contentView, attribute: .bottom, multiplier: 1.0, constant: -10.0),
NSLayoutConstraint(item: self.lineSeparatorView, attribute: .top, relatedBy: .equal, toItem: self.statusLabel, attribute: .bottom, multiplier: 1.0, constant: 10.0),
NSLayoutConstraint(item: self.lineSeparatorView, attribute: .leading, relatedBy: .equal, toItem: self.statusLabel, attribute: .leading, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: self.lineSeparatorView, attribute: .trailing, relatedBy: .equal, toItem: self.contentView, attribute: .trailing, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: self.lineSeparatorView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 0.5)
])
self.didSetupConstraints = true
}
super.updateConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configure(withViewModel viewModel: PackageTrackHistoryViewModel) {
self.statusLabel.text = viewModel.status()
self.dateLabel.text = viewModel.lastUpdateDateString()
self.setNeedsUpdateConstraints()
self.updateConstraintsIfNeeded()
}
}
|
mit
|
3e3bea183b19bcebce775c7faa0359c8
| 55.964286 | 186 | 0.704232 | 4.684288 | false | false | false | false |
fgengine/quickly
|
Quickly/Compositions/Standart/QSpinnerComposition.swift
|
1
|
2818
|
//
// Quickly
//
open class QSpinnerComposable : QComposable {
public var size: CGFloat
public var isAnimating: Bool
public init(
edgeInsets: UIEdgeInsets = UIEdgeInsets.zero,
size: CGFloat,
isAnimating: Bool = true
) {
self.size = size
self.isAnimating = isAnimating
super.init(edgeInsets: edgeInsets)
}
}
open class QSpinnerComposition< Composable: QSpinnerComposable, Spinner: QSpinnerView > : QComposition< Composable > {
lazy public var spinnerView: QSpinnerView = {
let view = Spinner()
view.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(view)
return view
}()
private var _edgeInsets: UIEdgeInsets?
private var _constraints: [NSLayoutConstraint] = [] {
willSet { self.contentView.removeConstraints(self._constraints) }
didSet { self.contentView.addConstraints(self._constraints) }
}
open override class func size(composable: Composable, spec: IQContainerSpec) -> CGSize {
return CGSize(
width: spec.containerSize.width,
height: composable.edgeInsets.top + composable.size + composable.edgeInsets.bottom
)
}
open override func preLayout(composable: Composable, spec: IQContainerSpec) {
if self._edgeInsets != composable.edgeInsets {
self._edgeInsets = composable.edgeInsets
self._constraints = [
self.spinnerView.topLayout >= self.contentView.topLayout.offset(composable.edgeInsets.top),
self.spinnerView.leadingLayout >= self.contentView.leadingLayout.offset(composable.edgeInsets.left),
self.spinnerView.trailingLayout <= self.contentView.trailingLayout.offset(-composable.edgeInsets.right),
self.spinnerView.bottomLayout <= self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom),
self.spinnerView.centerXLayout == self.contentView.centerXLayout,
self.spinnerView.centerYLayout == self.contentView.centerYLayout
]
}
}
open override func postLayout(composable: Composable, spec: IQContainerSpec) {
if composable.isAnimating == true {
self.spinnerView.start()
} else {
self.spinnerView.stop()
}
}
public func isAnimating() -> Bool {
return self.spinnerView.isAnimating()
}
public func start() {
if let composable = self.composable {
composable.isAnimating = true
self.spinnerView.start()
}
}
public func stop() {
if let composable = self.composable {
composable.isAnimating = false
self.spinnerView.stop()
}
}
}
|
mit
|
770f64c39153cf2ff4670edfe727fce9
| 32.152941 | 120 | 0.635557 | 5.247672 | false | false | false | false |
TJRoger/MMDrawerController-Storyboard-swift-
|
MMDrawerController-Storyboard/MMDrawerController-Storyboard/AppDelegate.swift
|
1
|
3035
|
//
// AppDelegate.swift
// MMDrawerController-Storyboard
//
// Created by Roger on 7/23/15.
// Copyright (c) 2015 Roger. All rights reserved.
//
import UIKit
import MMDrawerController
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var drawerController: MMDrawerController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
drawerController = MMDrawerController(centerViewController: mainStoryboard.instantiateViewControllerWithIdentifier("centerStoryboard") as! UIViewController, leftDrawerViewController: mainStoryboard.instantiateViewControllerWithIdentifier("leftStroyboard") as! UIViewController, rightDrawerViewController: mainStoryboard.instantiateViewControllerWithIdentifier("rightStoryboard") as! UIViewController)
drawerController?.setMaximumLeftDrawerWidth(280, animated: true, completion: nil)
drawerController?.openDrawerGestureModeMask = MMOpenDrawerGestureMode.All
drawerController?.closeDrawerGestureModeMask = MMCloseDrawerGestureMode.All
self.window?.rootViewController = drawerController
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
|
e2f2ac09f58cb9905ae2c8ad00a3cd3c
| 54.181818 | 408 | 0.771664 | 5.974409 | false | false | false | false |
nhatminh12369/LineChart
|
LineChart/DotCALayer.swift
|
1
|
922
|
//
// DotCALayer.swift
// LineChart
//
// Created by Michel Anderson Lutz Teixeira on 04/09/2018.
// Copyright © 2018 Nguyen Vu Nhat Minh. All rights reserved.
//
import UIKit
/**
* DotCALayer
*/
class DotCALayer: CALayer {
var innerRadius: CGFloat = 8
var dotInnerColor = UIColor.black
override init() {
super.init()
}
override init(layer: Any) {
super.init(layer: layer)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSublayers() {
super.layoutSublayers()
let inset = self.bounds.size.width - innerRadius
let innerDotLayer = CALayer()
innerDotLayer.frame = self.bounds.insetBy(dx: inset/2, dy: inset/2)
innerDotLayer.backgroundColor = dotInnerColor.cgColor
innerDotLayer.cornerRadius = innerRadius / 2
self.addSublayer(innerDotLayer)
}
}
|
mit
|
8b978d825207582d4a0e9310725bcf29
| 21.463415 | 75 | 0.644951 | 3.935897 | false | false | false | false |
MaartenBrijker/project
|
project/External/AudioKit-master/AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Amplitude Envelope.xcplaygroundpage/Contents.swift
|
1
|
4604
|
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Amplitude Envelope
//: ### Enveloping an FM Oscillator with an ADSR envelope
import XCPlayground
import AudioKit
var fmOscillator = AKFMOscillator()
var fmWithADSR = AKAmplitudeEnvelope(fmOscillator,
attackDuration: 0.1,
decayDuration: 0.1,
sustainLevel: 0.8,
releaseDuration: 0.1)
AudioKit.output = fmWithADSR
AudioKit.start()
fmOscillator.start()
//: User Interface Set up
class PlaygroundView: AKPlaygroundView {
var holdDuration = 1.0
var attackLabel: Label?
var decayLabel: Label?
var sustainLabel: Label?
var releaseLabel: Label?
var durationLabel: Label?
var attackSlider: Slider?
var decaySlider: Slider?
var sustainSlider: Slider?
var releaseSlider: Slider?
var durationSlider: Slider?
override func setup() {
let plotView = AKRollingOutputPlot.createView(500, height: 560)
self.addSubview(plotView)
addTitle("ADSR Envelope")
attackLabel = addLabel("Attack Duration: \(fmWithADSR.attackDuration)")
attackSlider = addSlider(#selector(setAttack), value: fmWithADSR.attackDuration)
decayLabel = addLabel("Decay Duration: \(fmWithADSR.decayDuration)")
decaySlider = addSlider(#selector(setDecay), value: fmWithADSR.decayDuration)
sustainLabel = addLabel("Sustain Label: \(fmWithADSR.sustainLevel)")
sustainSlider = addSlider(#selector(setSustain), value: fmWithADSR.sustainLevel)
releaseLabel = addLabel("Release Duration: \(fmWithADSR.releaseDuration)")
releaseSlider = addSlider(#selector(setRelease), value: fmWithADSR.releaseDuration)
durationLabel = addLabel("Hold Duration: \(holdDuration)")
durationSlider = addSlider(#selector(setDuration), value: 1.0, minimum: 0.0, maximum: 5.0)
addButton("Play Current", action: #selector(PlaygroundView.play))
addButton("Randomize", action: #selector(randomize))
}
func setAttack(slider: Slider) {
fmWithADSR.attackDuration = Double(slider.value)
attackLabel!.text = "Attack Duration: \(fmWithADSR.attackDuration)"
}
func setDecay(slider: Slider) {
fmWithADSR.decayDuration = Double(slider.value)
decayLabel!.text = "Decay Duration: \(fmWithADSR.decayDuration)"
}
func setSustain(slider: Slider) {
fmWithADSR.sustainLevel = Double(slider.value)
sustainLabel!.text = "Sustain Label: \(fmWithADSR.sustainLevel)"
}
func setRelease(slider: Slider) {
fmWithADSR.releaseDuration = Double(slider.value)
releaseLabel!.text = "Release Duration: \(fmWithADSR.releaseDuration)"
}
func setDuration(slider: Slider) {
holdDuration = Double(slider.value)
durationLabel!.text = "Hold Duration: \(holdDuration)"
}
func play() {
fmOscillator.baseFrequency = random(220, 880)
fmWithADSR.start()
self.performSelector(#selector(stop), withObject: nil, afterDelay: holdDuration)
}
func stop() {
fmWithADSR.stop()
}
func randomize() {
fmWithADSR.attackDuration = random(0.01, 0.5)
fmWithADSR.decayDuration = random(0.01, 0.2)
fmWithADSR.sustainLevel = random(0.01, 1)
fmWithADSR.releaseDuration = random(0.01, 1)
holdDuration = fmWithADSR.attackDuration + fmWithADSR.decayDuration + 0.5
attackSlider!.value = Float(fmWithADSR.attackDuration)
attackLabel!.text = "Attack Duration: \(fmWithADSR.attackDuration)"
decaySlider!.value = Float(fmWithADSR.decayDuration)
decayLabel!.text = "Decay Duration: \(fmWithADSR.decayDuration)"
sustainSlider!.value = Float(fmWithADSR.sustainLevel)
sustainLabel!.text = "Sustain Level: \(fmWithADSR.sustainLevel)"
releaseSlider!.value = Float(fmWithADSR.releaseDuration)
releaseLabel!.text = "Release Duration: \(fmWithADSR.releaseDuration)"
durationSlider!.value = Float(holdDuration)
durationLabel!.text = "Hold Duration: \(holdDuration)"
play()
}
}
let view = PlaygroundView(frame: CGRect(x: 0, y: 0, width: 500, height: 560))
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = view
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
|
apache-2.0
|
8b0b18aac8b1f4228f4e37d647829db0
| 33.616541 | 98 | 0.652476 | 4.571996 | false | false | false | false |
ifeherva/HSTracker
|
HSTracker/Utility/ImageCompare.swift
|
2
|
2647
|
//
// ImageCompare.swift
// HSTracker
//
// Created by Benjamin Michotte on 11/06/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
extension NSImage {
var CGImage: CGImage? {
if let imageData = self.tiffRepresentation,
let data = CGImageSourceCreateWithData(imageData as CFData, nil) {
return CGImageSourceCreateImageAtIndex(data, 0, nil)
}
return nil
}
}
class ImageCompare {
var original: NSImage?
init(original: NSImage) {
self.original = original
}
private func compare(with: NSImage,
threshold: CGFloat = 0.4, percent: CGFloat = 20) -> Int {
guard let original = self.original else { return 0 }
guard let origImage = original.CGImage else { return 0 }
guard let withImage = with.CGImage else { return 0 }
var score = 0
let numPixels = original.size.width * original.size.height
let testablePixels = Int(floor(numPixels / 100.0 * percent))
guard let origProvider = origImage.dataProvider else { return 0 }
let origPixelData = origProvider.data
let origData: UnsafePointer<UInt8> = CFDataGetBytePtr(origPixelData)
guard let pixelProvider = withImage.dataProvider else { return 0 }
let withPixelData = pixelProvider.data
let withData: UnsafePointer<UInt8> = CFDataGetBytePtr(withPixelData)
for _ in 0 ..< testablePixels {
let pixelX = Int(arc4random() % UInt32(original.size.width))
let pixelY = Int(arc4random() % UInt32(original.size.height))
let origPixelInfo: Int = ((Int(origImage.width) * pixelY) + pixelX) * 4
let origRed = CGFloat(origData[origPixelInfo])
let origGreen = CGFloat(origData[origPixelInfo + 1])
let origBlue = CGFloat(origData[origPixelInfo + 2])
let withPixelInfo: Int = ((Int(withImage.width) * pixelY) + pixelX) * 4
let withRed = CGFloat(withData[withPixelInfo])
let withGreen = CGFloat(withData[withPixelInfo + 1])
let withBlue = CGFloat(withData[withPixelInfo + 2])
let distance = CGFloat(sqrtf(powf(Float(origRed - withRed), 2)
+ powf(Float(origGreen - withGreen), 2)
+ powf(Float(origBlue - withBlue), 2)) / 255.0)
if distance < threshold {
score += 1
}
}
return Int(Float(score) / Float(testablePixels) * 100.0)
}
}
|
mit
|
b3e1721cdcc391badd60f186a586d68c
| 34.756757 | 83 | 0.591459 | 4.424749 | false | false | false | false |
debugsquad/nubecero
|
nubecero/View/Photos/VPhotosCell.swift
|
1
|
9108
|
import UIKit
class VPhotosCell:UICollectionViewCell
{
private weak var label:UILabel!
private weak var labelSize:UILabel!
private weak var layoutRightWidth:NSLayoutConstraint!
private weak var model:MPhotosItem?
private let attributesName:[String:AnyObject]
private let attributesCount:[String:AnyObject]
private let attributesSize:[String:AnyObject]
private let boundingRect:CGSize
private let drawingOptions:NSStringDrawingOptions
private let numberFormatter:NumberFormatter
private let kAnimateAfter:TimeInterval = 0.05
private let kAnimationDuration:TimeInterval = 0.3
private let kBoundingRectWidth:CGFloat = 500
private let kLabelSizeLeft:CGFloat = 10
private let kLabelSizeRight:CGFloat = 30
private let kAlphaSelected:CGFloat = 0.3
private let kAlphaNotSelected:CGFloat = 1
private let kKiloBytesPerMega:CGFloat = 1000
override init(frame:CGRect)
{
numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.decimal
attributesName = [
NSFontAttributeName:UIFont.regular(size:17),
NSForegroundColorAttributeName:UIColor(white:0.25, alpha:1)
]
attributesCount = [
NSFontAttributeName:UIFont.regular(size:12),
NSForegroundColorAttributeName:UIColor(white:0.45, alpha:1)
]
attributesSize = [
NSFontAttributeName:UIFont.medium(size:13)
]
boundingRect = CGSize(width:kBoundingRectWidth, height:frame.size.height)
drawingOptions = NSStringDrawingOptions([
NSStringDrawingOptions.usesFontLeading,
NSStringDrawingOptions.usesLineFragmentOrigin
])
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
let label:UILabel = UILabel()
label.isUserInteractionEnabled = false
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.clear
label.numberOfLines = 0
self.label = label
let labelSize:UILabel = UILabel()
labelSize.isUserInteractionEnabled = false
labelSize.translatesAutoresizingMaskIntoConstraints = false
labelSize.backgroundColor = UIColor.clear
labelSize.textColor = UIColor.white
self.labelSize = labelSize
let leftView:UIView = UIView()
leftView.isUserInteractionEnabled = false
leftView.translatesAutoresizingMaskIntoConstraints = false
leftView.clipsToBounds = true
leftView.backgroundColor = UIColor.white
let rightView:UIView = UIView()
rightView.isUserInteractionEnabled = false
rightView.translatesAutoresizingMaskIntoConstraints = false
rightView.clipsToBounds = true
rightView.backgroundColor = UIColor.complement
rightView.addSubview(labelSize)
leftView.addSubview(label)
addSubview(rightView)
addSubview(leftView)
let views:[String:UIView] = [
"label":label,
"rightView":rightView,
"leftView":leftView,
"labelSize":labelSize]
let metrics:[String:CGFloat] = [
"labelSizeLeft":kLabelSizeLeft]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-10-[label]-2-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-10-[labelSize(150)]",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[leftView]-0-[rightView]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[label]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[leftView]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[rightView]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[labelSize]-0-|",
options:[],
metrics:metrics,
views:views))
layoutRightWidth = NSLayoutConstraint(
item:rightView,
attribute:NSLayoutAttribute.width,
relatedBy:NSLayoutRelation.equal,
toItem:nil,
attribute:NSLayoutAttribute.notAnAttribute,
multiplier:1,
constant:0)
addConstraint(layoutRightWidth)
NotificationCenter.default.addObserver(
self,
selector:#selector(notifiedAlbumRefreshed(sender:)),
name:Notification.albumRefreshed,
object:nil)
}
required init?(coder:NSCoder)
{
fatalError()
}
deinit
{
NotificationCenter.default.removeObserver(self)
}
override var isSelected:Bool
{
didSet
{
hover()
}
}
override var isHighlighted:Bool
{
didSet
{
hover()
}
}
//MARK: notifications
func notifiedAlbumRefreshed(sender notification:Notification)
{
DispatchQueue.main.async
{ [weak self] in
guard
let album:MPhotosItem = notification.object as? MPhotosItem
else
{
return
}
if album === self?.model
{
self?.print()
}
}
}
//MARK: private
private func hover()
{
if isSelected || isHighlighted
{
alpha = kAlphaSelected
}
else
{
alpha = kAlphaNotSelected
}
}
//MARK: private
private func print()
{
guard
let model:MPhotosItem = self.model
else
{
return
}
let count:NSNumber = model.references.count as NSNumber
let megaBytesFloat:CGFloat = CGFloat(model.kiloBytes) / kKiloBytesPerMega
let megaBytes:NSNumber = megaBytesFloat as NSNumber
guard
let countString:String = numberFormatter.string(from:count),
let megaBytesString:String = numberFormatter.string(from:megaBytes)
else
{
return
}
let compositeString:String = String(
format:NSLocalizedString("VPhotosCell_labelPhotos", comment:""),
countString)
let compositeStringSize:String = String(
format:NSLocalizedString("VPhotosCell_labelSize", comment:""),
megaBytesString)
let mutableString:NSMutableAttributedString = NSMutableAttributedString()
let stringName:NSAttributedString = NSAttributedString(
string:model.name,
attributes:attributesName)
let stringCount:NSAttributedString = NSAttributedString(
string:compositeString,
attributes:attributesCount)
mutableString.append(stringName)
mutableString.append(stringCount)
let attrCompositeSize:NSAttributedString = NSAttributedString(
string:compositeStringSize,
attributes:attributesSize)
label.attributedText = mutableString
labelSize.attributedText = attrCompositeSize
let labelWidth:CGFloat = ceil(attrCompositeSize.boundingRect(
with:boundingRect,
options:drawingOptions,
context:nil).width)
let labelMarginWidth:CGFloat = labelWidth + kLabelSizeLeft + kLabelSizeRight
layoutRightWidth.constant = 0
DispatchQueue.main.asyncAfter(
deadline:DispatchTime.now() + kAnimateAfter)
{ [weak self] in
guard
let animationDuration:TimeInterval = self?.kAnimationDuration
else
{
return
}
self?.layoutRightWidth.constant = labelMarginWidth
UIView.animate(withDuration:animationDuration)
{ [weak self] in
self?.layoutIfNeeded()
}
}
}
//MARK: public
func config(model:MPhotosItem)
{
self.model = model
hover()
print()
}
}
|
mit
|
685142439520a00770bb5bbd5c766ca2
| 29.461538 | 84 | 0.581686 | 5.99605 | false | false | false | false |
son11592/STKeyboard
|
STKeyboard/Classes/STKeyboardPhotoCollection.swift
|
2
|
6574
|
//
// STKeyboardPhotoCollection.swift
// Bubu
//
// Created by Sơn Thái on 9/28/16.
// Copyright © 2016 LOZI. All rights reserved.
//
import AssetsLibrary
import UIKit
open class STKeyboardPhotoCollection: UICollectionView {
fileprivate let assetsLibrary = AssetsLibrary()
internal var collectionLayout: UICollectionViewLayout?
internal var fullSources: [AssetModel] = []
internal var imageSources: [AssetModel] = []
internal var location: Int = 0
internal var length: Int = 10
fileprivate var lastSelectedIndex: IndexPath?
convenience init() {
self.init(frame: CGRect.zero)
}
convenience init(frame: CGRect) {
let size: CGFloat = STKeyboard.STKeyboardDefaultHeight - 4
let collectionLayout = UICollectionViewFlowLayout()
collectionLayout.itemSize = CGSize(width: size, height: size)
collectionLayout.scrollDirection = .horizontal
collectionLayout.minimumInteritemSpacing = 0
collectionLayout.minimumLineSpacing = 2
collectionLayout.sectionInset = UIEdgeInsets.zero
self.init(frame: frame, collectionViewLayout: collectionLayout)
}
// Init collection with frame.
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
self.collectionLayout = layout
self.commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open func commonInit() {
self.delegate = self
self.dataSource = self
self.showsHorizontalScrollIndicator = false
self.showsVerticalScrollIndicator = false
self.isPagingEnabled = false
self.backgroundColor = UIColor.clear
self.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: STKeyboard.STKeyboardDefaultHeight)
self.register(STKeyboardPhotoCollectionCell.self, forCellWithReuseIdentifier: "STKeyboardPhotoCollectionCell")
self.contentInset = UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2)
self.assetsLibrary.delegate = self
self.assetsLibrary.initGroup()
}
open func fetchDefaultAssetsGroup() {
Threading.asyncBackground {
self.assetsLibrary.fetchDefaultPhAssetsWithReverse(true)
}
}
open func getDefaultAssetsGroup() {
Threading.asyncBackground {
self.assetsLibrary.forceGetDefaultCollection({ (assets) -> Void in
self.processResources(assets)
self.loadDataFromFullSources(location: self.location, length: self.length)
DispatchQueue.main.async {
self.reloadData()
}
}, reverse: true)
}
}
open func processResources(_ assets: [AssetModel]) {
self.fullSources.removeAll(keepingCapacity: false)
self.fullSources.append(contentsOf: assets)
}
open func loadDataFromFullSources(location: Int, length: Int) {
var sourceLen = length
if sourceLen + location > self.fullSources.count {
sourceLen = fullSources.count - location
}
if sourceLen >= 0 && location >= 0, location + sourceLen > location {
self.imageSources = Array(self.fullSources[location...(location + sourceLen - 1)])
}
}
}
// MARK: - UICollectionViewDelegate, UICollectionViewDataSource
extension STKeyboardPhotoCollection: UICollectionViewDelegate, UICollectionViewDataSource {
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "STKeyboardPhotoCollectionCell", for: indexPath)
if let photoCell = cell as? STKeyboardPhotoCollectionCell {
let asset = self.imageSources[indexPath.row]
photoCell.asset = asset
}
return cell
}
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.imageSources.count
}
public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
(self.getModel(at: indexPath) as? AssetModel)?.isSelected = false
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let lastSelectedIndex = self.lastSelectedIndex, lastSelectedIndex == indexPath else {
(self.getModel(at: indexPath) as? AssetModel)?.isSelected = true
self.lastSelectedIndex = indexPath
return
}
self.deselectItem(at: indexPath, animated: true)
self.lastSelectedIndex = nil
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
let contentOffseX = self.contentOffset.x + self.contentInset.left
if contentOffseX > scrollView.contentSize.width - scrollView.bounds.size.width * 1.5 {
self.length += 10
if self.length > self.fullSources.count {
self.length = self.fullSources.count
}
Threading.asyncBackground {
self.loadDataFromFullSources(location: self.location, length: self.length)
DispatchQueue.main.async {
self.reloadData()
}
}
}
}
}
public func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
let contentOffseX = self.contentOffset.x + self.contentInset.left
if contentOffseX > scrollView.contentSize.width - scrollView.bounds.size.width * 1.5 {
self.length += 10
if self.length > self.fullSources.count {
self.length = self.fullSources.count
}
Threading.asyncBackground {
self.loadDataFromFullSources(location: self.location, length: self.length)
DispatchQueue.main.async {
self.reloadData()
}
}
}
}
fileprivate func getModel(at indexPath: IndexPath) -> Model? {
guard !self.imageSources.isEmpty && indexPath.row >= 0 && indexPath.row < self.imageSources.count else { return nil }
return self.imageSources[indexPath.row]
}
}
// MARK: - AssetsLibraryDelegate
extension STKeyboardPhotoCollection: AssetsLibraryDelegate {
public func assetsLibraryGroupLoadingCompleted() {
Threading.asyncBackground {
self.assetsLibrary.forceGetDefaultCollection({ (assets) -> Void in
self.processResources(assets)
self.loadDataFromFullSources(location: self.location, length: self.length)
DispatchQueue.main.async {
self.reloadData()
}
}, reverse: true)
}
}
public func assetsLibraryGroupDidSelectGroup(_ imagesGroup: ImagesGroup) {
}
}
|
mit
|
67f6081f130cdbc55652baf9fc6242cb
| 33.584211 | 126 | 0.718612 | 4.676868 | false | false | false | false |
catloafsoft/AudioKit
|
AudioKit/OSX/AudioKit/Playgrounds/AudioKit for OSX.playground/Pages/Splitting Nodes.xcplaygroundpage/Contents.swift
|
1
|
1188
|
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Splitting Nodes
//: ### All nodes in AudioKit can have multiple destinations, the only caveat is that all of the destinations do have to eventually be mixed back together and none of the parallel signal paths can have any time stretching.
import XCPlayground
import AudioKit
import AVFoundation
//: This section prepares the players
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("drumloop", ofType: "wav")
var player = AKAudioPlayer(file!)
player.looping = true
let player1Window = AKAudioPlayerWindow(player, title: "Drums")
var delay = AKDelay(player)
let delayWindow = AKDelayWindow(delay)
var ringMod = AKRingModulator(player)
let ringModWindow = AKRingModulatorWindow(ringMod)
//: Any number of inputs can be equally summed into one output
let mixer = AKMixer(delay, ringMod, player)
AudioKit.output = mixer
AudioKit.start()
let plotView = AKOutputWaveformPlot.createView()
XCPlaygroundPage.currentPage.liveView = plotView
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
|
mit
|
def8b1e3f30ed972407f6a44405c62e3
| 33.941176 | 222 | 0.763468 | 4.054608 | false | false | false | false |
tardieu/swift
|
test/IDE/comment_measurement.swift
|
4
|
3728
|
// RUN: %target-swift-ide-test -new-mangling-for-tests -print-comments -source-filename %s -comments-xml-schema %S/../../bindings/xml/comment-xml-schema.rng | %FileCheck %s
/// Brief.
///
/// This is not a code block.
func spaceLineMeasurement() {}
/**
Brief.
This is not a code block.
*/
func spaceBlockMeasurement() {}
/// Brief.
///
/// This is not a code block.
func tabLineMeasurement() {}
/**
Brief.
This is not a code block.
*/
func tabBlockMeasurement() {}
/// Brief.
///
/// This is not a code block.
func spaceLineMeasurementIndented() {}
/**
Brief.
This is not a code block.
*/
func spaceBlockMeasurementIndented() {}
/// Brief.
///
/// This is not a code block.
func tabLineMeasurementIndented() {}
/**
Brief.
This is not a code block.
*/
func tabBlockMeasurementIndented() {}
// CHECK: {{.*}} DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>spaceLineMeasurement()</Name><USR>s:14swift_ide_test20spaceLineMeasurementyyF</USR><Declaration>func spaceLineMeasurement()</Declaration><Abstract><Para>Brief.</Para></Abstract><Discussion><Para>This is not a code block.</Para></Discussion></Function>]
// CHECK: {{.*}} DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>spaceBlockMeasurement()</Name><USR>s:14swift_ide_test21spaceBlockMeasurementyyF</USR><Declaration>func spaceBlockMeasurement()</Declaration><Abstract><Para>Brief.</Para></Abstract><Discussion><Para>This is not a code block.</Para></Discussion></Function>]
// CHECK: {{.*}} DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>tabLineMeasurement()</Name><USR>s:14swift_ide_test18tabLineMeasurementyyF</USR><Declaration>func tabLineMeasurement()</Declaration><Abstract><Para>Brief.</Para></Abstract><Discussion><Para>This is not a code block.</Para></Discussion></Function>]
// CHECK: {{.*}} DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>tabBlockMeasurement()</Name><USR>s:14swift_ide_test19tabBlockMeasurementyyF</USR><Declaration>func tabBlockMeasurement()</Declaration><Abstract><Para>Brief.</Para></Abstract><Discussion><Para>This is not a code block.</Para></Discussion></Function>]
// CHECK: {{.*}} DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>spaceLineMeasurementIndented()</Name><USR>s:14swift_ide_test28spaceLineMeasurementIndentedyyF</USR><Declaration>func spaceLineMeasurementIndented()</Declaration><Abstract><Para>Brief.</Para></Abstract><Discussion><Para>This is not a code block.</Para></Discussion></Function>]
// CHECK: {{.*}} DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>spaceBlockMeasurementIndented()</Name><USR>s:14swift_ide_test29spaceBlockMeasurementIndentedyyF</USR><Declaration>func spaceBlockMeasurementIndented()</Declaration><Abstract><Para>Brief.</Para></Abstract><Discussion><Para>This is not a code block.</Para></Discussion></Function>]
// CHECK: {{.*}} DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>tabLineMeasurementIndented()</Name><USR>s:14swift_ide_test26tabLineMeasurementIndentedyyF</USR><Declaration>func tabLineMeasurementIndented()</Declaration><Abstract><Para>Brief.</Para></Abstract><Discussion><Para>This is not a code block.</Para></Discussion></Function>]
// CHECK: {{.*}} DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>tabBlockMeasurementIndented()</Name><USR>s:14swift_ide_test27tabBlockMeasurementIndentedyyF</USR><Declaration>func tabBlockMeasurementIndented()</Declaration><Abstract><Para>Brief.</Para></Abstract><Discussion><Para>This is not a code block.</Para></Discussion></Function>]
|
apache-2.0
|
8dd080c874356bda1e4051c7d0a1df9a
| 63.275862 | 373 | 0.694742 | 4.299885 | false | true | false | false |
reza-ryte-club/firefox-ios
|
Storage/MockLogins.swift
|
5
|
4237
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
public class MockLogins: BrowserLogins, SyncableLogins {
private var cache = [Login]()
public init(files: FileAccessor) {
}
public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace) -> Deferred<Maybe<Cursor<LoginData>>> {
let cursor = ArrayCursor(data: cache.filter({ login in
return login.protectionSpace.host == protectionSpace.host
}).sort({ (loginA, loginB) -> Bool in
return loginA.timeLastUsed > loginB.timeLastUsed
}).map({ login in
return login as LoginData
}))
return Deferred(value: Maybe(success: cursor))
}
public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace, withUsername username: String?) -> Deferred<Maybe<Cursor<LoginData>>> {
let cursor = ArrayCursor(data: cache.filter({ login in
return login.protectionSpace.host == protectionSpace.host &&
login.username == username
}).sort({ (loginA, loginB) -> Bool in
return loginA.timeLastUsed > loginB.timeLastUsed
}).map({ login in
return login as LoginData
}))
return Deferred(value: Maybe(success: cursor))
}
// This method is only here for testing
public func getUsageDataForLoginByGUID(guid: GUID) -> Deferred<Maybe<LoginUsageData>> {
let res = cache.filter({ login in
return login.guid == guid
}).sort({ (loginA, loginB) -> Bool in
return loginA.timeLastUsed > loginB.timeLastUsed
})[0] as LoginUsageData
return Deferred(value: Maybe(success: res))
}
public func addLogin(login: LoginData) -> Success {
if let _ = cache.indexOf(login as! Login) {
return deferMaybe(LoginDataError(description: "Already in the cache"))
}
cache.append(login as! Login)
return succeed()
}
public func updateLoginByGUID(guid: GUID, new: LoginData, significant: Bool) -> Success {
// TODO
return succeed()
}
public func getModifiedLoginsToUpload() -> Deferred<Maybe<[Login]>> {
// TODO
return deferMaybe([])
}
public func getDeletedLoginsToUpload() -> Deferred<Maybe<[GUID]>> {
// TODO
return deferMaybe([])
}
public func updateLogin(login: LoginData) -> Success {
if let index = cache.indexOf(login as! Login) {
cache[index].timePasswordChanged = NSDate.nowMicroseconds()
return succeed()
}
return deferMaybe(LoginDataError(description: "Password wasn't cached yet. Can't update"))
}
public func addUseOfLoginByGUID(guid: GUID) -> Success {
if let login = cache.filter({ $0.guid == guid }).first {
login.timeLastUsed = NSDate.nowMicroseconds()
return succeed()
}
return deferMaybe(LoginDataError(description: "Password wasn't cached yet. Can't update"))
}
public func removeLoginByGUID(guid: GUID) -> Success {
let filtered = cache.filter { $0.guid != guid }
if filtered.count == cache.count {
return deferMaybe(LoginDataError(description: "Can not remove a password that wasn't stored"))
}
cache = filtered
return succeed()
}
public func removeAll() -> Success {
cache.removeAll(keepCapacity: false)
return succeed()
}
// TODO
public func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Success { return succeed() }
public func applyChangedLogin(upstream: ServerLogin) -> Success { return succeed() }
public func markAsSynchronized(_: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> { return deferMaybe(0) }
public func markAsDeleted(guids: [GUID]) -> Success { return succeed() }
public func onRemovedAccount() -> Success { return succeed() }
}
extension MockLogins: ResettableSyncStorage {
public func resetClient() -> Success {
return succeed()
}
}
|
mpl-2.0
|
799443a30a2ec97991f03505bc9657d1
| 36.504425 | 154 | 0.638423 | 4.903935 | false | false | false | false |
mikeyeung123/algorithms
|
RedBlackTree.swift
|
1
|
8947
|
/*
Red-black tree with search, insert, and delete
4 April 2015
Mike Yeung
*/
private enum Direction: Int {
case Left, Right
}
private func oppositeDirection(direction: Direction) -> Direction {
return Direction(rawValue: (direction.rawValue + 1) % 2)!
}
private enum Color: Int {
case Red, Black, DoubleBlack
}
// Initializer handles adding dummy nodes
private class Node<T> {
var value: T?
var color: Color
weak var parent: Node?
var childType: Direction?
var children: [Node]?
init(value: T?, color: Color, parent: Node?, childType: Direction?) {
assert(!(value == nil && color == .Red), "Dummy nodes must be black")
assert((parent == nil) == (childType == nil), "If parent is nil, childType must be nil, and vice versa")
self.value = value
self.color = color
self.parent = parent
self.childType = childType
if value != nil {
children = [Node]()
for direction in 0...1 {
children!.append(Node(value: nil, color: .Black, parent: self, childType: Direction(rawValue: direction)!))
}
}
}
func sibling() -> Node? {
return parent?.children![oppositeDirection(childType!).rawValue]
}
func switchColor() {
assert(color != .DoubleBlack, "Cannot switch DoubleBlack")
color = Color(rawValue: (color.rawValue + 1) % 2)!
}
}
class RedBlackTree<T: Comparable> {
private var root: Node<T>?
init() {
// Fixes compiler bug
}
private func search(#value: T, node: Node<T>?) -> (found: Bool, node: Node<T>?) {
if node == nil {
return (false, nil)
} else if node!.value == nil {
return (false, node)
} else if value == node!.value {
return (true, node)
} else {
var child = 0
if value > node!.value {
child = 1
}
return search(value: value, node: node!.children![child])
}
}
// Returns whether value is found
func search(value: T) -> Bool {
return search(value: value, node: root).found
}
private func rotate(node: Node<T>, direction: Direction) {
assert(node.value != nil, "Cannot call rotate() on dummy node")
let parent = node.parent
let childType = node.childType
let child = node.children![oppositeDirection(direction).rawValue]
assert(child.value != nil, "If rotating left, right child must not be dummy node, and vice versa")
let grandchild = child.children![direction.rawValue]
node.children![oppositeDirection(direction).rawValue] = grandchild
grandchild.parent = node
grandchild.childType = oppositeDirection(direction)
child.children![direction.rawValue] = node
node.parent = child
node.childType = oppositeDirection(direction)
parent?.children![childType!.rawValue] = child
child.parent = parent
child.childType = childType
}
private func recolorUpwards(var node: Node<T>) {
if node.parent != nil && node.parent!.color == .Red {
var parent = node.parent!
let grandparent = parent.parent!
let x = parent.childType!
let uncle = grandparent.children![oppositeDirection(parent.childType!).rawValue]
if uncle.color == .Red {
parent.switchColor()
grandparent.switchColor()
uncle.switchColor()
recolorUpwards(grandparent)
} else {
if node.childType == oppositeDirection(parent.childType!) {
rotate(parent, direction: parent.childType!)
swap(&node, &parent)
}
rotate(grandparent, direction: oppositeDirection(parent.childType!))
grandparent.switchColor()
parent.switchColor()
}
}
root?.color = .Black
}
// If value doesn't exist, insert it
func insert(value: T) {
if root == nil {
root = Node(value: value, color: .Black, parent: nil, childType: nil)
} else {
let result = search(value: value, node: root)
if !result.found {
let toInsert = Node(value: value, color: .Red, parent: result.node!.parent, childType: result.node!.childType)
result.node!.parent!.children![result.node!.childType!.rawValue] = toInsert
recolorUpwards(toInsert)
let x = toInsert.childType!
}
}
}
private func successor(node: Node<T>) -> Node<T> {
assert(node.children != nil && node.children![1].value != nil, "successor() must be called on node with right non-leaf child")
var iter = node.children![1]
while iter.children![0].value != nil {
iter = iter.children![0]
}
return iter
}
private func resolveDoubleBlack(node: Node<T>) {
if node.parent == nil {
node.color = .Black
} else if node.color == .DoubleBlack {
let parent = node.parent!
let sibling = node.sibling()!
if sibling.color == .Black {
let redChildren = sibling.children!.filter{$0.color == .Red}
if redChildren.count > 0 {
let sameDirectionChildren = redChildren.filter{$0.childType == sibling.childType}
let differentDirectionChildren = redChildren.filter{$0.childType != sibling.childType}
if sameDirectionChildren.count == 1 {
rotate(parent, direction: node.childType!)
sameDirectionChildren[0].color = .Black
node.color = .Black
} else {
rotate(sibling, direction: sibling.childType!)
rotate(parent, direction: node.childType!)
differentDirectionChildren[0].color = .Black
node.color = .Black
}
} else {
sibling.color = .Red
node.color = .Black
if parent.color == .Red {
parent.color = .Black
} else {
parent.color = .DoubleBlack
resolveDoubleBlack(parent)
}
}
} else {
rotate(parent, direction: node.childType!)
sibling.color = .Black
node.color = .Black
node.sibling()!.color = .Red
}
}
}
private func delete(node: Node<T>) {
assert(node.value != nil, "Cannot delete dummy node")
let children = node.children!.filter{$0.value != nil}
if children.count == 0 {
if node.parent == nil {
root = nil
} else if node.color == .Red {
node.value = nil
node.color = .Black
node.children = nil
} else {
node.value = nil
node.color = .DoubleBlack
node.children = nil
resolveDoubleBlack(node)
}
} else if children.count == 1 {
assert(children[0].color == .Red, "If only child isn't red, violates red-black tree properties, probably from a bug in insert()")
children[0].color == .Black
children[0].parent = node.parent
if node.parent == nil {
root = children[0]
} else {
node.parent!.children![node.childType!.rawValue] = children[0]
}
} else {
let s = successor(node)
node.value = s.value
delete(s)
}
}
// If value exists, delete it
func delete(value: T) {
let result = search(value: value, node: root)
if result.found {
delete(result.node!)
}
}
private func colorString(color: Color) -> String {
if color == .Red {
return "R"
} else {
return "B"
}
}
private func printTree(nodes: [Node<T>]) {
if nodes.count == 0 {
return
}
var children = [Node<T>]()
for node in nodes {
if node.value == nil {
print("D ")
} else {
print("\(node.value!)" + colorString(node.color) + " ")
children += node.children!
}
}
println()
printTree(children)
}
// For debugging only, very rudimentary
func printTree() {
if root != nil {
printTree([root!])
}
println()
}
}
|
mit
|
986700f70d7f42126ec2c4726976179b
| 33.411538 | 141 | 0.517045 | 4.537018 | false | false | false | false |
zisko/swift
|
stdlib/public/core/SwiftNativeNSArray.swift
|
1
|
10939
|
//===--- SwiftNativeNSArray.swift -----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// _ContiguousArrayStorageBase supplies the implementation of the
// _NSArrayCore API (and thus, NSArray the API) for our
// _ContiguousArrayStorage<T>. We can't put this implementation
// directly on _ContiguousArrayStorage because generic classes can't
// override Objective-C selectors.
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
/// Returns `true` iff the given `index` is valid as a position, i.e. `0
/// ≤ index ≤ count`.
@_inlineable // FIXME(sil-serialize-all)
@_versioned
@_transparent
internal func _isValidArrayIndex(_ index: Int, count: Int) -> Bool {
return (index >= 0) && (index <= count)
}
/// Returns `true` iff the given `index` is valid for subscripting, i.e.
/// `0 ≤ index < count`.
@_inlineable // FIXME(sil-serialize-all)
@_versioned
@_transparent
internal func _isValidArraySubscript(_ index: Int, count: Int) -> Bool {
return (index >= 0) && (index < count)
}
/// An `NSArray` with Swift-native reference counting and contiguous
/// storage.
@_fixed_layout // FIXME(sil-serialize-all)
@_versioned
internal class _SwiftNativeNSArrayWithContiguousStorage
: _SwiftNativeNSArray { // Provides NSArray inheritance and native refcounting
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
@nonobjc internal override init() {}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
deinit {}
// Operate on our contiguous storage
@_inlineable
@_versioned
internal func withUnsafeBufferOfObjects<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R {
_sanityCheckFailure(
"Must override withUnsafeBufferOfObjects in derived classes")
}
}
// Implement the APIs required by NSArray
extension _SwiftNativeNSArrayWithContiguousStorage : _NSArrayCore {
@objc internal var count: Int {
return withUnsafeBufferOfObjects { $0.count }
}
@objc(objectAtIndex:)
internal func objectAt(_ index: Int) -> AnyObject {
return withUnsafeBufferOfObjects {
objects in
_precondition(
_isValidArraySubscript(index, count: objects.count),
"Array index out of range")
return objects[index]
}
}
@objc internal func getObjects(
_ aBuffer: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange
) {
return withUnsafeBufferOfObjects {
objects in
_precondition(
_isValidArrayIndex(range.location, count: objects.count),
"Array index out of range")
_precondition(
_isValidArrayIndex(
range.location + range.length, count: objects.count),
"Array index out of range")
if objects.isEmpty { return }
// These objects are "returned" at +0, so treat them as pointer values to
// avoid retains. Copy bytes via a raw pointer to circumvent reference
// counting while correctly aliasing with all other pointer types.
UnsafeMutableRawPointer(aBuffer).copyMemory(
from: objects.baseAddress! + range.location,
byteCount: range.length * MemoryLayout<AnyObject>.stride)
}
}
@objc(countByEnumeratingWithState:objects:count:)
internal func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int {
var enumerationState = state.pointee
if enumerationState.state != 0 {
return 0
}
return withUnsafeBufferOfObjects {
objects in
enumerationState.mutationsPtr = _fastEnumerationStorageMutationsPtr
enumerationState.itemsPtr =
AutoreleasingUnsafeMutablePointer(objects.baseAddress)
enumerationState.state = 1
state.pointee = enumerationState
return objects.count
}
}
@objc(copyWithZone:)
internal func copy(with _: _SwiftNSZone?) -> AnyObject {
return self
}
}
/// An `NSArray` whose contiguous storage is created and filled, upon
/// first access, by bridging the elements of a Swift `Array`.
///
/// Ideally instances of this class would be allocated in-line in the
/// buffers used for Array storage.
@_fixed_layout // FIXME(sil-serialize-all)
@_versioned
@objc internal final class _SwiftDeferredNSArray
: _SwiftNativeNSArrayWithContiguousStorage {
// This stored property should be stored at offset zero. We perform atomic
// operations on it.
//
// Do not access this property directly.
@_versioned
@nonobjc
internal var _heapBufferBridged_DoNotUse: AnyObject?
// When this class is allocated inline, this property can become a
// computed one.
@_versioned
@nonobjc
internal let _nativeStorage: _ContiguousArrayStorageBase
@_inlineable
@_versioned
@nonobjc
internal var _heapBufferBridgedPtr: UnsafeMutablePointer<AnyObject?> {
return _getUnsafePointerToStoredProperties(self).assumingMemoryBound(
to: Optional<AnyObject>.self)
}
internal typealias HeapBufferStorage = _HeapBufferStorage<Int, AnyObject>
@_inlineable
@_versioned
internal var _heapBufferBridged: HeapBufferStorage? {
if let ref =
_stdlib_atomicLoadARCRef(object: _heapBufferBridgedPtr) {
return unsafeBitCast(ref, to: HeapBufferStorage.self)
}
return nil
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned
@nonobjc
internal init(_nativeStorage: _ContiguousArrayStorageBase) {
self._nativeStorage = _nativeStorage
}
@_inlineable
@_versioned
internal func _destroyBridgedStorage(_ hb: HeapBufferStorage?) {
if let bridgedStorage = hb {
let heapBuffer = _HeapBuffer(bridgedStorage)
let count = heapBuffer.value
heapBuffer.baseAddress.deinitialize(count: count)
}
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
deinit {
_destroyBridgedStorage(_heapBufferBridged)
}
@_inlineable
@_versioned
internal override func withUnsafeBufferOfObjects<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R {
while true {
var buffer: UnsafeBufferPointer<AnyObject>
// If we've already got a buffer of bridged objects, just use it
if let bridgedStorage = _heapBufferBridged {
let heapBuffer = _HeapBuffer(bridgedStorage)
buffer = UnsafeBufferPointer(
start: heapBuffer.baseAddress, count: heapBuffer.value)
}
// If elements are bridged verbatim, the native buffer is all we
// need, so return that.
else if let buf = _nativeStorage._withVerbatimBridgedUnsafeBuffer(
{ $0 }
) {
buffer = buf
}
else {
// Create buffer of bridged objects.
let objects = _nativeStorage._getNonVerbatimBridgedHeapBuffer()
// Atomically store a reference to that buffer in self.
if !_stdlib_atomicInitializeARCRef(
object: _heapBufferBridgedPtr, desired: objects.storage!) {
// Another thread won the race. Throw out our buffer.
_destroyBridgedStorage(
unsafeDowncast(objects.storage!, to: HeapBufferStorage.self))
}
continue // Try again
}
defer { _fixLifetime(self) }
return try body(buffer)
}
}
/// Returns the number of elements in the array.
///
/// This override allows the count to be read without triggering
/// bridging of array elements.
@objc
internal override var count: Int {
if let bridgedStorage = _heapBufferBridged {
return _HeapBuffer(bridgedStorage).value
}
// Check if elements are bridged verbatim.
return _nativeStorage._withVerbatimBridgedUnsafeBuffer { $0.count }
?? _nativeStorage._getNonVerbatimBridgedCount()
}
}
#else
// Empty shim version for non-objc platforms.
@_versioned
@_fixed_layout
internal class _SwiftNativeNSArrayWithContiguousStorage {
@_inlineable
@_versioned
internal init() {}
@_inlineable
@_versioned
deinit {}
}
#endif
/// Base class of the heap buffer backing arrays.
@_versioned
@_fixed_layout
internal class _ContiguousArrayStorageBase
: _SwiftNativeNSArrayWithContiguousStorage {
@_versioned
final var countAndCapacity: _ArrayBody
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
@nonobjc
internal init(_doNotCallMeBase: ()) {
_sanityCheckFailure("creating instance of _ContiguousArrayStorageBase")
}
#if _runtime(_ObjC)
@_inlineable
@_versioned
internal override func withUnsafeBufferOfObjects<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R {
if let result = try _withVerbatimBridgedUnsafeBuffer(body) {
return result
}
_sanityCheckFailure(
"Can't use a buffer of non-verbatim-bridged elements as an NSArray")
}
/// If the stored type is bridged verbatim, invoke `body` on an
/// `UnsafeBufferPointer` to the elements and return the result.
/// Otherwise, return `nil`.
@_inlineable // FIXME(sil-serialize-all)
@_versioned
internal func _withVerbatimBridgedUnsafeBuffer<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R? {
_sanityCheckFailure(
"Concrete subclasses must implement _withVerbatimBridgedUnsafeBuffer")
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned
@nonobjc
internal func _getNonVerbatimBridgedCount() -> Int {
_sanityCheckFailure(
"Concrete subclasses must implement _getNonVerbatimBridgedCount")
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned
internal func _getNonVerbatimBridgedHeapBuffer() ->
_HeapBuffer<Int, AnyObject> {
_sanityCheckFailure(
"Concrete subclasses must implement _getNonVerbatimBridgedHeapBuffer")
}
#endif
@_inlineable // FIXME(sil-serialize-all)
@_versioned
internal func canStoreElements(ofDynamicType _: Any.Type) -> Bool {
_sanityCheckFailure(
"Concrete subclasses must implement canStoreElements(ofDynamicType:)")
}
/// A type that every element in the array is.
@_inlineable // FIXME(sil-serialize-all)
@_versioned
internal var staticElementType: Any.Type {
_sanityCheckFailure(
"Concrete subclasses must implement staticElementType")
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
deinit {
_sanityCheck(
self !== _emptyArrayStorage, "Deallocating empty array storage?!")
}
}
|
apache-2.0
|
689b976ed9f3c10b87e3adfb83bd9979
| 29.710674 | 80 | 0.685997 | 4.933664 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.