repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
boytpcm123/ImageDownloader | refs/heads/master | ImageDownloader/ImageDownloader/FilesViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// ImageDownloader
//
// Created by ninjaKID on 2/27/17.
// Copyright © 2017 ninjaKID. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
/**
The KVO context used for all `PhotosViewController` instances. This provides a stable
address to use as the context parameter for the KVO observation methods.
*/
private var photosViewControllerObservationContext = 0
class FilesViewController: UIViewController {
/// The album that the app is importing
fileprivate var album: [Album] = []
/// Keys that we observe on `overallProgress`.
fileprivate let overalProgressObservedKeys = [
"fractionCompleted",
"completedUnitCount",
"totalUnitCount",
"cancelled",
"paused"
]
/// The overall progress for the import that is shown to the user
fileprivate var overallProgress: Progress? {
willSet {
guard let formerProgress = overallProgress else { return }
for overalProgressObservedKey in overalProgressObservedKeys {
formerProgress.removeObserver(self, forKeyPath: overalProgressObservedKey, context: &photosViewControllerObservationContext)
}
}
didSet {
if let newProgress = overallProgress {
for overalProgressObservedKey in overalProgressObservedKeys {
newProgress.addObserver(self, forKeyPath: overalProgressObservedKey, options: [], context: &photosViewControllerObservationContext)
}
}
updateProgressView()
updateToolbar()
}
}
// MARK: Key-Value Observing
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard context == &photosViewControllerObservationContext else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
OperationQueue.main.addOperation {
self.updateProgressView()
self.updateToolbar()
}
}
// MARK: Update UI
fileprivate func updateProgressView() {
let shouldHide: Bool
if let overallProgress = self.overallProgress {
shouldHide = overallProgressIsFinished || overallProgress.isCancelled
//progressView.progress = Float(overallProgress.fractionCompleted)
}
else {
shouldHide = true
}
if progressViewIsHidden != shouldHide {
UIView.animate(withDuration: 0.2, animations: {
//self.progressContainerView.alpha = shouldHide ? 0.0 : 1.0
})
progressViewIsHidden = shouldHide
}
}
fileprivate func updateToolbar() {
let items = [UIBarButtonItem]()
if let overallProgress = overallProgress {
if overallProgressIsFinished || overallProgress.isCancelled {
//items.append(resetToolbarItem)
}
else {
// The import is running.
// items.append(cancelToolbarItem)
if overallProgress.isPaused {
//items.append(resumeToolbarItem)
}
else {
// items.append(pauseToolbarItem)
}
}
}
else {
// items.append(startToolbarItem)
}
navigationController?.toolbar?.setItems(items, animated: true)
}
// MARK: Nib Loading
fileprivate var progressViewIsHidden = true
fileprivate var overallProgressIsFinished: Bool {
let completed = overallProgress!.completedUnitCount
let total = overallProgress!.totalUnitCount
// An NSProgress is finished if it's not indeterminate, and the completedUnitCount > totalUnitCount.
return (completed >= total && total > 0 && completed > 0) || (completed > 0 && total == 0)
}
@IBOutlet weak var btnAdd: UIBarButtonItem!
@IBOutlet weak var btnReset: UIBarButtonItem!
@IBOutlet weak var btnPause: UIBarButtonItem!
@IBOutlet weak var tableFile: UITableView!
@IBOutlet weak var sliderDownload: UISlider!
var queue = OperationQueue()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
btnReset.isEnabled = false
btnPause.isEnabled = btnReset.isEnabled
btnAdd.isEnabled = !btnReset.isEnabled
}
@IBAction func btnActionReset(_ sender: UIBarButtonItem) {
print("Reset button click")
btnReset.isEnabled = false
btnPause.isEnabled = btnReset.isEnabled
btnAdd.isEnabled = !btnReset.isEnabled
Common.ListFileDownload = [FileDownload]()
reloadDataTableFile()
deleteFile()
URLCache.shared.removeAllCachedResponses()
}
@IBAction func btnActionAdd(_ sender: UIBarButtonItem) {
print("Add button click")
btnReset.isEnabled = true
btnPause.isEnabled = btnReset.isEnabled
btnAdd.isEnabled = !btnReset.isEnabled
//Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(self.reloadDataTableFile), name: Const.notificationDownloadedZip, object: nil)
Downloader.downloadFileZip()
}
@IBAction func btnActionPause(_ sender: UIBarButtonItem) {
print("Pause button click")
}
func deleteFile() {
//Create a FileManager instance
let fileManager = FileManager.default
//Delete file
do {
try fileManager.removeItem(atPath: Const.pathFolderName.path)
try fileManager.removeItem(atPath: Const.pathZipFile.path)
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}
}
func reloadDataTableFile() {
DispatchQueue.main.async(execute: {
self.tableFile.reloadData()
});
beginDownloadData()
// Stop listening notification
NotificationCenter.default.removeObserver(self, name: Const.notificationDownloadedZip, object: nil);
}
func beginDownloadData() {
let total = Common.ListFileDownload.count
for i in 0 ..< total {
let arraysImage = Common.ListFileDownload[i]._dataOfContent
let albumFile = Album()
albumFile.photos = arraysImage.map { Photo(URL: URL(string:$0)!) }
album.append(albumFile)
print(albumFile.photos);
}
}
@IBAction func sliderChanged(_ sender: UISlider) {
//Restrict slider to a fixed value
let fixed = roundf(sender.value / 1.0) * 1.0;
sender.setValue(fixed, animated: true)
handleDownload()
}
func handleDownload() {
print("handle Download")
}
}
extension FilesViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Common.ListFileDownload.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let itemFile:FileDownload = Common.ListFileDownload[indexPath.row] as FileDownload
let cell: FilesViewCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) as! FilesViewCell
cell.titleFile.text = itemFile._nameFile
cell.statusFile.text = "Downloading..."
cell.progressFile.progress = 0.5
if overallProgress == nil {
overallProgress = album[indexPath.row].importPhotos()
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell: FilesViewCell = tableView.cellForRow(at: indexPath) as! FilesViewCell
tableView.deselectRow(at: indexPath, animated: true)
print(indexPath.row)
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let listViewController = storyBoard.instantiateViewController(withIdentifier: "ListViewController") as! ListViewController
listViewController.title = cell.titleFile.text
listViewController.indexList = indexPath.row
listViewController.album = album[indexPath.row]
self.navigationController?.pushViewController(listViewController, animated: true)
}
}
| 7d0547c687d32fb818a4e19a8beb2baa | 30.693662 | 151 | 0.610932 | false | false | false | false |
MChainZhou/DesignPatterns | refs/heads/master | Memo/Memo/Simple_2_加强案例/Simple_1_命令模式/BankAccountReceiver.swift | mit | 1 | //
// BankAccountReceiver.swift
// Memo
//
// Created by apple on 2017/8/31.
// Copyright © 2017年 apple. All rights reserved.
//
import UIKit
//命令的接收者:处理对象
class BankAccountReceiver {
//账户对象集合
private var entries = [Int:BankAccount]()
//账户id的增长属性
private var nextId:Int = 1
//总金额
private var total:Float = 0
@discardableResult func addEntry(name:String,amount:Float,time:String) -> BankAccountCommand {
let entry = BankAccount(id: nextId, name: name, amonut: amount, time: time)
self.entries[nextId] = entry
nextId += 1
self.total += amount
return creatUndoCommand(entry: entry)
}
//命令模式 -> 撤销
private func creatUndoCommand(entry:BankAccount) -> BankAccountCommand {
return BankAccountCommand(instructions: { (receiver) in
let removeObj = receiver.entries.removeValue(forKey: entry.id)
if removeObj != nil {
receiver.total -= (removeObj?.amonut)!
}
}, receiver: self)
}
func printEntries() {
for entry in self.entries.values.sorted(by: {(b1,b2) -> Bool in
return b1.id < b2.id
}) {
print("id:\(entry.id) 姓名:\(entry.name) 金额:\(entry.amonut) 时间:\(entry.time)")
}
}
}
| 463225785314503f016f7dcc2162cd37 | 25.86 | 98 | 0.575577 | false | false | false | false |
sundeepgupta/butterfly | refs/heads/master | butterfly/AddPhotoVc.swift | mit | 1 | import UIKit
public class AddPhotoVc : UIViewController, PickPhotoDelegate {
var thoughts = ""
@IBOutlet weak var photoView: UIImageView!
lazy var pickPhoto: PickPhoto = PickPhoto(showIn: self, delegate: self)
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setToolbarHidden(false, animated: false)
}
@IBAction func add() {
self.pickPhoto.show()
}
@IBAction func remove() {
self.photoView.image = nil
}
public override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool {
var shouldPerform = false
let success = { () -> Void in
shouldPerform = true
}
let failure = { (error: NSError) -> Void in
let errorMessage = error.userInfo!["error"] as! String
let message = "There was an error saving your memory :(\n\n\(errorMessage)"
let alert = Alert.basic(title: "Darn!", message: message)
self.presentViewController(alert, animated: true, completion: nil)
}
Data.saveMemory(thoughts: self.thoughts, photo: self.photoView.image, success: success, failure: failure)
return shouldPerform
}
// MARK: AddPhotoDelegate
func pickedPhoto(photo: UIImage) {
self.photoView.image = photo
}
}
| 4b00eff036b69425b0e341883e5609df | 30.76087 | 113 | 0.616016 | false | false | false | false |
DarrenKong/firefox-ios | refs/heads/master | Client/Frontend/Browser/ErrorPageHelper.swift | mpl-2.0 | 3 | /* 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 WebKit
import GCDWebServers
import Shared
import Storage
class ErrorPageHelper {
static let MozDomain = "mozilla"
static let MozErrorDownloadsNotEnabled = 100
fileprivate static let MessageOpenInSafari = "openInSafari"
fileprivate static let MessageCertVisitOnce = "certVisitOnce"
// When an error page is intentionally loaded, its added to this set. If its in the set, we show
// it as an error page. If its not, we assume someone is trying to reload this page somehow, and
// we'll instead redirect back to the original URL.
fileprivate static var redirecting = [URL]()
fileprivate static weak var certStore: CertStore?
// Regardless of cause, NSURLErrorServerCertificateUntrusted is currently returned in all cases.
// Check the other cases in case this gets fixed in the future.
fileprivate static let CertErrors = [
NSURLErrorServerCertificateUntrusted,
NSURLErrorServerCertificateHasBadDate,
NSURLErrorServerCertificateHasUnknownRoot,
NSURLErrorServerCertificateNotYetValid
]
// Error codes copied from Gecko. The ints corresponding to these codes were determined
// by inspecting the NSError in each of these cases.
fileprivate static let CertErrorCodes = [
-9813: "SEC_ERROR_UNKNOWN_ISSUER",
-9814: "SEC_ERROR_EXPIRED_CERTIFICATE",
-9843: "SSL_ERROR_BAD_CERT_DOMAIN",
]
class func cfErrorToName(_ err: CFNetworkErrors) -> String {
switch err {
case .cfHostErrorHostNotFound: return "CFHostErrorHostNotFound"
case .cfHostErrorUnknown: return "CFHostErrorUnknown"
case .cfsocksErrorUnknownClientVersion: return "CFSOCKSErrorUnknownClientVersion"
case .cfsocksErrorUnsupportedServerVersion: return "CFSOCKSErrorUnsupportedServerVersion"
case .cfsocks4ErrorRequestFailed: return "CFSOCKS4ErrorRequestFailed"
case .cfsocks4ErrorIdentdFailed: return "CFSOCKS4ErrorIdentdFailed"
case .cfsocks4ErrorIdConflict: return "CFSOCKS4ErrorIdConflict"
case .cfsocks4ErrorUnknownStatusCode: return "CFSOCKS4ErrorUnknownStatusCode"
case .cfsocks5ErrorBadState: return "CFSOCKS5ErrorBadState"
case .cfsocks5ErrorBadResponseAddr: return "CFSOCKS5ErrorBadResponseAddr"
case .cfsocks5ErrorBadCredentials: return "CFSOCKS5ErrorBadCredentials"
case .cfsocks5ErrorUnsupportedNegotiationMethod: return "CFSOCKS5ErrorUnsupportedNegotiationMethod"
case .cfsocks5ErrorNoAcceptableMethod: return "CFSOCKS5ErrorNoAcceptableMethod"
case .cfftpErrorUnexpectedStatusCode: return "CFFTPErrorUnexpectedStatusCode"
case .cfErrorHTTPAuthenticationTypeUnsupported: return "CFErrorHTTPAuthenticationTypeUnsupported"
case .cfErrorHTTPBadCredentials: return "CFErrorHTTPBadCredentials"
case .cfErrorHTTPConnectionLost: return "CFErrorHTTPConnectionLost"
case .cfErrorHTTPParseFailure: return "CFErrorHTTPParseFailure"
case .cfErrorHTTPRedirectionLoopDetected: return "CFErrorHTTPRedirectionLoopDetected"
case .cfErrorHTTPBadURL: return "CFErrorHTTPBadURL"
case .cfErrorHTTPProxyConnectionFailure: return "CFErrorHTTPProxyConnectionFailure"
case .cfErrorHTTPBadProxyCredentials: return "CFErrorHTTPBadProxyCredentials"
case .cfErrorPACFileError: return "CFErrorPACFileError"
case .cfErrorPACFileAuth: return "CFErrorPACFileAuth"
case .cfErrorHTTPSProxyConnectionFailure: return "CFErrorHTTPSProxyConnectionFailure"
case .cfStreamErrorHTTPSProxyFailureUnexpectedResponseToCONNECTMethod: return "CFStreamErrorHTTPSProxyFailureUnexpectedResponseToCONNECTMethod"
case .cfurlErrorBackgroundSessionInUseByAnotherProcess: return "CFURLErrorBackgroundSessionInUseByAnotherProcess"
case .cfurlErrorBackgroundSessionWasDisconnected: return "CFURLErrorBackgroundSessionWasDisconnected"
case .cfurlErrorUnknown: return "CFURLErrorUnknown"
case .cfurlErrorCancelled: return "CFURLErrorCancelled"
case .cfurlErrorBadURL: return "CFURLErrorBadURL"
case .cfurlErrorTimedOut: return "CFURLErrorTimedOut"
case .cfurlErrorUnsupportedURL: return "CFURLErrorUnsupportedURL"
case .cfurlErrorCannotFindHost: return "CFURLErrorCannotFindHost"
case .cfurlErrorCannotConnectToHost: return "CFURLErrorCannotConnectToHost"
case .cfurlErrorNetworkConnectionLost: return "CFURLErrorNetworkConnectionLost"
case .cfurlErrorDNSLookupFailed: return "CFURLErrorDNSLookupFailed"
case .cfurlErrorHTTPTooManyRedirects: return "CFURLErrorHTTPTooManyRedirects"
case .cfurlErrorResourceUnavailable: return "CFURLErrorResourceUnavailable"
case .cfurlErrorNotConnectedToInternet: return "CFURLErrorNotConnectedToInternet"
case .cfurlErrorRedirectToNonExistentLocation: return "CFURLErrorRedirectToNonExistentLocation"
case .cfurlErrorBadServerResponse: return "CFURLErrorBadServerResponse"
case .cfurlErrorUserCancelledAuthentication: return "CFURLErrorUserCancelledAuthentication"
case .cfurlErrorUserAuthenticationRequired: return "CFURLErrorUserAuthenticationRequired"
case .cfurlErrorZeroByteResource: return "CFURLErrorZeroByteResource"
case .cfurlErrorCannotDecodeRawData: return "CFURLErrorCannotDecodeRawData"
case .cfurlErrorCannotDecodeContentData: return "CFURLErrorCannotDecodeContentData"
case .cfurlErrorCannotParseResponse: return "CFURLErrorCannotParseResponse"
case .cfurlErrorInternationalRoamingOff: return "CFURLErrorInternationalRoamingOff"
case .cfurlErrorCallIsActive: return "CFURLErrorCallIsActive"
case .cfurlErrorDataNotAllowed: return "CFURLErrorDataNotAllowed"
case .cfurlErrorRequestBodyStreamExhausted: return "CFURLErrorRequestBodyStreamExhausted"
case .cfurlErrorFileDoesNotExist: return "CFURLErrorFileDoesNotExist"
case .cfurlErrorFileIsDirectory: return "CFURLErrorFileIsDirectory"
case .cfurlErrorNoPermissionsToReadFile: return "CFURLErrorNoPermissionsToReadFile"
case .cfurlErrorDataLengthExceedsMaximum: return "CFURLErrorDataLengthExceedsMaximum"
case .cfurlErrorSecureConnectionFailed: return "CFURLErrorSecureConnectionFailed"
case .cfurlErrorServerCertificateHasBadDate: return "CFURLErrorServerCertificateHasBadDate"
case .cfurlErrorServerCertificateUntrusted: return "CFURLErrorServerCertificateUntrusted"
case .cfurlErrorServerCertificateHasUnknownRoot: return "CFURLErrorServerCertificateHasUnknownRoot"
case .cfurlErrorServerCertificateNotYetValid: return "CFURLErrorServerCertificateNotYetValid"
case .cfurlErrorClientCertificateRejected: return "CFURLErrorClientCertificateRejected"
case .cfurlErrorClientCertificateRequired: return "CFURLErrorClientCertificateRequired"
case .cfurlErrorCannotLoadFromNetwork: return "CFURLErrorCannotLoadFromNetwork"
case .cfurlErrorCannotCreateFile: return "CFURLErrorCannotCreateFile"
case .cfurlErrorCannotOpenFile: return "CFURLErrorCannotOpenFile"
case .cfurlErrorCannotCloseFile: return "CFURLErrorCannotCloseFile"
case .cfurlErrorCannotWriteToFile: return "CFURLErrorCannotWriteToFile"
case .cfurlErrorCannotRemoveFile: return "CFURLErrorCannotRemoveFile"
case .cfurlErrorCannotMoveFile: return "CFURLErrorCannotMoveFile"
case .cfurlErrorDownloadDecodingFailedMidStream: return "CFURLErrorDownloadDecodingFailedMidStream"
case .cfurlErrorDownloadDecodingFailedToComplete: return "CFURLErrorDownloadDecodingFailedToComplete"
case .cfhttpCookieCannotParseCookieFile: return "CFHTTPCookieCannotParseCookieFile"
case .cfNetServiceErrorUnknown: return "CFNetServiceErrorUnknown"
case .cfNetServiceErrorCollision: return "CFNetServiceErrorCollision"
case .cfNetServiceErrorNotFound: return "CFNetServiceErrorNotFound"
case .cfNetServiceErrorInProgress: return "CFNetServiceErrorInProgress"
case .cfNetServiceErrorBadArgument: return "CFNetServiceErrorBadArgument"
case .cfNetServiceErrorCancel: return "CFNetServiceErrorCancel"
case .cfNetServiceErrorInvalid: return "CFNetServiceErrorInvalid"
case .cfNetServiceErrorTimeout: return "CFNetServiceErrorTimeout"
case .cfNetServiceErrorDNSServiceFailure: return "CFNetServiceErrorDNSServiceFailure"
default: return "Unknown"
}
}
class func register(_ server: WebServer, certStore: CertStore?) {
self.certStore = certStore
server.registerHandlerForMethod("GET", module: "errors", resource: "error.html", handler: { (request) -> GCDWebServerResponse! in
guard let url = request?.url.originalURLFromErrorURL else {
return GCDWebServerResponse(statusCode: 404)
}
guard let index = self.redirecting.index(of: url) else {
return GCDWebServerDataResponse(redirect: url, permanent: false)
}
self.redirecting.remove(at: index)
guard let code = request?.query["code"] as? String,
let errCode = Int(code),
let errDescription = request?.query["description"] as? String,
let errURLString = request?.query["url"] as? String,
let errURLDomain = URL(string: errURLString)?.host,
var errDomain = request?.query["domain"] as? String else {
return GCDWebServerResponse(statusCode: 404)
}
var asset = Bundle.main.path(forResource: "NetError", ofType: "html")
var variables = [
"error_code": "\(errCode)",
"error_title": errDescription,
"short_description": errDomain,
]
let tryAgain = NSLocalizedString("Try again", tableName: "ErrorPages", comment: "Shown in error pages on a button that will try to load the page again")
var actions = "<button onclick='webkit.messageHandlers.localRequestHelper.postMessage({ type: \"reload\" })'>\(tryAgain)</button>"
if errDomain == kCFErrorDomainCFNetwork as String {
if let code = CFNetworkErrors(rawValue: Int32(errCode)) {
errDomain = self.cfErrorToName(code)
}
} else if errDomain == ErrorPageHelper.MozDomain {
if errCode == ErrorPageHelper.MozErrorDownloadsNotEnabled {
let downloadInSafari = NSLocalizedString("Open in Safari", tableName: "ErrorPages", comment: "Shown in error pages for files that can't be shown and need to be downloaded.")
// Overwrite the normal try-again action.
actions = "<button onclick='webkit.messageHandlers.errorPageHelperMessageManager.postMessage({type: \"\(MessageOpenInSafari)\"})'>\(downloadInSafari)</button>"
}
errDomain = ""
} else if CertErrors.contains(errCode) {
guard let certError = request?.query["certerror"] as? String else {
return GCDWebServerResponse(statusCode: 404)
}
asset = Bundle.main.path(forResource: "CertError", ofType: "html")
actions = "<button onclick='history.back()'>\(Strings.ErrorPagesGoBackButton)</button>"
variables["error_title"] = Strings.ErrorPagesCertWarningTitle
variables["cert_error"] = certError
variables["long_description"] = String(format: Strings.ErrorPagesCertWarningDescription, "<b>\(errURLDomain)</b>")
variables["advanced_button"] = Strings.ErrorPagesAdvancedButton
variables["warning_description"] = Strings.ErrorPagesCertWarningDescription
variables["warning_advanced1"] = Strings.ErrorPagesAdvancedWarning1
variables["warning_advanced2"] = Strings.ErrorPagesAdvancedWarning2
variables["warning_actions"] =
"<p><a href='javascript:webkit.messageHandlers.errorPageHelperMessageManager.postMessage({type: \"\(MessageCertVisitOnce)\"})'>\(Strings.ErrorPagesVisitOnceButton)</button></p>"
}
variables["actions"] = actions
let response = GCDWebServerDataResponse(htmlTemplate: asset, variables: variables)
response?.setValue("no cache", forAdditionalHeader: "Pragma")
response?.setValue("no-cache,must-revalidate", forAdditionalHeader: "Cache-Control")
response?.setValue(Date().description, forAdditionalHeader: "Expires")
return response
})
server.registerHandlerForMethod("GET", module: "errors", resource: "NetError.css", handler: { (request) -> GCDWebServerResponse! in
let path = Bundle(for: self).path(forResource: "NetError", ofType: "css")!
return GCDWebServerDataResponse(data: try? Data(contentsOf: URL(fileURLWithPath: path)), contentType: "text/css")
})
server.registerHandlerForMethod("GET", module: "errors", resource: "CertError.css", handler: { (request) -> GCDWebServerResponse! in
let path = Bundle(for: self).path(forResource: "CertError", ofType: "css")!
return GCDWebServerDataResponse(data: try? Data(contentsOf: URL(fileURLWithPath: path)), contentType: "text/css")
})
}
func showPage(_ error: NSError, forUrl url: URL, inWebView webView: WKWebView) {
// Don't show error pages for error pages.
if url.isErrorPageURL {
if let previousURL = url.originalURLFromErrorURL,
let index = ErrorPageHelper.redirecting.index(of: previousURL) {
ErrorPageHelper.redirecting.remove(at: index)
}
return
}
// Add this page to the redirecting list. This will cause the server to actually show the error page
// (instead of redirecting to the original URL).
ErrorPageHelper.redirecting.append(url)
var components = URLComponents(string: WebServer.sharedInstance.base + "/errors/error.html")!
var queryItems = [
URLQueryItem(name: "url", value: url.absoluteString),
URLQueryItem(name: "code", value: String(error.code)),
URLQueryItem(name: "domain", value: error.domain),
URLQueryItem(name: "description", value: error.localizedDescription)
]
// If this is an invalid certificate, show a certificate error allowing the
// user to go back or continue. The certificate itself is encoded and added as
// a query parameter to the error page URL; we then read the certificate from
// the URL if the user wants to continue.
if ErrorPageHelper.CertErrors.contains(error.code),
let certChain = error.userInfo["NSErrorPeerCertificateChainKey"] as? [SecCertificate],
let cert = certChain.first,
let underlyingError = error.userInfo[NSUnderlyingErrorKey] as? NSError,
let certErrorCode = underlyingError.userInfo["_kCFStreamErrorCodeKey"] as? Int {
let encodedCert = (SecCertificateCopyData(cert) as Data).base64EncodedString
queryItems.append(URLQueryItem(name: "badcert", value: encodedCert))
let certError = ErrorPageHelper.CertErrorCodes[certErrorCode] ?? ""
queryItems.append(URLQueryItem(name: "certerror", value: String(certError)))
}
components.queryItems = queryItems
webView.load(PrivilegedRequest(url: components.url!) as URLRequest)
}
}
extension ErrorPageHelper: TabContentScript {
static func name() -> String {
return "ErrorPageHelper"
}
func scriptMessageHandlerName() -> String? {
return "errorPageHelperMessageManager"
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if let errorURL = message.frameInfo.request.url, errorURL.isErrorPageURL,
let res = message.body as? [String: String],
let originalURL = errorURL.originalURLFromErrorURL,
let type = res["type"] {
switch type {
case ErrorPageHelper.MessageOpenInSafari:
UIApplication.shared.open(originalURL, options: [:])
case ErrorPageHelper.MessageCertVisitOnce:
if let cert = certFromErrorURL(errorURL),
let host = originalURL.host {
let origin = "\(host):\(originalURL.port ?? 443)"
ErrorPageHelper.certStore?.addCertificate(cert, forOrigin: origin)
_ = message.webView?.reload()
}
default:
assertionFailure("Unknown error message")
}
}
}
fileprivate func certFromErrorURL(_ url: URL) -> SecCertificate? {
let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
if let encodedCert = components?.queryItems?.filter({ $0.name == "badcert" }).first?.value,
let certData = Data(base64Encoded: encodedCert, options: []) {
return SecCertificateCreateWithData(nil, certData as CFData)
}
return nil
}
}
| 0d444c889961b190afb516ea93822270 | 57.942953 | 197 | 0.709991 | false | false | false | false |
carabina/ActionSwift3 | refs/heads/master | ActionSwift3/display/SimpleButton.swift | mit | 1 | //
// SimpleButton.swift
// ActionSwift
//
// Created by Craig on 5/08/2015.
// Copyright (c) 2015 Interactive Coconut. All rights reserved.
//
import UIKit
/**
SimpleButton's currentState is set to this.
*/
public enum SimpleButtonState {
case Up
case Down
}
/**
Display a button with two states. A state can be represented by a DisplayObject, or any subclass thereof, eg. MovieClip or Sprite.
*/
public class SimpleButton: InteractiveObject {
private var upState:DisplayObject
private var downState:DisplayObject
public init(upState:DisplayObject,downState:DisplayObject) {
//keeping non-optionals honest
self.upState = upState
self.downState = downState
self.currentState = .Up
self.enabled = true
super.init()
self.initProperties(upState, downState)
}
//required to ensure didSet gets called
private func initProperties(upState:DisplayObject, _ downState:DisplayObject) {
self.upState = upState
self.downState = downState
self.currentState = .Up
self.enabled = true
}
/** The current state of the button. Unlike AS3, this state can be set manually. */
public var currentState:SimpleButtonState {
didSet {
switch currentState {
case .Up:
self.node.removeAllChildren()
self.node.addChild(upState.node)
case .Down:
self.node.removeAllChildren()
self.node.addChild(downState.node)
}
self.setUpEventListeners()
}
}
public var enabled:Bool {
didSet {
setUpEventListeners()
}
}
private func setUpEventListeners() {
self.removeStateEventListeners()
if (enabled) {
switch currentState {
case .Up:
upState.addEventListener(InteractiveEventType.TouchBegin.rawValue, EventHandler(touchEventHandler, "touchEventHandler"))
case .Down:
upState.addEventListener(InteractiveEventType.TouchEnd.rawValue, EventHandler(touchEventHandler, "touchEventHandler"))
}
}
}
private func removeStateEventListeners() {
upState.removeEventListeners(InteractiveEventType.TouchBegin.rawValue)
upState.removeEventListeners(InteractiveEventType.TouchEnd.rawValue)
}
private func touchEventHandler(event:Event) -> Void {
if let touchEvent = event as? TouchEvent {
if touchEvent.type == InteractiveEventType.TouchBegin.rawValue {
if (self.currentState == .Up) {
self.currentState = .Down
}
} else if touchEvent.type == InteractiveEventType.TouchEnd.rawValue {
if (self.currentState == .Down) {
self.currentState = .Up
}
}
}
dispatchEvent(event)
}
}
| 8817d600f57bd1071e35997c391647e5 | 31.626374 | 136 | 0.615359 | false | false | false | false |
xianglin123/douyuzhibo | refs/heads/master | douyuzhibo/douyuzhibo/Classes/Tools/UIBarButtonItem+Ext.swift | apache-2.0 | 1 | //
// UIBarButtonItem+Ext.swift
// douyuzhibo
//
// Created by xianglin on 16/10/4.
// Copyright © 2016年 xianglin. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
convenience init(normalImageName : String , highImageName : String = "" , size : CGSize = CGSize.zero) {
let btn = UIButton()
btn.setImage(UIImage(named: normalImageName), for: UIControlState())
if highImageName != "" {
btn.setImage(UIImage(named: highImageName), for: .highlighted)
}
if size == CGSize.zero {
btn.sizeToFit()
}else{
btn.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
}
self.init(customView : btn)
}
}
| d7022a33338d118bb02e88c0d893577b | 26.222222 | 108 | 0.587755 | false | false | false | false |
ben-ng/swift | refs/heads/master | validation-test/compiler_crashers_fixed/01188-swift-genericfunctiontype-get.swift | apache-2.0 | 1 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func j<f: l: e -> e = {
{
l) {
m }
}
protocol k {
class func j()
}
class e: k{ class func j
func g<h>() -> (h, h -> h) -> h {
}
protocol f {
protocol c : b { func b
class x<u>: where T.E == F>}
class A {
class func a() -> Self {
}
}
func b<T>(t: AnyObject.Type) }
protocol e {
}
enum S<T> : P {
func f<T>() -> T col f : b { func b
struct d<f : e, g: e where g.h ==ay) {
}
}
extension NSSet {
convenience init<T>(array: Array<T>) {
}
}
class A {
struct d
| 0c01f7fccd3f90bde7845c7457fb3ca5 | 20.375 | 79 | 0.636257 | false | false | false | false |
jasonhenderson/examples-ios | refs/heads/master | Swizzling/SwizzlingExample/UIViewControllerExtension.swift | gpl-3.0 | 1 | //
// SwizzledSwiftUIViewController.swift
// Swizzling
//
// Created by Jason Henderson on 10/20/16.
//
// This file is part of examples-ios.
//
// examples-ios is free software: you c an 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.
//
// examples-ios 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 examples-ios. If not, see <http://www.gnu.org/licenses/>.
//
import Foundation
import UIKit
import ObjectiveC
/// Courtesy, with some updates, of http://nshipster.com/swift-objc-runtime/
extension UIViewController {
/// Used with associated objects to store additional AnyObjects in extended class
private struct AssociatedKeys {
static var DescriptiveName = "se_DescriptiveName"
}
/// Some contrived property for use in this example
var descriptiveName: String? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) as? String
}
set {
if let newValue = newValue {
objc_setAssociatedObject(
self,
&AssociatedKeys.DescriptiveName,
newValue as NSString?,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
}
/// Swizzle in initialize since it is guaranteed to be executed, and load is never executed by Swift
public override class func initialize() {
struct Static {
static var token: dispatch_once_t = 0
}
// make sure this isn't a subclass
if self !== UIViewController.self {
return
}
// Always wrap in dispatch_once since the swizzle is executed at the global scope
dispatch_once(&Static.token) {
let originalSelector = #selector(UIViewController.viewWillAppear(_:))
let swizzledSelector = #selector(sss_viewWillAppear(_:))
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didAddMethod {
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
}
/// This is called whenever viewWillAppear is called, since we swapped them above
func sss_viewWillAppear(animated: Bool) {
// Does not actually call this method, but the normal viewWillAppear, since we switched them in initialize
self.sss_viewWillAppear(animated)
// Just a demo of associated objects, not really pertinent to the swizzling example
if let name = descriptiveName {
print("viewWillAppear was swizzled in Swift and had a descriptiveName! (\(name))")
} else {
print("viewWillAppear was swizzled in Swift with no descriptiveName!")
}
}
}
| 37f137ead715c6bf3d4099f0b332a585 | 37.145833 | 152 | 0.645276 | false | false | false | false |
RMizin/PigeonMessenger-project | refs/heads/main | FalconMessenger/Supporting Files/UIComponents/INSPhotosGallery/INSPhotoViewController.swift | gpl-3.0 | 1 | //
// INSPhotoViewController.swift
// INSPhotoViewer
//
// Created by Michal Zaborowski on 28.02.2016.
// Copyright © 2016 Inspace Labs Sp z o. o. Spółka Komandytowa. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this library 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 UIKit
import AVKit
open class INSPhotoViewController: UIViewController, UIScrollViewDelegate {
var photo: INSPhotoViewable
var longPressGestureHandler: ((UILongPressGestureRecognizer) -> ())?
lazy private(set) var scalingImageView: INSScalingImageView = {
return INSScalingImageView()
}()
lazy private(set) var doubleTapGestureRecognizer: UITapGestureRecognizer = {
let gesture = UITapGestureRecognizer(target: self, action: #selector(INSPhotoViewController.handleDoubleTapWithGestureRecognizer(_:)))
gesture.numberOfTapsRequired = 2
return gesture
}()
lazy private(set) var longPressGestureRecognizer: UILongPressGestureRecognizer = {
let gesture = UILongPressGestureRecognizer(target: self, action: #selector(INSPhotoViewController.handleLongPressWithGestureRecognizer(_:)))
return gesture
}()
lazy private(set) var activityIndicator: UIActivityIndicatorView = {
let activityIndicator = UIActivityIndicatorView(style: .whiteLarge)
activityIndicator.startAnimating()
return activityIndicator
}()
public init(photo: INSPhotoViewable) {
self.photo = photo
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
scalingImageView.delegate = nil
}
let playerController = INSVideoPlayerViewController()
open override func viewDidLoad() {
super.viewDidLoad()
scalingImageView.delegate = self
scalingImageView.frame = view.bounds
scalingImageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(scalingImageView)
view.addSubview(activityIndicator)
activityIndicator.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
activityIndicator.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleBottomMargin]
activityIndicator.sizeToFit()
if photo.localVideoURL != nil || photo.videoURL != nil {
playerController.view.addSubview(scalingImageView)
playerController.view.frame = view.bounds
if let urlString = photo.localVideoURL, let url = URL(string: urlString) {
playerController.player = AVPlayer(url: url)
view.addSubview(playerController.view)
} else if let urlString = photo.videoURL, let url = URL(string: urlString) {
playerController.player = AVPlayer(url: url)
view.addSubview(playerController.view)
}
playerController.view.addGestureRecognizer(doubleTapGestureRecognizer)
}
else {
view.addGestureRecognizer(doubleTapGestureRecognizer)
view.addGestureRecognizer(longPressGestureRecognizer)
}
if let image = photo.image {
self.scalingImageView.image = image
self.activityIndicator.stopAnimating()
} else if let thumbnailImage = photo.thumbnailImage {
self.scalingImageView.image = blurEffect(image: thumbnailImage)
loadFullSizeImage()
} else {
loadThumbnailImage()
}
}
open override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
scalingImageView.frame = view.bounds
playerController.view.frame = view.bounds
}
private func loadThumbnailImage() {
view.bringSubviewToFront(activityIndicator)
photo.loadThumbnailImageWithCompletionHandler { [weak self] (image, error) -> () in
let completeLoading = {
self?.scalingImageView.image = blurEffect(image: image ?? UIImage())
// if image != nil {
// // self?.activityIndicator.stopAnimating()
// }
self?.loadFullSizeImage()
}
if Thread.isMainThread {
completeLoading()
} else {
DispatchQueue.main.async(execute: { () -> Void in
completeLoading()
})
}
}
}
private func loadFullSizeImage() {
print("loading full size")
view.bringSubviewToFront(activityIndicator)
self.photo.loadImageWithCompletionHandler({ [weak self] (image, error) -> () in
let completeLoading = {
self?.activityIndicator.stopAnimating()
self?.scalingImageView.image = image
}
if Thread.isMainThread {
completeLoading()
} else {
DispatchQueue.main.async(execute: { () -> Void in
completeLoading()
})
}
})
}
@objc private func handleLongPressWithGestureRecognizer(_ recognizer: UILongPressGestureRecognizer) {
if recognizer.state == UIGestureRecognizer.State.began {
longPressGestureHandler?(recognizer)
}
}
@objc private func handleDoubleTapWithGestureRecognizer(_ recognizer: UITapGestureRecognizer) {
if photo.videoURL != nil || photo.localVideoURL != nil {
if playerController.videoGravity != .resizeAspectFill {
playerController.videoGravity = .resizeAspectFill
} else {
playerController.videoGravity = .resizeAspect
}
return
}
let pointInView = recognizer.location(in: scalingImageView.imageView)
var newZoomScale = scalingImageView.maximumZoomScale
if scalingImageView.zoomScale >= scalingImageView.maximumZoomScale || abs(scalingImageView.zoomScale - scalingImageView.maximumZoomScale) <= 0.01 {
newZoomScale = scalingImageView.minimumZoomScale
}
let scrollViewSize = scalingImageView.bounds.size
let width = scrollViewSize.width / newZoomScale
let height = scrollViewSize.height / newZoomScale
let originX = pointInView.x - (width / 2.0)
let originY = pointInView.y - (height / 2.0)
let rectToZoom = CGRect(x: originX, y: originY, width: width, height: height)
scalingImageView.zoom(to: rectToZoom, animated: true)
}
// MARK:- UIScrollViewDelegate
open func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return scalingImageView.imageView
}
open func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
scrollView.panGestureRecognizer.isEnabled = true
}
open func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
// There is a bug, especially prevalent on iPhone 6 Plus, that causes zooming to render all other gesture recognizers ineffective.
// This bug is fixed by disabling the pan gesture recognizer of the scroll view when it is not needed.
if (scrollView.zoomScale == scrollView.minimumZoomScale) {
scrollView.panGestureRecognizer.isEnabled = false;
}
}
}
| b423d7dc9d1522151b542361b4da3ad3 | 37.562189 | 155 | 0.667527 | false | false | false | false |
h-n-y/UICollectionView-TheCompleteGuide | refs/heads/master | chapter-4/Survey-2/Survey/ViewController.swift | mit | 1 | //
// ViewController.swift
// Survey
//
// Created by Hans Yelek on 4/30/16.
// Copyright © 2016 Hans Yelek. All rights reserved.
//
import UIKit
class ViewController: UICollectionViewController {
private static let CellIdentifier = "CellIdentifier"
private static let HeaderIdentifier = "HeaderIdentifier"
//static let MaxItemSize = CGSize(width: 200, height: 200)
private var selectionModelArray: Array<SelectionModel>
private var currentModelArrayIndex: Int = 0
private var isFinished: Bool = false
override init(collectionViewLayout layout: UICollectionViewLayout) {
selectionModelArray = ViewController.newSelectionModel()
super.init(collectionViewLayout: layout)
}
required init?(coder aDecoder: NSCoder) {
selectionModelArray = ViewController.newSelectionModel()
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Create a new collection view with our flow layout and set ourself as delegate and data source
//let surveyCollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: surveyFlowLayout)
self.collectionView?.dataSource = self
self.collectionView?.delegate = self
// Register classes
self.collectionView?.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: ViewController.CellIdentifier)
self.collectionView?.registerClass(CollectionHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: ViewController.HeaderIdentifier)
//
self.collectionView?.opaque = false
self.collectionView?.backgroundColor = UIColor.blackColor()
//self.collectionView = surveyCollectionView
}
// Returns the photo model at any index path
private func photoModelForIndexPath(indexPath: NSIndexPath) -> PhotoModel? {
guard indexPath.section < selectionModelArray.count else { return nil }
guard indexPath.row < selectionModelArray[indexPath.section].photoModels.count else { return nil }
return selectionModelArray[indexPath.section].photoModels[indexPath.item]
}
// Configures a cell for a given index path
private func configureCell(cell: CollectionViewCell, forIndexPath indexPath: NSIndexPath) {
if let image = photoModelForIndexPath(indexPath)?.image {
cell.image = image
}
cell.setDisabled(false)
cell.selected = false
// If the cell is not in our current last index, disable it
if indexPath.section < currentModelArrayIndex {
cell.setDisabled(true)
// If the cell was selected by the user previously, select it now
if indexPath.row == selectionModelArray[indexPath.section].selectedPhotoModelIndex {
cell.selected = true
}
}
}
private class func newSelectionModel() -> Array<SelectionModel> {
let modelArray: Array<SelectionModel> = [
SelectionModel.selectionModelWithPhotoModels([
PhotoModel.photoModelWithName("Purple Flower", image: UIImage(named: "0.jpg")),
PhotoModel.photoModelWithName("WWDC Hypertable", image: UIImage(named: "1.jpg")),
PhotoModel.photoModelWithName("Purple Flower II", image: UIImage(named: "2.jpg")),
]),
SelectionModel.selectionModelWithPhotoModels([
PhotoModel.photoModelWithName("Castle", image: UIImage(named: "3.jpg")),
PhotoModel.photoModelWithName("Skyward Look", image: UIImage(named: "4.jpg")),
PhotoModel.photoModelWithName("Kakabeka Falls", image: UIImage(named: "5.jpg")),
]),
SelectionModel.selectionModelWithPhotoModels([
PhotoModel.photoModelWithName("Puppy", image: UIImage(named: "6.jpg")),
PhotoModel.photoModelWithName("Thunder Bay Sunset", image: UIImage(named: "7.jpg")),
PhotoModel.photoModelWithName("Sunflower I", image: UIImage(named: "8.jpg")),
]),
SelectionModel.selectionModelWithPhotoModels([
PhotoModel.photoModelWithName("Sunflower II", image: UIImage(named: "9.jpg")),
PhotoModel.photoModelWithName("Sunflower I", image: UIImage(named: "10.jpg")),
PhotoModel.photoModelWithName("Squirrel", image: UIImage(named: "11.jpg")),
]),
SelectionModel.selectionModelWithPhotoModels([
PhotoModel.photoModelWithName("Montréal Subway", image: UIImage(named: "12.jpg")),
PhotoModel.photoModelWithName("Geometrically Intriguing Flower", image: UIImage(named: "13.jpg")),
PhotoModel.photoModelWithName("Grand Lake", image: UIImage(named: "17.jpg")),
]),
SelectionModel.selectionModelWithPhotoModels([
PhotoModel.photoModelWithName("Spadina Subway Station", image: UIImage(named: "15.jpg")),
PhotoModel.photoModelWithName("Staircase to Grey", image: UIImage(named: "14.jpg")),
PhotoModel.photoModelWithName("Saint John River", image: UIImage(named: "16.jpg")),
]),
SelectionModel.selectionModelWithPhotoModels([
PhotoModel.photoModelWithName("Purple Bokeh Flower", image: UIImage(named: "18.jpg")),
PhotoModel.photoModelWithName("Puppy II", image: UIImage(named: "19.jpg")),
PhotoModel.photoModelWithName("Plant", image: UIImage(named: "21.jpg")),
]),
SelectionModel.selectionModelWithPhotoModels([
PhotoModel.photoModelWithName("Peggy's Cove I", image: UIImage(named: "21.jpg")),
PhotoModel.photoModelWithName("Peggy's Cove II", image: UIImage(named: "22.jpg")),
PhotoModel.photoModelWithName("Sneaky Cat", image: UIImage(named: "23.jpg")),
]),
SelectionModel.selectionModelWithPhotoModels([
PhotoModel.photoModelWithName("King Street West", image: UIImage(named: "24.jpg")),
PhotoModel.photoModelWithName("TTC Streetcar", image: UIImage(named: "25.jpg")),
PhotoModel.photoModelWithName("UofT at Night", image: UIImage(named: "26.jpg")),
]),
SelectionModel.selectionModelWithPhotoModels([
PhotoModel.photoModelWithName("Mushroom", image: UIImage(named: "27.jpg")),
PhotoModel.photoModelWithName("Montréal Subway Selective Colour", image: UIImage(named: "28.jpg")),
PhotoModel.photoModelWithName("On Air", image: UIImage(named: "29.jpg")),
]),
]
return modelArray
}
}
// MARK: - UICollectionViewDataSource
extension ViewController {
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
// Return the smallest of either our current model index plus one, or our total number of sections.
// This will show one section when we only want to display section zero, etc.
// It will prevent us from returning 11 when we only have 10 sections.
return min(currentModelArrayIndex + 1, selectionModelArray.count)
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// Return the number of photos in the section model
return selectionModelArray[currentModelArrayIndex].photoModels.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ViewController.CellIdentifier, forIndexPath: indexPath) as! CollectionViewCell
configureCell(cell, forIndexPath: indexPath)
return cell
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: ViewController.HeaderIdentifier, forIndexPath: indexPath) as! CollectionHeaderView
if indexPath.section == 0 {
// If this is the first header, display a prompt to the user
headerView.text = "Tap on a photo to start the recommendation engine."
} else if indexPath.section <= currentModelArrayIndex {
// Otherwise, display a prompt using the selected photo from the previous section
let selectionModel: SelectionModel = selectionModelArray[indexPath.section - 1]
if let selectedPhotoModel: PhotoModel = photoModelForIndexPath(NSIndexPath(forItem: selectionModel.selectedPhotoModelIndex, inSection: indexPath.section - 1)) {
headerView.text = "Because you liked \(selectedPhotoModel.name)"
}
}
return headerView
}
}
// MARK: - UICollectionViewDelegate
extension ViewController {
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// No matter what, deselect cell
collectionView.deselectItemAtIndexPath(indexPath, animated: true)
// Set the selected photo index
selectionModelArray[currentModelArrayIndex].selectedPhotoModelIndex = indexPath.item
if currentModelArrayIndex >= selectionModelArray.count - 1 {
// Present some dialogue to indicate things are done.
isFinished = true
let action = UIAlertAction(title: "Awesome!", style: .Default, handler: nil)
let alert = UIAlertController(title: "Recommendation Engine", message: "Based on your selections, we have concluded you have excellent taste in photography!", preferredStyle: .Alert)
alert.addAction(action)
presentViewController(alert, animated: true, completion: nil)
return
}
collectionView.performBatchUpdates({
self.currentModelArrayIndex += 1
self.collectionView?.insertSections(NSIndexSet(index: self.currentModelArrayIndex))
self.collectionView?.reloadSections(NSIndexSet(index: self.currentModelArrayIndex - 1))
}, completion: { finished in
collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: self.currentModelArrayIndex), atScrollPosition: .Top, animated: true)
})
}
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return indexPath.section == currentModelArrayIndex && !isFinished
}
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
if action == #selector(NSObject.copy(_:)) {
return true
}
return false
}
override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
if action == #selector(NSObject.copy(_:)) {
let pasteboard = UIPasteboard.generalPasteboard()
pasteboard.string = photoModelForIndexPath(indexPath)?.name
}
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
// Grab the photo model for the cell
guard let photoModel: PhotoModel = photoModelForIndexPath(indexPath), image = photoModel.image else { return CGSizeZero }
// Determine the size and aspect ration for the model's image
let photoSize = image.size
let aspectRatio: CGFloat = photoSize.width / photoSize.height
// Start out with the detail image size at maximum size
let maxSize: CGSize = CollectionViewFlowLayout.MaxItemSize
var itemSize: CGSize = maxSize
if aspectRatio < 1 {
// The photo is taller than it is wide, so constrain the width
itemSize = CGSize(width: maxSize.width * aspectRatio, height: maxSize.height)
} else if aspectRatio > 1 {
// The photo is wider than it is tall, so constrain the height
itemSize = CGSize(width: maxSize.width, height: maxSize.height / aspectRatio)
}
return itemSize
}
}
| 58c8f8bccc97fd4e9d98947a176ada15 | 48.287313 | 194 | 0.664925 | false | false | false | false |
konanxu/WeiBoWithSwift | refs/heads/master | WeiBo/WeiBo/Classes/Tools/Category/UIView+Category.swift | mit | 1 | //
// UIView+Category.swift
// WeiBo
//
// Created by Konan on 16/3/21.
// Copyright © 2016年 Konan. All rights reserved.
//
import UIKit
extension UIView{
func getConstraintWidth() ->NSLayoutConstraint?{
let arr = self.constraints
for cons in arr{
if(cons.firstAttribute == NSLayoutAttribute.Width){
return cons
}
}
return nil
}
func getConstraintHeight() ->NSLayoutConstraint?{
let arr = self.constraints
for cons in arr{
if(cons.firstAttribute == NSLayoutAttribute.Height){
return cons
}
}
return nil
}
} | 8ead7fd4cd4034897be5eee1f96b6d2b | 20.09375 | 64 | 0.559347 | false | false | false | false |
ravirani/algorithms | refs/heads/master | String/LongestPalindromicSubstring.swift | mit | 1 | //
// LongestPalindromicSubstring.swift
//
//
// Solved using Manacher's algorithm
// https://en.wikipedia.org/wiki/Longest_palindromic_substring
//
//
import Foundation
extension String {
subscript(index: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: index)]
}
}
func longestPalindromicSubstring(inputString: String) -> Int {
let stringLength = inputString.characters.count
guard stringLength > 1 else {
return stringLength
}
var palindromicStringLengths = Array(repeating: 1, count: stringLength)
var indexWithMaxLength = 0, maxLength = Int.min
var length = 1, indexGoingForward = 0, indexGoingBackward = 0
for currentIndex in 1..<stringLength {
let rightEdgeIndex = palindromicStringLengths[indexWithMaxLength]/2 + indexWithMaxLength
// Current index is entirely self contained in the previous max length palindrome
if currentIndex < rightEdgeIndex {
// Set the count to the left side equivalent because thats the min length palindrome that exists
// at this index
palindromicStringLengths[currentIndex] = palindromicStringLengths[indexWithMaxLength - (currentIndex - indexWithMaxLength)]
// If the length of this palindrome ends here, we don't need to evaluate this character
if currentIndex + palindromicStringLengths[currentIndex]/2 == currentIndex {
continue
}
}
length = 1
indexGoingBackward = currentIndex - 1
indexGoingForward = currentIndex + 1
while indexGoingBackward >= 0 &&
indexGoingForward < stringLength &&
inputString[indexGoingBackward] == inputString[indexGoingForward]
{
length += 2
indexGoingBackward -= 1
indexGoingForward += 1
}
palindromicStringLengths[currentIndex] = length
if length > maxLength {
maxLength = length
indexWithMaxLength = currentIndex
}
}
return maxLength
}
// Base case
assert(longestPalindromicSubstring(inputString: "abadefg") == 3)
// Case checking right boundary condition
assert(longestPalindromicSubstring(inputString: "abaxabaxabb") == 9)
// Case checking guard conditions
assert(longestPalindromicSubstring(inputString: "a") == 1)
assert(longestPalindromicSubstring(inputString: "") == 0)
| 8fc1d20fcb06fa4646020c296f8daef6 | 29.453333 | 129 | 0.716725 | false | false | false | false |
riehs/virtual-tourist | refs/heads/master | Virtual Tourist/Virtual Tourist/Pin.swift | mit | 1 | //
// Pin.swift
// Virtual Tourist
//
// Created by Daniel Riehs on 4/2/15.
// Copyright (c) 2015 Daniel Riehs. All rights reserved.
//
import MapKit
import CoreData
//Make Pin available to Objective-C code. (Necessary for Core Data.)
@objc(Pin)
//Make Pin a subclass of NSManagedObject. (Necessary for Core Data.)
class Pin: NSManagedObject, MKAnnotation {
//Useful for saving data into the Core Data context.
var sharedContext: NSManagedObjectContext {
return CoreDataStackManager.sharedInstance().managedObjectContext!
}
//Promoting these five properties to Core Data attributes by prefixing them with @NSManaged.
@NSManaged var latitude: Double
@NSManaged var longitude: Double
@NSManaged var title: String?
@NSManaged var photos: [Photo]
@NSManaged var loading: Bool
//The location must be a computed property because CLLocationCoordinate2D cannot be stored in Core Data.
var coordinate: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
//The standard Core Data init method.
override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
super.init(entity: entity, insertInto: context)
}
//Load pins from Core Data.
func fetchAllPhotos() -> [Pin] {
let error: NSErrorPointer? = nil
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Pin")
let results: [AnyObject]?
do {
results = try sharedContext.fetch(fetchRequest)
} catch let error1 as NSError {
error??.pointee = error1
results = nil
}
if error != nil {
print("Error in fetchAllPins(): \(String(describing: error))")
}
return results as! [Pin]
}
//The init method needs to accept the shared context as one of its parameters.
init(latitude: Double, longitude: Double, title: String, context: NSManagedObjectContext) {
//The entity name here is the same as the entity name in the Model.xcdatamodeld file.
let entity = NSEntityDescription.entity(forEntityName: "Pin", in: context)!
super.init(entity: entity, insertInto: context)
self.latitude = latitude
self.longitude = longitude
self.title = title
//The loading property is set to true so that the PhotoAlbumViewController knows to fetch a new collection of photos.
loading = true
CoreDataStackManager.sharedInstance().saveContext()
}
}
| 3de590e41c104f0f54a45d7003609993 | 28.2875 | 119 | 0.745625 | false | false | false | false |
ios-ximen/DYZB | refs/heads/master | 斗鱼直播/斗鱼直播/Classes/Home/Controllers/GameController.swift | mit | 1 | //
// GameController.swift
// 斗鱼直播
//
// Created by niujinfeng on 2017/7/8.
// Copyright © 2017年 niujinfeng. All rights reserved.
//
import UIKit
fileprivate let KEdgeMargin : CGFloat = 10
fileprivate let KgameItemW = (KscreenWidth - KEdgeMargin * 2) / 3
fileprivate let KitemH = KitemW * 6 / 5
fileprivate let KHeadH : CGFloat = 50
fileprivate let KgameViewH : CGFloat = 90
fileprivate let KGameCellID = "KGameCellID"
fileprivate let KGameHeadViewID = "KGameHeadViewID"
class GameController: BaseViewController {
//mark: -懒加载
fileprivate lazy var gameVM : GameViewModel = GameViewModel()
fileprivate lazy var collectionHeadView : CollectionHeadView = {
let headView = CollectionHeadView.headView()
headView.frame = CGRect(x: 0, y: -(KHeadH + KgameViewH), width: KscreenWidth, height: KHeadH)
headView.iconImageVeiw.image = UIImage(named: "Img_orange")
headView.titleLable.text = "常见"
headView.moreBtn.isHidden = true
return headView
}()
fileprivate lazy var gameView : KGameView = {
let gameView = KGameView.kGameView()
gameView.frame = CGRect(x: 0, y: -KgameViewH, width: KscreenWidth, height: KgameViewH)
return gameView
}()
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: KgameItemW, height: KitemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .vertical
//设置头部
layout.headerReferenceSize = CGSize(width: KscreenWidth, height: KHeadH)
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.contentInset = UIEdgeInsetsMake(0, KEdgeMargin, 0, KEdgeMargin)
collectionView.backgroundColor = UIColor.white
//注册cell
collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: KGameCellID)
//注册头部
collectionView.register(UINib(nibName: "CollectionHeadView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: KGameHeadViewID)
collectionView.autoresizingMask = [.flexibleHeight, .flexibleHeight]
collectionView.dataSource = self
return collectionView
}()
//mark: -系统回调方法
override func viewDidLoad() {
super.viewDidLoad()
//设置ui
setUpUI()
//网络请求
loadRequest()
}
}
//mark: -设置ui
extension GameController{
override func setUpUI(){
//给contentView赋值
contentView = contentView
//添加collectionView
view.addSubview(collectionView)
//添加headView
collectionView.addSubview(collectionHeadView)
//添加gameView
collectionView.addSubview(gameView)
//设置collectionView的内边距
collectionView.contentInset = UIEdgeInsetsMake(KHeadH + KgameViewH, 0, 0, 0)
//调用super
super.setUpUI()
}
}
//mark: -网络请求
extension GameController{
fileprivate func loadRequest(){
self.gameVM.loadRequest {
//刷新数据
self.collectionView.reloadData()
//传递数据,默认是60组数据,需要传10组数据
self.gameView.gameGroup = Array(self.gameVM.gameModels[0..<10])
//加载数据完成
self.loadDataFinished()
}
}
}
//mark: -遵守UICollectionViewDataSource协议
extension GameController : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return gameVM.gameModels.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KGameCellID, for: indexPath) as! CollectionGameCell
cell.baseGame = gameVM.gameModels[indexPath.item]
//cell.backgroundColor = UIColor.andomColor()
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: KGameHeadViewID, for: indexPath) as! CollectionHeadView
headView.titleLable.text = "全部"
headView.moreBtn.isHidden = true
headView.iconImageVeiw.image = UIImage(named: "Img_orange")
return headView
}
}
| ac930047af1b02aad56e20a57828e692 | 36.362903 | 186 | 0.685085 | false | false | false | false |
paulsumit1993/DailyFeed | refs/heads/master | DailyFeed/📦Model/NewsSourceParameters.swift | gpl-3.0 | 1 | //
// NewsSourceRequestParameters.swift
// DailyFeed
//
// Created by Sumit Paul on 05/05/19.
//
import Foundation
struct NewsSourceParameters {
let category: String?
let language: String?
let country: String?
init(category: String? = nil, language: String? = nil, country: String? = nil) {
self.category = category
self.language = language
self.country = country
}
}
| 016d3d95ac00321dbb6e2428f8c26827 | 20.1 | 84 | 0.64218 | false | false | false | false |
LuisPalacios/lupa | refs/heads/master | lupa/Global/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// lupa
//
// Created by Luis Palacios on 11/8/15.
// Copyright © 2015 Luis Palacios. All rights reserved.
//
import Cocoa
// ErroType's
//
enum skControllerNotReady: Error {
case cannotActivate
case cannotCreate
case cannotAccessIconImage
}
extension skControllerNotReady: CustomStringConvertible {
var description: String {
switch self {
case .cannotActivate: return "Attention! can't activate the custom NSViewController"
case .cannotCreate: return "Attention! can't create the custom NSViewController"
case .cannotAccessIconImage : return "Attention! can't access the Icon Image"
}
}
}
// Main app entry point
//
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
/// --------------------------------------------------------------------------------
// MARK: Attributes
/// --------------------------------------------------------------------------------
// For the following attributes I'm using Implicitly Unwrapped Optional (!)
// they are optionals and no need to initialize them here, will do later.
var lupaSearchCtrl : LupaSearchWinCtrl! // My Window for the status bar
var lupaDefaultsController : LupaDefaults! // Preferences Window
var defaultWindow : NSWindow! // Find out the main window (to hide it)
// Key's to observe for the HotKeys
var observableKeys_HotKey = [ LUPADefaults.lupa_HotkeyEnabled ]
// Connected to MainMenu.xib objects through Interface Builder
@IBOutlet weak var statusMenu: NSMenu!
// In order to work with the user defaults, stored under:
// /Users/<your_user>/Library/Preferences/parchis.org.lupa.plist
// $ defaults read parchis.org.lupa.plist
let userDefaults : UserDefaults = UserDefaults.standard
// To prepare the program name with GIT numbers
var programName : String = ""
/// --------------------------------------------------------------------------------
// MARK: Main
/// --------------------------------------------------------------------------------
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Ask to visualize the mutually exclusive constraints
let userDefaults : UserDefaults = UserDefaults.standard
userDefaults.set(true, forKey: "NSConstraintBasedLayoutVisualizeMutuallyExclusiveConstraints")
// NOTE: In order for the Icon disapear from the Dock and also disapear
// from the CMD-ALT list I also modified the Info.plist and added:
//
// Application is agent (UIElement) -> YES
//
/// Prepare windows
// I deleted the default main window from MainMenu.xib but just in
// case double check and hide it.
defaultWindow = NSApplication.shared.windows.first
if defaultWindow != nil {
defaultWindow.close()
}
/// Program name
// Store my program name.
self.programName = programLongName()
/// HotKey
// Register default values to be used when app start for the first time
// I ship with some already predefined values for some keys.
self.userDefaults.register( defaults: [ LUPADefaults.lupa_HotkeyEnabled:true ] )
// Start observing changes in the user Defaults hotkey properties...
self.loadKVO()
// Initialize the defaults Preferences Window
self.lupaDefaultsController = LupaDefaults(windowNibName: NSNib.Name(rawValue: "LupaDefaults"))
/// Create my custom View Controller
// Based on LPStatusItem framework singleton
//
var success: Bool = false
do {
try createCustomViewController()
do {
/// Activate the status bar and make all connections
///
try activateStatusBarWithWinController()
success = true
} catch let error as skControllerNotReady {
print(error.description)
} catch {
print ("Undefinded error")
}
} catch let error as skControllerNotReady {
print(error.description)
} catch {
print ("Undefinded error")
}
// Show result
if success {
// print("AppDelegate: Everything WENT WELL!!!")
} else {
print("AppDelegate: Something really bad hapenned !!!!")
}
}
func applicationWillTerminate(_ aNotification: Notification) {
// Deactivate the KVO - Key Value Observing
self.unloadKVO()
}
/// --------------------------------------------------------------------------------
// MARK: IBActions through First Responder
/// --------------------------------------------------------------------------------
//
// Show the preferences window:
// When the user selects "Preferences" it will go through the First Responder
// chain till it finds someone implementing this method.
// I just use it thorugh First Responder.
//
// Connect MainMenu.xib->Program->Preferences with FirstResponder->"showPreferences:"
//
@IBAction func showPreferences(_ sender : AnyObject) {
// Open the preferences (Defaults) window
//
if let window = self.lupaDefaultsController.window {
NSApplication.shared.activate(ignoringOtherApps: true)
window.makeKeyAndOrderFront(self)
window.center()
if let h = NSScreen.main?.visibleFrame.size.height {
let newOrigin = CGPoint(x: window.frame.origin.x, y: h-window.frame.size.height)
window.setFrameOrigin(newOrigin)
}
}
}
//
// Show the searc box view:
//
// Connect with FirstResponder->"showSearchBox:"
//
@IBAction func showSearchBox(_ sender : AnyObject) {
// Ask the LPStatusItem to manifest
lpStatusItem.showStatusItemWindow()
}
/// --------------------------------------------------------------------------------
// MARK: Main custom view controller and status bar activation
/// --------------------------------------------------------------------------------
// Create my custom View Controller which will be shown under
// the status bar.
//
func createCustomViewController () throws {
/// CREATE LupaSearchWinCtrl !!!
//
// Prepare the name of the NIB (from the name of the class)
let searchWinNibName = NSStringFromClass(LupaSearchWinCtrl.self).components(separatedBy: ".").last!
// ..and create custom Win Controller
lupaSearchCtrl = LupaSearchWinCtrl(windowNibName: NSNib.Name(rawValue: searchWinNibName))
}
// Activate status bar and make connections
//
func activateStatusBarWithWinController() throws {
//
// Activate my (singleton) "lpStatusItem" (Status Bar Item) passing:
//
// the custom view controller
// the custom icon
//
if ( lupaSearchCtrl != nil ) {
if let letItemImage = NSImage(named: NSImage.Name(rawValue: "LupaOn_18x18")) {
let itemImage = letItemImage
lpStatusItem.activateStatusItemWithMenuImageWindow(self.statusMenu, itemImage: itemImage, winController: lupaSearchCtrl)
} else {
throw skControllerNotReady.cannotAccessIconImage
}
} else {
throw skControllerNotReady.cannotActivate
}
}
/// --------------------------------------------------------------------------------
// MARK: KVO - Key Value Observing activation, de-activation and action
/// --------------------------------------------------------------------------------
// Context (up=unsafe pointer)
fileprivate var upLUPA_AppDelegate_KVOContext_HotKey = 0
// Load and activate the Key Value Observing
//
func loadKVO () {
self.onObserver()
}
// Activate the observer
//
func onObserver () {
// Options
// I'm setting .Initial so a notification should be sent to the observer immediately,
// before the observer registration method even returns. Nice trick to perform initial setup...
//
let options = NSKeyValueObservingOptions([.initial, .new])
for item in self.observableKeys_HotKey {
// print("\(self.userDefaults).addObserver(\(self), item: \(item), options: \(options), context: &upLUPA_AppDelegate_KVOContext_HotKey)")
self.userDefaults.addObserver(
self,
forKeyPath: item,
options: options,
context: &upLUPA_AppDelegate_KVOContext_HotKey)
}
}
// Deactivate and unload the Key Value Observing
//
func unloadKVO () {
self.offObserver()
}
// Deactivate the observer
//
func offObserver () {
for item in self.observableKeys_HotKey {
// print("\(self.userDefaults) removeObserver(\(self), forKeyPath: \(item), context: &upLUPA_AppDelegate_KVOContext_HotKey))")
self.userDefaults.removeObserver(self, forKeyPath: item, context: &upLUPA_AppDelegate_KVOContext_HotKey)
}
}
// Actions when a change comes...
//
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
// Act on the appropiate context
if context == &upLUPA_AppDelegate_KVOContext_HotKey {
// New guard statement to return early if there's no change.
guard let change = change else {
// print("No change, return")
return
}
// Identify the kind of change
//
if let rv = change[NSKeyValueChangeKey.kindKey] as? UInt,
let kind = NSKeyValueChange(rawValue: rv) {
switch kind {
case .setting:
if ( keyPath == LUPADefaults.lupa_HotkeyEnabled ) {
if let letNewValue : Bool = (change[NSKeyValueChangeKey.newKey] as AnyObject).boolValue {
let newValue = letNewValue
self.activateHotKey(newValue)
}
}
case .insertion:
// print(".Insertion -> \(change[NSKeyValueChangeNewKey]) ")
break
case .removal:
// print(".Removal -> \(change[NSKeyValueChangeOldKey]) ")
break
case .replacement:
// print(".Replacement -> \(change[NSKeyValueChangeOldKey]) ")
break
}
// Debug purposes
//print("change[NSKeyValueChangeNewKey] -> \(change[NSKeyValueChangeNewKey]) ")
//print("change[NSKeyValueChangeOldKey] -> \(change[NSKeyValueChangeOldKey]) ")
//print("change[NSKeyValueChangeIndexesKey] -> \(change[NSKeyValueChangeIndexesKey]) ")
//print("change[NSKeyValueChangeNotificationIsPriorKey] -> \(change[NSKeyValueChangeNotificationIsPriorKey]) ")
}
} else {
// Defaults...
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
/// --------------------------------------------------------------------------------
// MARK: Hotkey actioning
/// --------------------------------------------------------------------------------
// Activate or deactivate the Shortcut HotKey
//
func activateHotKey (_ newValue: Bool) {
if newValue == true {
MASShortcutBinder.shared().bindShortcut(withDefaultsKey: LUPADefaults.lupa_Hotkey, toAction: {
self.actionHotKey()
})
} else {
MASShortcutBinder.shared().breakBinding(withDefaultsKey: LUPADefaults.lupa_Hotkey)
}
}
// Action when the HotKey is Pressed
//
func actionHotKey() {
// Send a message to firstResponder
NSApplication.shared.sendAction(#selector(AppDelegate.showSearchBox(_:)), to: nil, from: self)
}
}
| 10fc050d2da5356fd53d1e8a6c855554 | 36.339181 | 151 | 0.54119 | false | false | false | false |
debugsquad/Hyperborea | refs/heads/master | Hyperborea/Model/Search/MSearchContentModeItemSynonyms.swift | mit | 1 | import UIKit
class MSearchContentModeItemSynonyms:MSearchContentModeItem
{
private let kCellAddedHeight:CGFloat = 40
init()
{
let title:String = NSLocalizedString("MSearchContentModeItemSynonyms_title", comment:"")
let symbol:String = NSLocalizedString("MSearchContentModeItemSynonyms_symbol", comment:"")
let reusableIdentifier:String = VSearchContentCellSynonyms.reusableIdentifier
super.init(
title:title,
symbol:symbol,
reusableIdentifier:reusableIdentifier)
}
override func selected(controller:CSearch)
{
controller.fetchSynonyms()
}
override func usingString(controller:CSearch) -> NSAttributedString?
{
let attributedString:NSAttributedString? = controller.modelEntry?.synonyms?.attributedString
return attributedString
}
override func contentHeight(controller:CSearch) -> CGFloat
{
let textHeight:CGFloat = heightForString(controller:controller)
var cellHeight:CGFloat = textHeight
if textHeight > 0
{
cellHeight += kCellAddedHeight
}
return cellHeight
}
}
| d2c891bf669b8ea8ea11b5470993effe | 27.511628 | 100 | 0.654976 | false | false | false | false |
PiXeL16/BudgetShare | refs/heads/master | BudgetShareTests/Modules/BudgetDetail/BudgetDetailList/View/MockBudgetDetailListView.swift | mit | 1 | @testable import BudgetShare
import Foundation
import UIKit
class MockBudgetDetailListView: BudgetDetailListView {
var invokedControllerGetter = false
var invokedControllerGetterCount = 0
var stubbedController: UIViewController!
var controller: UIViewController? {
invokedControllerGetter = true
invokedControllerGetterCount += 1
return stubbedController
}
var invokedPresenterSetter = false
var invokedPresenterSetterCount = 0
var invokedPresenter: BudgetDetailListModule?
var invokedPresenterList = [BudgetDetailListModule?]()
var invokedPresenterGetter = false
var invokedPresenterGetterCount = 0
var stubbedPresenter: BudgetDetailListModule!
var presenter: BudgetDetailListModule! {
set {
invokedPresenterSetter = true
invokedPresenterSetterCount += 1
invokedPresenter = newValue
invokedPresenterList.append(newValue)
}
get {
invokedPresenterGetter = true
invokedPresenterGetterCount += 1
return stubbedPresenter
}
}
var invokedDidReceiveError = false
var invokedDidReceiveErrorCount = 0
var invokedDidReceiveErrorParameters: (message: String, Void)?
var invokedDidReceiveErrorParametersList = [(message: String, Void)]()
func didReceiveError(message: String) {
invokedDidReceiveError = true
invokedDidReceiveErrorCount += 1
invokedDidReceiveErrorParameters = (message, ())
invokedDidReceiveErrorParametersList.append((message, ()))
}
var invokedDidUpdateBudgetDataSource = false
var invokedDidUpdateBudgetDataSourceCount = 0
var invokedDidUpdateBudgetDataSourceParameters: (dataSource: BudgetDetailListDatasource, Void)?
var invokedDidUpdateBudgetDataSourceParametersList = [(dataSource: BudgetDetailListDatasource, Void)]()
func didUpdateBudgetDataSource(dataSource: BudgetDetailListDatasource) {
invokedDidUpdateBudgetDataSource = true
invokedDidUpdateBudgetDataSourceCount += 1
invokedDidUpdateBudgetDataSourceParameters = (dataSource, ())
invokedDidUpdateBudgetDataSourceParametersList.append((dataSource, ()))
}
}
| 96dcd553bdfdc5e4a2ddad1c66cfbefc | 37.568966 | 107 | 0.731337 | false | false | false | false |
RobinChao/Hacking-with-Swift | refs/heads/master | HackingWithSwift-02/HackingWithSwift-02/ViewController.swift | mit | 1 | //
// ViewController.swift
// HackingWithSwift-02
//
// Created by Robin on 2/18/16.
// Copyright © 2016 Robin. All rights reserved.
//
import UIKit
import GameplayKit
class ViewController: UIViewController {
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!
var countries = [String]()
var score = 0
var correntAnswer = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
countries += ["estonia", "france", "germany", "ireland", "italy", "monaco", "nigeria", "poland", "russia", "spain", "uk", "us"]
button1.layer.borderWidth = 1
button2.layer.borderWidth = 1
button3.layer.borderWidth = 1
button1.layer.borderColor = UIColor.lightGrayColor().CGColor
button2.layer.borderColor = UIColor.lightGrayColor().CGColor
button3.layer.borderColor = UIColor.lightGrayColor().CGColor
askQuestion(nil)
}
func askQuestion(action: UIAlertAction!) {
countries = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(countries) as! [String]
button1.setBackgroundImage(UIImage(named: countries[0]), forState: .Normal)
button2.setBackgroundImage(UIImage(named: countries[1]), forState: .Normal)
button3.setBackgroundImage(UIImage(named: countries[2]), forState: .Normal)
correntAnswer = GKRandomSource.sharedRandom().nextIntWithUpperBound(3)
title = countries[correntAnswer].uppercaseString
}
@IBAction func buttonTapped(sender: AnyObject) {
var title: String
if (sender.tag == correntAnswer){
title = "Corrent"
score += 1
}else{
title = "Wrong"
score -= 1
}
let alertController = UIAlertController(title: title, message: "Your score is \(score).", preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Continue", style: .Default, handler: askQuestion))
presentViewController(alertController, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 0604fcc63c3bcf6dbe7aa123148cef3b | 29.65 | 135 | 0.630506 | false | false | false | false |
coinbase/coinbase-ios-sdk | refs/heads/master | Example/Source/ViewControllers/Menu/MenuViewController.swift | apache-2.0 | 1 | //
// MenuViewController.swift
// iOS Example
//
// Copyright © 2018 Coinbase All rights reserved.
//
import UIKit
import CoinbaseSDK
class MenuViewController: UIViewController {
private static let kErrorAlertTitle = "Something went wrong."
private static let kSuccessAlertTitle = "Success!"
private static let kEmptyTokenAlertMessage = "Unable to refresh access token. Refresh token is empty."
private static let kRevokeAlertTitle = "Revoke Token."
private static let kRevokeAlertMessage = "Are you sure you want to revoke token? This will automatically log you out."
private static let kRevokeAlertActionTitle = "Revoke"
private static let kRevokeAlertCancelTitle = "Cancel"
private static let kRevokeSuccessAlertMessage = "Token was successfully revoked."
private let coinbase = Coinbase.default
// MARK: - IBAction Methods
@IBAction func logOutAction(_ sender: UIBarButtonItem) {
RootControllerCoordinator.setRoot(.authorization)
guard let accessToken = TokenUtils.loadAccessToken() else {
return
}
coinbase.tokenResource.revoke(accessToken: accessToken) { _ in }
}
@IBAction func refreshTokenAction() {
guard let refreshToken = TokenUtils.loadRefreshToken() else {
presentSimpleAlert(title: MenuViewController.kErrorAlertTitle,
message: MenuViewController.kEmptyTokenAlertMessage)
return
}
coinbase.tokenResource.refresh(clientID: OAuth2ApplicationKeys.clientID,
clientSecret: OAuth2ApplicationKeys.clientSecret,
refreshToken: refreshToken) { [weak self] result in
switch result {
case .success(let userToken):
let message = self?.tokenInfoMessage(from: userToken)
self?.presentSimpleAlert(title: MenuViewController.kSuccessAlertTitle,
message: message)
case .failure(let error):
self?.present(error: error)
}
}
}
@IBAction func revokeTokenAction() {
let alertController = UIAlertController(title: MenuViewController.kRevokeAlertTitle,
message: MenuViewController.kRevokeAlertMessage,
preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: MenuViewController.kRevokeAlertActionTitle, style: .destructive) { [weak self] _ in
self?.revokeToken()
})
alertController.addAction(UIAlertAction(title: MenuViewController.kRevokeAlertCancelTitle, style: .cancel))
present(alertController, animated: true)
}
// MARK: - Private Methods
private func tokenInfoMessage(from userToken: UserToken) -> String {
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .short
let date = Date(timeInterval: Double(userToken.expiresIn), since: Date())
return "Token was successfully refreshed.\nNew access token will expire on:\n\n\(formatter.string(from: date))"
}
private func revokeToken() {
guard let accessToken = TokenUtils.loadAccessToken() else {
return
}
coinbase.tokenResource.revoke(accessToken: accessToken, completion: { [weak self] result in
switch result {
case .success:
RootControllerCoordinator.rootViewController?
.presentSimpleAlert(title: MenuViewController.kSuccessAlertTitle,
message: MenuViewController.kRevokeSuccessAlertMessage)
case .failure(let error):
self?.present(error: error)
}
})
}
}
| defbbe27fbdd6dc8b00b579e593de98a | 41.958763 | 138 | 0.591793 | false | false | false | false |
sketchytech/SwiftFiles | refs/heads/master | FilesPlayground.playground/Sources/FileList.swift | mit | 1 | //
// FileList.swift
// SwiftFilesZip
//
// Created by Anthony Levings on 30/04/2015.
// Copyright (c) 2015 Gylphi. All rights reserved.
//
import Foundation
// see here for Apple's ObjC Code https://developer.apple.com/library/mac/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/AccessingFilesandDirectories/AccessingFilesandDirectories.html
public class FileList {
public static func allFilesAndFolders(inDirectory directory:NSSearchPathDirectory, subdirectory:String?) throws -> [NSURL]? {
// Create load path
if let loadPath = buildPathToDirectory(directory, subdirectory: subdirectory) {
let url = NSURL(fileURLWithPath: loadPath)
let properties = [NSURLLocalizedNameKey,
NSURLCreationDateKey, NSURLLocalizedTypeDescriptionKey]
let array = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(url, includingPropertiesForKeys: properties, options:NSDirectoryEnumerationOptions.SkipsHiddenFiles)
return array
}
return nil
}
public static func allFilesAndFoldersInTemporaryDirectory(subdirectory:String?) throws -> [NSURL]? {
// Create load path
let loadPath = buildPathToTemporaryDirectory(subdirectory)
let url = NSURL(fileURLWithPath: loadPath)
let properties = [NSURLLocalizedNameKey,
NSURLCreationDateKey, NSURLLocalizedTypeDescriptionKey]
let array = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(url, includingPropertiesForKeys: properties, options:NSDirectoryEnumerationOptions.SkipsHiddenFiles)
return array
}
// private methods
private static func buildPathToDirectory(directory:NSSearchPathDirectory, subdirectory:String?) -> String? {
// Remove unnecessary slash if need
// Remove unnecessary slash if need
var subDir = ""
if let sub = subdirectory {
subDir = FileHelper.stripSlashIfNeeded(sub)
}
// Create generic beginning to file delete path
var buildPath = ""
if let direct = FileDirectory.applicationDirectory(directory),
path = direct.path {
buildPath = path + "/"
}
buildPath += subDir
buildPath += "/"
var dir:ObjCBool = true
let dirExists = NSFileManager.defaultManager().fileExistsAtPath(buildPath, isDirectory:&dir)
if dir.boolValue == false {
return nil
}
if dirExists == false {
return nil
}
return buildPath
}
public static func buildPathToTemporaryDirectory(subdirectory:String?) -> String {
// Remove unnecessary slash if need
var subDir:String?
if let sub = subdirectory {
subDir = FileHelper.stripSlashIfNeeded(sub)
}
// Create generic beginning to file load path
var loadPath = ""
if let direct = FileDirectory.applicationTemporaryDirectory(),
path = direct.path {
loadPath = path + "/"
}
if let sub = subDir {
loadPath += sub
loadPath += "/"
}
// Add requested save path
return loadPath
}
} | 59f918e3b065da4031fe37254089d1a3 | 30.46789 | 203 | 0.620297 | false | false | false | false |
PlutoMa/SwiftProjects | refs/heads/master | 030.Google Now/GoogleNow/GoogleNow/AnotherViewController.swift | mit | 1 | //
// AnotherViewController.swift
// GoogleNow
//
// Created by Dareway on 2017/11/9.
// Copyright © 2017年 Pluto. All rights reserved.
//
import UIKit
class AnotherViewController: UIViewController {
var dismissButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.navigationController?.isNavigationBarHidden = true
dismissButton = UIButton(type: .custom)
dismissButton.frame.size = CGSize(width: 70, height: 70)
dismissButton.center.x = self.view.center.x
dismissButton.frame.origin.y = self.view.frame.height - 250
dismissButton.backgroundColor = UIColor.red
dismissButton.addTarget(self, action: #selector(dismissAction), for: .touchUpInside)
dismissButton.layer.cornerRadius = dismissButton.frame.width / 2
dismissButton.layer.masksToBounds = true
dismissButton.layer.shadowColor = UIColor.black.cgColor
dismissButton.setImage(#imageLiteral(resourceName: "loading"), for: .normal)
self.view.addSubview(dismissButton)
let leftBottomImgView = UIImageView()
leftBottomImgView.frame.size = CGSize(width: 25, height: 25)
leftBottomImgView.frame.origin = CGPoint(x: 22, y: self.view.frame.height - 25 - 22)
leftBottomImgView.image = #imageLiteral(resourceName: "close")
self.view.addSubview(leftBottomImgView)
let rightBottomImgView = UIImageView()
rightBottomImgView.frame.size = CGSize(width: 25, height: 25)
rightBottomImgView.frame.origin = CGPoint(x: self.view.frame.width - 25 - 22, y: self.view.frame.height - 25 - 22)
rightBottomImgView.image = #imageLiteral(resourceName: "earth")
self.view.addSubview(rightBottomImgView)
let resultLabel = UILabel()
resultLabel.frame.origin = CGPoint(x: 35, y: 35)
resultLabel.text = "Speak Now"
resultLabel.font = UIFont.systemFont(ofSize: 28)
resultLabel.textColor = UIColor(red: 150/255.0, green: 150/255.0, blue: 150/255.0, alpha: 1)
self.view.addSubview(resultLabel)
resultLabel.sizeToFit()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@objc func dismissAction() {
self.dismiss(animated: true, completion: nil)
}
}
| 370952b36ac8ae99d502f61235008509 | 39 | 122 | 0.674167 | false | false | false | false |
jopamer/swift | refs/heads/master | test/Sema/exhaustive_switch.swift | apache-2.0 | 1 | // RUN: %target-typecheck-verify-swift -swift-version 5 -enable-resilience
// RUN: %target-typecheck-verify-swift -swift-version 4 -enable-resilience -enable-nonfrozen-enum-exhaustivity-diagnostics
func foo(a: Int?, b: Int?) -> Int {
switch (a, b) {
case (.none, _): return 1
case (_, .none): return 2
case (.some(_), .some(_)): return 3
}
switch (a, b) {
case (.none, _): return 1
case (_, .none): return 2
case (_?, _?): return 3
}
switch Optional<(Int?, Int?)>.some((a, b)) {
case .none: return 1
case let (_, x?)?: return x
case let (x?, _)?: return x
case (.none, .none)?: return 0
}
}
func bar(a: Bool, b: Bool) -> Int {
switch (a, b) {
case (false, false):
return 1
case (true, _):
return 2
case (false, true):
return 3
}
}
enum Result<T> {
case Ok(T)
case Error(Error)
func shouldWork<U>(other: Result<U>) -> Int {
switch (self, other) { // No warning
case (.Ok, .Ok): return 1
case (.Error, .Error): return 2
case (.Error, _): return 3
case (_, .Error): return 4
}
}
}
func overParenthesized() {
// SR-7492: Space projection needs to treat extra paren-patterns explicitly.
let x: Result<(Result<Int>, String)> = .Ok((.Ok(1), "World"))
switch x {
case let .Error(e):
print(e)
case let .Ok((.Error(e), b)):
print(e, b)
case let .Ok((.Ok(a), b)): // No warning here.
print(a, b)
}
}
enum Foo {
case A(Int)
case B(Int)
}
func foo() {
switch (Foo.A(1), Foo.B(1)) {
case (.A(_), .A(_)):
()
case (.B(_), _):
()
case (_, .B(_)):
()
}
switch (Foo.A(1), Optional<(Int, Int)>.some((0, 0))) {
case (.A(_), _):
break
case (.B(_), (let q, _)?):
print(q)
case (.B(_), nil):
break
}
}
class C {}
enum Bar {
case TheCase(C?)
}
func test(f: Bar) -> Bool {
switch f {
case .TheCase(_?):
return true
case .TheCase(nil):
return false
}
}
func op(this : Optional<Bool>, other : Optional<Bool>) -> Optional<Bool> {
switch (this, other) { // No warning
case let (.none, w):
return w
case let (w, .none):
return w
case let (.some(e1), .some(e2)):
return .some(e1 && e2)
}
}
enum Threepeat {
case a, b, c
}
func test3(x: Threepeat, y: Threepeat) {
switch (x, y) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{add missing case: '(.a, .c)'}}
case (.a, .a):
()
case (.b, _):
()
case (.c, _):
()
case (_, .b):
()
}
}
enum A {
case A(Int)
case B(Bool)
case C
case D
}
enum B {
case A
case B
}
func s(a: A, b: B) {
switch (a, b) {
case (.A(_), .A):
break
case (.A(_), .B):
break
case (.B(_), let b):
// expected-warning@-1 {{immutable value 'b' was never used; consider replacing with '_' or removing it}}
break
case (.C, _), (.D, _):
break
}
}
enum Grimble {
case A
case B
case C
}
enum Gromble {
case D
case E
}
func doSomething(foo:Grimble, bar:Gromble) {
switch(foo, bar) { // No warning
case (.A, .D):
break
case (.A, .E):
break
case (.B, _):
break
case (.C, _):
break
}
}
enum E {
case A
case B
}
func f(l: E, r: E) {
switch (l, r) {
case (.A, .A):
return
case (.A, _):
return
case (_, .A):
return
case (.B, .B):
return
}
}
enum TestEnum {
case A, B
}
func switchOverEnum(testEnumTuple: (TestEnum, TestEnum)) {
switch testEnumTuple {
case (_,.B):
// Matches (.A, .B) and (.B, .B)
break
case (.A,_):
// Matches (.A, .A)
// Would also match (.A, .B) but first case takes precedent
break
case (.B,.A):
// Matches (.B, .A)
break
}
}
func tests(a: Int?, b: String?) {
switch (a, b) {
case let (.some(n), _): print("a: ", n, "?")
case (.none, _): print("Nothing", "?")
}
switch (a, b) {
case let (.some(n), .some(s)): print("a: ", n, "b: ", s)
case let (.some(n), .none): print("a: ", n, "Nothing")
case (.none, _): print("Nothing")
}
switch (a, b) {
case let (.some(n), .some(s)): print("a: ", n, "b: ", s)
case let (.some(n), .none): print("a: ", n, "Nothing")
case let (.none, .some(s)): print("Nothing", "b: ", s)
case (.none, _): print("Nothing", "?")
}
switch (a, b) {
case let (.some(n), .some(s)): print("a: ", n, "b: ", s)
case let (.some(n), .none): print("a: ", n, "Nothing")
case let (.none, .some(s)): print("Nothing", "b: ", s)
case (.none, .none): print("Nothing", "Nothing")
}
}
enum X {
case Empty
case A(Int)
case B(Int)
}
func f(a: X, b: X) {
switch (a, b) {
case (_, .Empty): ()
case (.Empty, _): ()
case (.A, .A): ()
case (.B, .B): ()
case (.A, .B): ()
case (.B, .A): ()
}
}
func f2(a: X, b: X) {
switch (a, b) {
case (.A, .A): ()
case (.B, .B): ()
case (.A, .B): ()
case (.B, .A): ()
case (_, .Empty): ()
case (.Empty, _): ()
case (.A, .A): () // expected-warning {{case is already handled by previous patterns; consider removing it}}
case (.B, .B): () // expected-warning {{case is already handled by previous patterns; consider removing it}}
case (.A, .B): () // expected-warning {{case is already handled by previous patterns; consider removing it}}
case (.B, .A): () // expected-warning {{case is already handled by previous patterns; consider removing it}}
default: ()
}
}
enum XX : Int {
case A
case B
case C
case D
case E
}
func switcheroo(a: XX, b: XX) -> Int {
switch(a, b) { // No warning
case (.A, _) : return 1
case (_, .A) : return 2
case (.C, _) : return 3
case (_, .C) : return 4
case (.B, .B) : return 5
case (.B, .D) : return 6
case (.D, .B) : return 7
case (.B, .E) : return 8
case (.E, .B) : return 9
case (.E, _) : return 10
case (_, .E) : return 11
case (.D, .D) : return 12
default:
print("never hits this:", a, b)
return 13
}
}
enum PatternCasts {
case one(Any)
case two
case three(String)
}
func checkPatternCasts() {
// Pattern casts with this structure shouldn't warn about duplicate cases.
let x: PatternCasts = .one("One")
switch x {
case .one(let s as String): print(s)
case .one: break
case .two: break
case .three: break
}
// But should warn here.
switch x {
case .one(_): print(s)
case .one: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
case .two: break
case .three: break
}
// And not here
switch x {
case .one: break
case .two: break
case .three(let s as String?): print(s as Any)
}
}
enum MyNever {}
func ~= (_ : MyNever, _ : MyNever) -> Bool { return true }
func myFatalError() -> MyNever { fatalError() }
func checkUninhabited() {
// Scrutinees of uninhabited type may match any number and kind of patterns
// that Sema is willing to accept at will. After all, it's quite a feat to
// productively inhabit the type of crashing programs.
func test1(x : Never) {
switch x {} // No diagnostic.
}
func test2(x : Never) {
switch (x, x) {} // No diagnostic.
}
func test3(x : MyNever) {
switch x { // No diagnostic.
case myFatalError(): break
case myFatalError(): break
case myFatalError(): break
}
}
}
enum Runcible {
case spoon
case hat
case fork
}
func checkDiagnosticMinimality(x: Runcible?) {
switch (x!, x!) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{add missing case: '(.fork, _)'}}
// expected-note@-2 {{add missing case: '(.hat, .hat)'}}
// expected-note@-3 {{add missing case: '(_, .fork)'}}
case (.spoon, .spoon):
break
case (.spoon, .hat):
break
case (.hat, .spoon):
break
}
switch (x!, x!) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{add missing case: '(.fork, _)'}}
// expected-note@-2 {{add missing case: '(.hat, .spoon)'}}
// expected-note@-3 {{add missing case: '(.spoon, .hat)'}}
// expected-note@-4 {{add missing case: '(_, .fork)'}}
case (.spoon, .spoon):
break
case (.hat, .hat):
break
}
}
enum LargeSpaceEnum {
case case0
case case1
case case2
case case3
case case4
case case5
case case6
case case7
case case8
case case9
case case10
}
func notQuiteBigEnough() -> Bool {
switch (LargeSpaceEnum.case1, LargeSpaceEnum.case2) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 110 {{add missing case:}}
case (.case0, .case0): return true
case (.case1, .case1): return true
case (.case2, .case2): return true
case (.case3, .case3): return true
case (.case4, .case4): return true
case (.case5, .case5): return true
case (.case6, .case6): return true
case (.case7, .case7): return true
case (.case8, .case8): return true
case (.case9, .case9): return true
case (.case10, .case10): return true
}
}
enum OverlyLargeSpaceEnum {
case case0
case case1
case case2
case case3
case case4
case case5
case case6
case case7
case case8
case case9
case case10
case case11
}
enum ContainsOverlyLargeEnum {
case one(OverlyLargeSpaceEnum)
case two(OverlyLargeSpaceEnum)
case three(OverlyLargeSpaceEnum, OverlyLargeSpaceEnum)
}
func quiteBigEnough() -> Bool {
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{the compiler is unable to check that this switch is exhaustive in reasonable time}}
// expected-note@-1 {{do you want to add a default clause?}}
case (.case0, .case0): return true
case (.case1, .case1): return true
case (.case2, .case2): return true
case (.case3, .case3): return true
case (.case4, .case4): return true
case (.case5, .case5): return true
case (.case6, .case6): return true
case (.case7, .case7): return true
case (.case8, .case8): return true
case (.case9, .case9): return true
case (.case10, .case10): return true
case (.case11, .case11): return true
}
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{the compiler is unable to check that this switch is exhaustive in reasonable time}}
// expected-note@-1 {{do you want to add a default clause?}}
case (.case0, _): return true
case (.case1, _): return true
case (.case2, _): return true
case (.case3, _): return true
case (.case4, _): return true
case (.case5, _): return true
case (.case6, _): return true
case (.case7, _): return true
case (.case8, _): return true
case (.case9, _): return true
case (.case10, _): return true
}
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{the compiler is unable to check that this switch is exhaustive in reasonable time}}
case (.case0, _): return true
case (.case1, _): return true
case (.case2, _): return true
case (.case3, _): return true
case (.case4, _): return true
case (.case5, _): return true
case (.case6, _): return true
case (.case7, _): return true
case (.case8, _): return true
case (.case9, _): return true
case (.case10, _): return true
@unknown default: return false // expected-note {{remove '@unknown' to handle remaining values}} {{3-12=}}
}
// No diagnostic
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
case (.case0, _): return true
case (.case1, _): return true
case (.case2, _): return true
case (.case3, _): return true
case (.case4, _): return true
case (.case5, _): return true
case (.case6, _): return true
case (.case7, _): return true
case (.case8, _): return true
case (.case9, _): return true
case (.case10, _): return true
case (.case11, _): return true
}
// No diagnostic
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
case (_, .case0): return true
case (_, .case1): return true
case (_, .case2): return true
case (_, .case3): return true
case (_, .case4): return true
case (_, .case5): return true
case (_, .case6): return true
case (_, .case7): return true
case (_, .case8): return true
case (_, .case9): return true
case (_, .case10): return true
case (_, .case11): return true
}
// No diagnostic
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
case (_, _): return true
}
// No diagnostic
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
case (.case0, .case0): return true
case (.case1, .case1): return true
case (.case2, .case2): return true
case (.case3, .case3): return true
case _: return true
}
// No diagnostic
switch ContainsOverlyLargeEnum.one(.case0) {
case .one: return true
case .two: return true
case .three: return true
}
// Make sure we haven't just stopped emitting diagnostics.
switch OverlyLargeSpaceEnum.case1 { // expected-error {{switch must be exhaustive}} expected-note 12 {{add missing case}} expected-note {{handle unknown values}}
}
}
indirect enum InfinitelySized {
case one
case two
case recur(InfinitelySized)
case mutualRecur(MutuallyRecursive, InfinitelySized)
}
indirect enum MutuallyRecursive {
case one
case two
case recur(MutuallyRecursive)
case mutualRecur(InfinitelySized, MutuallyRecursive)
}
func infinitelySized() -> Bool {
switch (InfinitelySized.one, InfinitelySized.one) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 8 {{add missing case:}}
case (.one, .one): return true
case (.two, .two): return true
}
switch (MutuallyRecursive.one, MutuallyRecursive.one) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 8 {{add missing case:}}
case (.one, .one): return true
case (.two, .two): return true
}
}
func diagnoseDuplicateLiterals() {
let str = "def"
let int = 2
let dbl = 2.5
// No Diagnostics
switch str {
case "abc": break
case "def": break
case "ghi": break
default: break
}
switch str {
case "abc": break
case "def": break // expected-note {{first occurrence of identical literal pattern is here}}
case "def": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case "ghi": break
default: break
}
switch str {
case "abc", "def": break // expected-note 2 {{first occurrence of identical literal pattern is here}}
case "ghi", "jkl": break
case "abc", "def": break // expected-warning 2 {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
switch str {
case "xyz": break // expected-note {{first occurrence of identical literal pattern is here}}
case "ghi": break
case "def": break
case "abc": break
case "xyz": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
func someStr() -> String { return "sdlkj" }
let otherStr = "ifnvbnwe"
switch str {
case "sdlkj": break
case "ghi": break // expected-note {{first occurrence of identical literal pattern is here}}
case someStr(): break
case "def": break
case otherStr: break
case "xyz": break // expected-note {{first occurrence of identical literal pattern is here}}
case "ifnvbnwe": break
case "ghi": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case "xyz": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
// No Diagnostics
switch int {
case -2: break
case -1: break
case 0: break
case 1: break
case 2: break
case 3: break
default: break
}
switch int {
case -2: break // expected-note {{first occurrence of identical literal pattern is here}}
case -2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 1: break
case 2: break // expected-note {{first occurrence of identical literal pattern is here}}
case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 3: break
default: break
}
switch int {
case -2, -2: break // expected-note {{first occurrence of identical literal pattern is here}} expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 1, 2: break // expected-note 3 {{first occurrence of identical literal pattern is here}}
case 2, 3: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 1, 2: break // expected-warning 2 {{literal value is already handled by previous pattern; consider removing it}}
case 4, 5: break
case 7, 7: break // expected-note {{first occurrence of identical literal pattern is here}}
// expected-warning@-1 {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
switch int {
case 1: break // expected-note {{first occurrence of identical literal pattern is here}}
case 2: break // expected-note 2 {{first occurrence of identical literal pattern is here}}
case 3: break
case 17: break // expected-note {{first occurrence of identical literal pattern is here}}
case 4: break
case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 001: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 5: break
case 0x11: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 0b10: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
switch int {
case 10: break
case 0b10: break // expected-note {{first occurrence of identical literal pattern is here}}
case -0b10: break // expected-note {{first occurrence of identical literal pattern is here}}
case 3000: break
case 0x12: break // expected-note {{first occurrence of identical literal pattern is here}}
case 400: break
case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case -2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 18: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
func someInt() -> Int { return 0x1234 }
let otherInt = 13254
switch int {
case 13254: break
case 3000: break
case 00000002: break // expected-note {{first occurrence of identical literal pattern is here}}
case 0x1234: break
case someInt(): break
case 400: break
case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 18: break
case otherInt: break
case 230: break
default: break
}
// No Diagnostics
switch dbl {
case -3.5: break
case -2.5: break
case -1.5: break
case 1.5: break
case 2.5: break
case 3.5: break
default: break
}
switch dbl {
case -3.5: break
case -2.5: break // expected-note {{first occurrence of identical literal pattern is here}}
case -2.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case -1.5: break
case 1.5: break
case 2.5: break // expected-note {{first occurrence of identical literal pattern is here}}
case 2.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 3.5: break
default: break
}
switch dbl {
case 1.5, 4.5, 7.5, 6.9: break // expected-note 2 {{first occurrence of identical literal pattern is here}}
case 3.4, 1.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 7.5, 2.3: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
switch dbl {
case 1: break
case 1.5: break // expected-note 2 {{first occurrence of identical literal pattern is here}}
case 2.5: break
case 3.5: break // expected-note {{first occurrence of identical literal pattern is here}}
case 5.3132: break
case 1.500: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 46.2395: break
case 1.5000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 0003.50000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 23452.43: break
default: break
}
func someDouble() -> Double { return 324.4523 }
let otherDouble = 458.2345
switch dbl {
case 1: break // expected-note {{first occurrence of identical literal pattern is here}}
case 1.5: break
case 2.5: break
case 3.5: break // expected-note {{first occurrence of identical literal pattern is here}}
case 5.3132: break
case 46.2395: break
case someDouble(): break
case 0003.50000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case otherDouble: break
case 2.50505: break // expected-note {{first occurrence of identical literal pattern is here}}
case 23452.43: break
case 00001: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 123453: break
case 2.50505000000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
}
func checkLiteralTuples() {
let str1 = "abc"
let str2 = "def"
let int1 = 23
let int2 = 7
let dbl1 = 4.23
let dbl2 = 23.45
// No Diagnostics
switch (str1, str2) {
case ("abc", "def"): break
case ("def", "ghi"): break
case ("ghi", "def"): break
case ("abc", "def"): break // We currently don't catch this
default: break
}
// No Diagnostics
switch (int1, int2) {
case (94, 23): break
case (7, 23): break
case (94, 23): break // We currently don't catch this
case (23, 7): break
default: break
}
// No Diagnostics
switch (dbl1, dbl2) {
case (543.21, 123.45): break
case (543.21, 123.45): break // We currently don't catch this
case (23.45, 4.23): break
case (4.23, 23.45): break
default: break
}
}
func sr6975() {
enum E {
case a, b
}
let e = E.b
switch e {
case .a as E: // expected-warning {{'as' test is always true}}
print("a")
case .b: // Valid!
print("b")
case .a: // expected-warning {{case is already handled by previous patterns; consider removing it}}
print("second a")
}
func foo(_ str: String) -> Int {
switch str { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{do you want to add a default clause?}}
case let (x as Int) as Any:
return x
}
}
_ = foo("wtf")
}
public enum NonExhaustive {
case a, b
}
public enum NonExhaustivePayload {
case a(Int), b(Bool)
}
@_frozen public enum TemporalProxy {
case seconds(Int)
case milliseconds(Int)
case microseconds(Int)
case nanoseconds(Int)
@_downgrade_exhaustivity_check
case never
}
// Inlinable code is considered "outside" the module and must include a default
// case.
@inlinable
public func testNonExhaustive(_ value: NonExhaustive, _ payload: NonExhaustivePayload, for interval: TemporalProxy, flag: Bool) {
switch value { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{none}}
case .a: break
}
switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{3-3=@unknown default:\n<#fatalError#>()\n}}
case .a: break
case .b: break
}
switch value {
case .a: break
case .b: break
default: break // no-warning
}
switch value {
case .a: break
case .b: break
@unknown case _: break // no-warning
}
switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}}
case .a: break
@unknown case _: break
}
switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.a'}} {{none}} expected-note {{add missing case: '.b'}} {{none}}
@unknown case _: break
}
switch value {
case _: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
// Test being part of other spaces.
switch value as Optional { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.some(_)'}}
case .a?: break
case .b?: break
case nil: break
}
switch value as Optional {
case .a?: break
case .b?: break
case nil: break
@unknown case _: break
} // no-warning
switch value as Optional {
case _?: break
case nil: break
} // no-warning
switch (value, flag) { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '(_, false)'}}
case (.a, _): break
case (.b, false): break
case (_, true): break
}
switch (value, flag) {
case (.a, _): break
case (.b, false): break
case (_, true): break
@unknown case _: break
} // no-warning
switch (flag, value) { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '(false, _)'}}
case (_, .a): break
case (false, .b): break
case (true, _): break
}
switch (flag, value) {
case (_, .a): break
case (false, .b): break
case (true, _): break
@unknown case _: break
} // no-warning
switch (value, value) { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '(_, _)'}}
case (.a, _), (_, .a): break
case (.b, _), (_, .b): break
}
switch (value, value) {
case (.a, _), (_, .a): break
case (.b, _), (_, .b): break
@unknown case _: break
} // no-warning
// Test interaction with @_downgrade_exhaustivity_check.
switch (value, interval) { // expected-warning {{switch must be exhaustive}} {{none}}
// expected-note@-1 {{add missing case: '(_, .milliseconds(_))'}}
// expected-note@-2 {{add missing case: '(_, .microseconds(_))'}}
// expected-note@-3 {{add missing case: '(_, .nanoseconds(_))'}}
// expected-note@-4 {{add missing case: '(_, .never)'}}
case (_, .seconds): break
case (.a, _): break
case (.b, _): break
}
switch (value, interval) { // expected-warning {{switch must be exhaustive}} {{none}}
// expected-note@-1 {{add missing case: '(_, .seconds(_))'}}
// expected-note@-2 {{add missing case: '(_, .milliseconds(_))'}}
// expected-note@-3 {{add missing case: '(_, .microseconds(_))'}}
// expected-note@-4 {{add missing case: '(_, .nanoseconds(_))'}}
case (_, .never): break
case (.a, _): break
case (.b, _): break
}
// Test payloaded enums.
switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{none}}
case .a: break
}
switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{3-3=@unknown default:\n<#fatalError#>()\n}}
case .a: break
case .b: break
}
switch payload {
case .a: break
case .b: break
default: break // no-warning
}
switch payload {
case .a: break
case .b: break
@unknown case _: break // no-warning
}
switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}}
case .a: break
@unknown case _: break
}
switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{none}}
case .a: break
case .b(false): break
}
switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}}
case .a: break
case .b(false): break
@unknown case _: break
}
// Test fully-covered switches.
switch interval {
case .seconds, .milliseconds, .microseconds, .nanoseconds: break
case .never: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
switch flag {
case true: break
case false: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
switch flag as Optional {
case _?: break
case nil: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
switch (flag, value) {
case (true, _): break
case (false, _): break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
}
public func testNonExhaustiveWithinModule(_ value: NonExhaustive, _ payload: NonExhaustivePayload, for interval: TemporalProxy, flag: Bool) {
switch value { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}}
case .a: break
}
switch value { // no-warning
case .a: break
case .b: break
}
switch value {
case .a: break
case .b: break
default: break // no-warning
}
switch value {
case .a: break
case .b: break
@unknown case _: break // no-warning
}
switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}}
case .a: break
@unknown case _: break
}
switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.a'}} {{none}} expected-note {{add missing case: '.b'}} {{none}}
@unknown case _: break
}
switch value {
case _: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
// Test being part of other spaces.
switch value as Optional { // no-warning
case .a?: break
case .b?: break
case nil: break
}
switch value as Optional {
case _?: break
case nil: break
} // no-warning
switch (value, flag) { // no-warning
case (.a, _): break
case (.b, false): break
case (_, true): break
}
switch (flag, value) { // no-warning
case (_, .a): break
case (false, .b): break
case (true, _): break
}
switch (value, value) { // no-warning
case (.a, _): break
case (.b, _): break
case (_, .a): break
case (_, .b): break
}
switch (value, value) { // no-warning
case (.a, _): break
case (.b, _): break
case (_, .a): break
case (_, .b): break
@unknown case _: break
}
// Test interaction with @_downgrade_exhaustivity_check.
switch (value, interval) { // no-warning
case (_, .seconds): break
case (.a, _): break
case (.b, _): break
}
switch (value, interval) { // no-warning
case (_, .never): break
case (.a, _): break
case (.b, _): break
}
// Test payloaded enums.
switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}}
case .a: break
}
switch payload { // no-warning
case .a: break
case .b: break
}
switch payload {
case .a: break
case .b: break
default: break // no-warning
}
switch payload {
case .a: break
case .b: break
@unknown case _: break // no-warning
}
switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}}
case .a: break
@unknown case _: break
}
switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}}
case .a: break
case .b(false): break
}
switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}}
case .a: break
case .b(false): break
@unknown case _: break
}
}
enum UnavailableCase {
case a
case b
@available(*, unavailable)
case oopsThisWasABadIdea
}
enum UnavailableCaseOSSpecific {
case a
case b
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
case unavailableOnAllTheseApplePlatforms
#else
@available(*, unavailable)
case dummyCaseForOtherPlatforms
#endif
}
enum UnavailableCaseOSIntroduced {
case a
case b
@available(macOS 50, iOS 50, tvOS 50, watchOS 50, *)
case notYetIntroduced
}
func testUnavailableCases(_ x: UnavailableCase, _ y: UnavailableCaseOSSpecific, _ z: UnavailableCaseOSIntroduced) {
switch x {
case .a: break
case .b: break
} // no-error
switch y {
case .a: break
case .b: break
} // no-error
switch z {
case .a: break
case .b: break
case .notYetIntroduced: break
} // no-error
}
// The following test used to behave differently when the uninhabited enum was
// defined in the same module as the function (as opposed to using Swift.Never).
enum NoError {}
extension Result where T == NoError {
func testUninhabited() {
switch self {
case .Error(_):
break
// No .Ok case possible because of the 'NoError'.
}
switch self {
case .Error(_):
break
case .Ok(_):
break // But it's okay to write one.
}
}
}
| 654ed550254137a83bc67cce43702dc0 | 25.965462 | 205 | 0.636215 | false | false | false | false |
00buggy00/SwiftOpenGLTutorials | refs/heads/master | 08 StartAnimating/SwiftOpenGLView.swift | mit | 1 | //
// SwiftOpenGLView.swift
// SwiftOpenGL
//
// Created by Myles La Verne Schultz on 10/24/15.
// Copyright © 2015 MyKo. All rights reserved.
//
// Ver. 8: Draws a simple animation using NSTimer
//
import Cocoa
import OpenGL.GL3
final class SwiftOpenGLView: NSOpenGLView {
private var programID: GLuint = 0
private var vaoID: GLuint = 0
private var vboID: GLuint = 0
private var tboID: GLuint = 0
// The NSTimer for animating.
private var timer = Timer()
required init?(coder: NSCoder) {
super.init(coder: coder)
let attrs: [NSOpenGLPixelFormatAttribute] = [
UInt32(NSOpenGLPFAAccelerated),
UInt32(NSOpenGLPFAColorSize), UInt32(32),
UInt32(NSOpenGLPFAOpenGLProfile), UInt32(NSOpenGLProfileVersion3_2Core),
UInt32(0)
]
guard let pixelFormat = NSOpenGLPixelFormat(attributes: attrs) else {
Swift.print("pixelFormat could not be constructed")
return
}
self.pixelFormat = pixelFormat
guard let context = NSOpenGLContext(format: pixelFormat, share: nil) else {
Swift.print("context could not be constructed")
return
}
self.openGLContext = context
}
override func prepareOpenGL() {
super.prepareOpenGL()
glClearColor(0.0, 0.0, 0.0, 1.0)
programID = glCreateProgram()
//format: x, y, r, g, b, s, t, nx, ny, nz
let data: [GLfloat] = [-1.0, -1.0, 1.0, 0.0, 1.0, 0.0, 2.0, -1.0, -1.0, 0.0001,
0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0001,
1.0, -1.0, 0.0, 0.0, 1.0, 2.0, 2.0, 1.0, -1.0, 0.0001]
let fileURL = Bundle.main.url(forResource: "Texture", withExtension: "png")
let dataProvider = CGDataProvider(url: fileURL! as CFURL)
let image = CGImage(pngDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: false, intent: CGColorRenderingIntent.defaultIntent)
let textureData = UnsafeMutableRawPointer.allocate(bytes: 256 * 4 * 256, alignedTo: MemoryLayout<GLint>.alignment)
let context = CGContext(data: textureData, width: 256, height: 256, bitsPerComponent: 8, bytesPerRow: 4 * 256, space: CGColorSpace(name: CGColorSpace.genericRGBLinear)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
context?.draw(image!, in: CGRect(x: 0.0, y: 0.0, width: 256.0, height: 256.0))
glGenTextures(1, &tboID)
glBindTexture(GLenum(GL_TEXTURE_2D), tboID)
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GL_LINEAR)
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GL_LINEAR)
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), GL_REPEAT)
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), GL_REPEAT)
glTexImage2D(GLenum(GL_TEXTURE_2D), 0, GL_RGBA, 256, 256, 0, GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), textureData)
free(textureData)
glGenBuffers(1, &vboID)
glBindBuffer(GLenum(GL_ARRAY_BUFFER), vboID)
glBufferData(GLenum(GL_ARRAY_BUFFER), data.count * MemoryLayout<GLfloat>.size, data, GLenum(GL_STATIC_DRAW))
glGenVertexArrays(1, &vaoID)
glBindVertexArray(vaoID)
glVertexAttribPointer(0, 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 40, UnsafePointer<GLuint>(bitPattern: 0))
glEnableVertexAttribArray(0)
glVertexAttribPointer(1, 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 40, UnsafePointer<GLuint>(bitPattern: 8))
glEnableVertexAttribArray(1)
glVertexAttribPointer(2, 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 40, UnsafePointer<GLuint>(bitPattern: 20))
glEnableVertexAttribArray(2)
glVertexAttribPointer(3, 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 40, UnsafePointer<GLuint>(bitPattern:28))
glEnableVertexAttribArray(3)
glBindVertexArray(0)
let vs = glCreateShader(GLenum(GL_VERTEX_SHADER))
var source = "#version 330 core \n" +
"layout (location = 0) in vec2 position; \n" +
"layout (location = 1) in vec3 color; \n" +
"layout (location = 2) in vec2 texturePosition; \n" +
"layout (location = 3) in vec3 normal; \n" +
"out vec3 passPosition; \n" +
"out vec3 passColor; \n" +
"out vec2 passTexturePosition; \n" +
"out vec3 passNormal; \n" +
"void main() \n" +
"{ \n" +
" gl_Position = vec4(position, 0.0, 1.0); \n" +
" passPosition = vec3(position, 0.0); \n" +
" passColor = color; \n" +
" passTexturePosition = texturePosition; \n" +
" passNormal = normal; \n" +
"} \n"
let vss = source.cString(using: String.Encoding.ascii)
var vssptr = UnsafePointer<GLchar>(vss)
glShaderSource(vs, 1, &vssptr, nil)
glCompileShader(vs)
var compiled: GLint = 0
glGetShaderiv(vs, GLbitfield(GL_COMPILE_STATUS), &compiled)
if compiled <= 0 {
Swift.print("Could not compile vertex, getting log")
var logLength: GLint = 0
glGetShaderiv(vs, GLenum(GL_INFO_LOG_LENGTH), &logLength)
Swift.print(" logLength = \(logLength)")
if logLength > 0 {
let cLog = UnsafeMutablePointer<GLchar>.allocate(capacity: Int(logLength))
glGetShaderInfoLog(vs, GLsizei(logLength), &logLength, cLog)
Swift.print(" log = \n\t\(String.init(cString: cLog))")
free(cLog)
}
}
let fs = glCreateShader(GLenum(GL_FRAGMENT_SHADER))
source = "#version 330 core \n" +
"uniform sampler2D sample; \n" +
// The Light uniform Struct allows us to more convenietly access the light attributes
"uniform struct Light { \n" +
" vec3 color; \n" +
" vec3 position; \n" +
" float ambient; \n" +
" float specStrength; \n" +
" float specHardness; \n" +
"} light; \n" +
"in vec3 passPosition; \n" +
"in vec3 passColor; \n" +
"in vec2 passTexturePosition; \n" +
"in vec3 passNormal; \n" +
"out vec4 outColor; \n" +
"void main() \n" +
"{ \n" +
" vec3 normal = normalize(passNormal); \n" +
" vec3 lightRay = normalize(light.position - passPosition); \n" +
" float intensity = dot(normal, lightRay); \n" +
" intensity = clamp(intensity, 0, 1); \n" +
// viewer is the vector pointing from the fragment to the viewer
" vec3 viewer = normalize(vec3(0.0, 0.0, 0.2) - passPosition); \n" +
// reflect() calculates the reflection vector
// first parameter is the incident ray
// second parameter is the normal
// we do not negate the lightRay because it is already pointing from the surface to the viewer
// negating the vector would cause the reflection vector to point away from the viewer and no
// highlight would seen.
" vec3 reflection = reflect(lightRay, normal); \n" +
// specular is calculated by taking the dot product of the viewer and reflection vectors,
// ensuring those vectors are >=0.0 with max(), and then raising that value by the value
// of hardness to adjust the hardness of the edge of the highlight.
" float specular = pow(max(dot(viewer, reflection), 0.0), light.specHardness); \n" +
// The specular component casts light so it must also be multiplied by the .color component.
" vec3 light = light.ambient + light.color * intensity + light.specStrength * specular * light.color; \n" +
" vec3 surface = texture(sample, passTexturePosition).rgb * passColor; \n" +
" vec3 rgb = surface * light; \n" +
" outColor = vec4(rgb, 1.0); \n" +
"} \n"
let fss = source.cString(using: String.Encoding.ascii)
var fssptr = UnsafePointer<GLchar>(fss)
glShaderSource(fs, 1, &fssptr, nil)
glCompileShader(fs)
compiled = 0
glGetShaderiv(fs, GLbitfield(GL_COMPILE_STATUS), &compiled)
if compiled <= 0 {
Swift.print("Could not compile fragement, getting log")
var logLength: GLint = 0
glGetShaderiv(fs, GLbitfield(GL_INFO_LOG_LENGTH), &logLength)
Swift.print(" logLength = \(logLength)")
if logLength > 0 {
let cLog = UnsafeMutablePointer<GLchar>.allocate(capacity: Int(logLength))
glGetShaderInfoLog(fs, GLsizei(logLength), &logLength, cLog)
Swift.print(" log = \n\t\(String.init(cString: cLog))")
free(cLog)
}
}
glAttachShader(programID, vs)
glAttachShader(programID, fs)
glLinkProgram(programID)
var linked: GLint = 0
glGetProgramiv(programID, UInt32(GL_LINK_STATUS), &linked)
if linked <= 0 {
Swift.print("Could not link, getting log")
var logLength: GLint = 0
glGetProgramiv(programID, UInt32(GL_INFO_LOG_LENGTH), &logLength)
Swift.print(" logLength = \(logLength)")
if logLength > 0 {
let cLog = UnsafeMutablePointer<GLchar>.allocate(capacity: Int(logLength))
glGetProgramInfoLog(programID, GLsizei(logLength), &logLength, cLog)
Swift.print(" log: \n\t\(String.init(cString: cLog))")
free(cLog)
}
}
glDeleteShader(vs)
glDeleteShader(fs)
let sampleLocation = glGetUniformLocation(programID, "sample")
glUniform1i(sampleLocation, GL_TEXTURE0)
glUseProgram(programID)
// Uniforms for the light struct. Each component is accessed using dot notation.
glUniform3fv(glGetUniformLocation(programID, "light.color"), 1, [1.0, 1.0, 1.0])
glUniform3fv(glGetUniformLocation(programID, "light.position"), 1, [0.0, 1.0, 0.1])
glUniform1f(glGetUniformLocation(programID, "light.ambient"), 0.25)
glUniform1f(glGetUniformLocation(programID, "light.specStrength"), 1.0)
glUniform1f(glGetUniformLocation(programID, "light.specHardness"), 32)
drawView()
// Now that the pipeline is set, we'll start the timer.
// First, tell the context how often to look for a new frame. A value of 1 indicates
// our tartget is 60 frames per second
self.openGLContext?.setValues([1], for: .swapInterval)
// This line may also be placed in init(_:), but it makes more sense to create and add
// it to the loop when were ready to start animating. No sense in wasting computation time.
// Time interval is the time until the timer fires: 0.001 = firing in 1/1000 of a second
// Target is the object that will call a mthod once the timer fires, self indcates this
// method is in SwiftOpenGLView.
// Selector is the method that is to be called when the timer fires. In Swift, a string
// literal of the method name may be passed.
// UserInfo allows you to add additional parameters to the timer that may be retrieved
// for use in the selector
// Repeats indicates if this timer is to fire continuously at the interval specified
// in the timerInterval parameter. true indicates we want to continue firing
self.timer = Timer(timeInterval: 0.001, target: self, selector: #selector(SwiftOpenGLView.redraw), userInfo: nil, repeats: true)
// Once the timer is created, we need to add it to the default run loop and the event
// Essentially the default loop is for general application loop, while the event loop
// is for firing during events like dragging the view around and clicking within the view
RunLoop.current.add(self.timer, forMode: RunLoopMode.defaultRunLoopMode)
RunLoop.current.add(self.timer, forMode: RunLoopMode.eventTrackingRunLoopMode)
}
// The function to be called when the timer fires.
// display() is a function owned by NSView that recalls the lockFocus, drawRect(_:),
// and unlockFocus of the subview and each subview.
// The SwiftOpenGLView.drawRect(_:) calls drawView() as part of it's definition
@objc func redraw() {
self.display()
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
drawView()
}
private func drawView() {
// To make the animation visible, we'll change the background color over time.
// CACurrentMediaTime() returns the amount of time since the app started.
// sin() is applied to this value and then a float value is made from it.
// glClearColor() takes four floats to create an rgba color. We have not activated
// blending, so no matter what value we pass here is ignored.
let value = Float(sin(CACurrentMediaTime()))
glClearColor(value, value, value, 1.0)
glClear(GLbitfield(GL_COLOR_BUFFER_BIT))
glUseProgram(programID)
glBindVertexArray(vaoID)
glDrawArrays(GLenum(GL_TRIANGLES), 0, 3)
glBindVertexArray(0)
glFlush()
}
deinit {
// Stop and the timer and remove it from the run loop.
self.timer.invalidate()
glDeleteVertexArrays(1, &vaoID)
glDeleteBuffers(1, &vboID)
glDeleteProgram(programID)
glDeleteTextures(1, &tboID)
}
}
| 927506c197fd6d82261b50fc609f7db4 | 52.570513 | 235 | 0.506162 | false | false | false | false |
coodly/laughing-adventure | refs/heads/master | Source/UI/UIView+Autolayout.swift | apache-2.0 | 1 | /*
* Copyright 2015 Coodly LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 extension UIView {
public func add(fullSized view: UIView) {
addSubview(view)
let views: [String: AnyObject] = ["view": view]
view.translatesAutoresizingMaskIntoConstraints = false
let vertical = NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options: [], metrics: nil, views: views)
let horizontal = NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: [], metrics: nil, views: views)
addConstraints(vertical + horizontal)
}
public func add(toTop view: UIView, height: CGFloat? = nil) {
addSubview(view)
let views: [String: AnyObject] = ["view": view]
let usedHeight = height ?? view.frame.height
view.translatesAutoresizingMaskIntoConstraints = false
let horizontal = NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: [], metrics: nil, views: views)
let top = NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)
let heightConstraint: NSLayoutConstraint
if usedHeight < 1 {
heightConstraint = NSLayoutConstraint(item: view, attribute: .height, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .height, multiplier: 1, constant: 0)
} else {
heightConstraint = NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: usedHeight)
}
let vertical = [top, heightConstraint]
addConstraints(vertical + horizontal)
}
}
| f3b15c0fb8f6f38ebb8f7a7714f12d57 | 43.627451 | 174 | 0.677944 | false | false | false | false |
googlecreativelab/justaline-ios | refs/heads/master | ViewControllers/PairingChooser.swift | apache-2.0 | 1 | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 UIKit
protocol PairingChooserDelegate {
func shouldBeginPartnerSession ()
}
class PairingChooser: UIViewController {
var delegate: PairingChooserDelegate?
@IBOutlet weak var overlayButton: UIButton!
@IBOutlet weak var buttonContainer: UIView!
@IBOutlet weak var joinButton: UIButton!
@IBOutlet weak var pairButton: UIButton!
@IBOutlet weak var cancelButton: UIButton!
var offscreenContainerPosition: CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
offscreenContainerPosition = buttonContainer.frame.size.height
pairButton.setTitle(NSLocalizedString("draw_with_partner", comment: "Draw with a partner"), for: .normal)
cancelButton.setTitle(NSLocalizedString("cancel", comment: "Cancel"), for: .normal)
print(offscreenContainerPosition)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
buttonContainer.transform = CGAffineTransform.init(translationX: 0, y: offscreenContainerPosition)
UIView.animate(withDuration: 0.25, animations: {
self.buttonContainer.transform = .identity
}) { (success) in
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, self.pairButton)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIView.animate(withDuration: 0.35) {
self.buttonContainer.transform = CGAffineTransform.init(translationX: 0, y: self.offscreenContainerPosition)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func pairButtonTapped(_ sender: UIButton) {
self.dismiss(animated: true, completion: {
self.delegate?.shouldBeginPartnerSession()
})
}
@IBAction func cancelTapped(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
| 2e044bbaac0b56d3c17dfbaa9e357c40 | 35.36 | 120 | 0.69527 | false | false | false | false |
zhangao0086/DKImageBrowserVC | refs/heads/master | DKPhotoGallery/Resource/DKPhotoGalleryResource.swift | mit | 1 | //
// DKPhotoGalleryResource.swift
// DKPhotoGallery
//
// Created by ZhangAo on 15/8/11.
// Copyright (c) 2015年 ZhangAo. All rights reserved.
//
import UIKit
/// Manage all resource files and internationalization support for DKPhotoGallery.
public class DKPhotoGalleryResource {
// MARK: - Internationalization
public class func localizedStringWithKey(_ key: String, value: String? = nil) -> String {
let string = customLocalizationBlock?(key)
return string ?? NSLocalizedString(key, tableName: "DKPhotoGallery",
bundle:Bundle.photoGalleryResourceBundle(),
value: value ?? "",
comment: "")
}
@objc public static var customLocalizationBlock: ((_ title: String) -> String?)?
// MARK: - Images
public class func downloadFailedImage() -> UIImage {
return imageForResource("ImageFailed")
}
public class func closeVideoImage() -> UIImage {
return imageForResource("VideoClose")
}
public class func videoPlayImage() -> UIImage {
return imageForResource("VideoPlay")
}
public class func videoToolbarPlayImage() -> UIImage {
return imageForResource("ToolbarPlay")
}
public class func videoToolbarPauseImage() -> UIImage {
return imageForResource("ToolbarPause")
}
public class func videoPlayControlBackgroundImage() -> UIImage {
return stretchImgFromMiddle(imageForResource("VideoPlayControlBackground"))
}
public class func videoTimeSliderImage() -> UIImage {
return imageForResource("VideoTimeSlider")
}
// MARK: - Private
private class func imageForResource(_ name: String) -> UIImage {
let bundle = Bundle.photoGalleryResourceBundle()
let image = UIImage(named: name, in: bundle, compatibleWith: nil) ?? UIImage()
return image
}
private class func stretchImgFromMiddle(_ image: UIImage) -> UIImage {
let centerX = image.size.width / 2
let centerY = image.size.height / 2
return image.resizableImage(withCapInsets: UIEdgeInsets(top: centerY, left: centerX, bottom: centerY, right: centerX))
}
}
private extension Bundle {
class func photoGalleryResourceBundle() -> Bundle {
let assetPath = Bundle(for: DKPhotoGalleryResource.self).resourcePath!
return Bundle(path: (assetPath as NSString).appendingPathComponent("DKPhotoGallery.bundle"))!
}
}
| 3a08b1161bcbe2600d187db287ef9b9b | 31.061728 | 126 | 0.636504 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/Services/NotificationActionsService.swift | gpl-2.0 | 1 | import Foundation
import CocoaLumberjack
/// This service encapsulates all of the Actions that can be performed with a NotificationBlock
///
class NotificationActionsService: LocalCoreDataService {
/// Follows a Site referenced by a given NotificationBlock.
///
/// - Parameter block: The Notification's Site Block
/// - Parameter completion: Closure block to be executed on completion, indicating if we've succeeded or not.
///
func followSiteWithBlock(_ block: FormattableUserContent, completion: ((Bool) -> Void)? = nil) {
guard let siteID = block.metaSiteID?.uintValue else {
completion?(false)
return
}
siteService.followSite(withID: siteID, success: {
DDLogInfo("Successfully followed site \(siteID)")
self.invalidateCacheAndForceSyncNotification(with: block)
completion?(true)
}, failure: { error in
DDLogError("Error while trying to follow site: \(String(describing: error))")
completion?(false)
})
}
/// Unfollows a Site referenced by a given NotificationBlock.
///
/// - Parameter block: The Notification's Site Block
/// - Parameter completion: Closure block to be executed on completion, indicating if we've succeeded or not.
///
func unfollowSiteWithBlock(_ block: FormattableUserContent, completion: ((Bool) -> Void)? = nil) {
guard let siteID = block.metaSiteID?.uintValue else {
completion?(false)
return
}
siteService.unfollowSite(withID: siteID, success: {
DDLogInfo("Successfully unfollowed site \(siteID)")
self.invalidateCacheAndForceSyncNotification(with: block)
completion?(true)
}, failure: { error in
DDLogError("Error while trying to unfollow site: \(String(describing: error))")
completion?(false)
})
}
/// Replies a comment referenced by a given NotificationBlock.
///
/// - Parameter block: The Notification's Comment Block
/// - Parameter content: The Reply's Content
/// - Parameter completion: Closure block to be executed on completion, indicating if we've succeeded or not.
///
func replyCommentWithBlock(_ block: FormattableCommentContent, content: String, completion: ((Bool) -> Void)? = nil) {
guard let commentID = block.metaCommentID, let siteID = block.metaSiteID else {
completion?(false)
return
}
commentService.replyToComment(withID: commentID, siteID: siteID, content: content, success: {
DDLogInfo("Successfully replied to comment \(siteID).\(commentID)")
self.invalidateCacheAndForceSyncNotification(with: block)
completion?(true)
}, failure: { error in
DDLogError("Error while trying to reply comment: \(String(describing: error))")
completion?(false)
})
}
/// Updates a comment referenced by a given NotificationBlock.
///
/// - Parameter block: The Notification's Comment Block
/// - Parameter content: The Comment's New Content
/// - Parameter completion: Closure block to be executed on completion, indicating if we've succeeded or not.
///
func updateCommentWithBlock(_ block: FormattableCommentContent, content: String, completion: ((Bool) -> Void)? = nil) {
guard let commentID = block.metaCommentID, let siteID = block.metaSiteID else {
completion?(false)
return
}
// Local Override: Temporary hack until the Notification is updated
block.textOverride = content
// Hit the backend
commentService.updateComment(withID: commentID, siteID: siteID, content: content, success: {
DDLogInfo("Successfully updated to comment \(siteID).\(commentID)")
self.invalidateCacheAndForceSyncNotification(with: block)
completion?(true)
}, failure: { error in
DDLogError("Error while trying to update comment: \(String(describing: error))")
completion?(false)
})
}
/// Likes a comment referenced by a given NotificationBlock.
///
/// - Parameter block: The Notification's Comment Block
/// - Parameter completion: Closure block to be executed on completion, indicating if we've succeeded or not.
///
func likeCommentWithBlock(_ block: FormattableCommentContent, completion: ((Bool) -> Void)? = nil) {
guard let commentID = block.metaCommentID, let siteID = block.metaSiteID else {
completion?(false)
return
}
// If the associated comment is *not* approved, let's attempt to auto-approve it, automatically
if block.isCommentApproved == false {
approveCommentWithBlock(block)
}
// Proceed toggling the Like field
commentService.likeComment(withID: commentID, siteID: siteID, success: {
DDLogInfo("Successfully liked comment \(siteID).\(commentID)")
self.invalidateCacheAndForceSyncNotification(with: block)
completion?(true)
}, failure: { error in
DDLogError("Error while trying to like comment: \(String(describing: error))")
completion?(false)
})
}
/// Unlikes a comment referenced by a given NotificationBlock.
///
/// - Parameter block: The Notification's Comment Block
/// - Parameter completion: Closure block to be executed on completion, indicating if we've succeeded or not.
///
func unlikeCommentWithBlock(_ block: FormattableCommentContent, completion: ((Bool) -> Void)? = nil) {
guard let commentID = block.metaCommentID, let siteID = block.metaSiteID else {
completion?(false)
return
}
commentService.unlikeComment(withID: commentID, siteID: siteID, success: {
DDLogInfo("Successfully unliked comment \(siteID).\(commentID)")
self.invalidateCacheAndForceSyncNotification(with: block)
completion?(true)
}, failure: { error in
DDLogError("Error while trying to unlike comment: \(String(describing: error))")
completion?(false)
})
}
/// Approves a comment referenced by a given NotificationBlock.
///
/// - Parameter block: The Notification's Comment Block
/// - Parameter completion: Closure block to be executed on completion, indicating if we've succeeded or not.
///
func approveCommentWithBlock(_ block: FormattableCommentContent, completion: ((Bool) -> Void)? = nil) {
guard let commentID = block.metaCommentID, let siteID = block.metaSiteID else {
completion?(false)
return
}
commentService.approveComment(withID: commentID, siteID: siteID, success: {
DDLogInfo("Successfully approved comment \(siteID).\(commentID)")
self.invalidateCacheAndForceSyncNotification(with: block)
completion?(true)
}, failure: { error in
DDLogError("Error while trying to moderate comment: \(String(describing: error))")
completion?(false)
})
}
/// Unapproves a comment referenced by a given NotificationBlock.
///
/// - Parameter block: The Notification's Comment Block
/// - Parameter completion: Closure block to be executed on completion, indicating if we've succeeded or not.
///
func unapproveCommentWithBlock(_ block: FormattableCommentContent, completion: ((Bool) -> Void)? = nil) {
guard let commentID = block.metaCommentID, let siteID = block.metaSiteID else {
completion?(false)
return
}
commentService.unapproveComment(withID: commentID, siteID: siteID, success: {
DDLogInfo("Successfully unapproved comment \(siteID).\(commentID)")
self.invalidateCacheAndForceSyncNotification(with: block)
completion?(true)
}, failure: { error in
DDLogError("Error while trying to moderate comment: \(String(describing: error))")
completion?(false)
})
}
/// Spams a comment referenced by a given NotificationBlock.
///
/// - Parameter block: The Notification's Comment Block
/// - Parameter completion: Closure block to be executed on completion, indicating if we've succeeded or not.
///
func spamCommentWithBlock(_ block: FormattableCommentContent, completion: ((Bool) -> Void)? = nil) {
guard let commentID = block.metaCommentID, let siteID = block.metaSiteID else {
completion?(false)
return
}
commentService.spamComment(withID: commentID, siteID: siteID, success: {
DDLogInfo("Successfully spammed comment \(siteID).\(commentID)")
self.invalidateCacheAndForceSyncNotification(with: block)
completion?(true)
}, failure: { error in
DDLogError("Error while trying to mark comment as spam: \(String(describing: error))")
completion?(false)
})
}
/// Deletes a comment referenced by a given NotificationBlock.
///
/// - Parameter block: The Notification's Comment Block
/// - Parameter completion: Closure block to be executed on completion, indicating if we've succeeded or not.
///
func deleteCommentWithBlock(_ block: FormattableCommentContent, completion: ((Bool) -> Void)? = nil) {
guard let commentID = block.metaCommentID, let siteID = block.metaSiteID else {
completion?(false)
return
}
commentService.deleteComment(withID: commentID, siteID: siteID, success: {
DDLogInfo("Successfully deleted comment \(siteID).\(commentID)")
self.invalidateCacheAndForceSyncNotification(with: block)
completion?(true)
}, failure: { error in
DDLogError("Error while trying to delete comment: \(String(describing: error))")
completion?(false)
})
}
}
// MARK: - Private Helpers
//
private extension NotificationActionsService {
/// Invalidates the Local Cache for a given Notification, and re-downloaded from the remote endpoint.
/// We're doing *both actions* so that in the eventual case of "Broken REST Request", the notification's hash won't match
/// with the remote value, and the note will be redownloaded upon Sync.
///
/// Required due to a beautiful backend bug. Details here: https://github.com/wordpress-mobile/WordPress-iOS/pull/6871
///
/// - Parameter block: child NotificationBlock object of the Notification-to-be-refreshed.
///
func invalidateCacheAndForceSyncNotification(with block: NotificationTextContent) {
guard let mediator = NotificationSyncMediator() else {
return
}
let notificationID = block.parent.notificationIdentifier
DDLogInfo("Invalidating Cache and Force Sync'ing Notification with ID: \(notificationID)")
mediator.invalidateCacheForNotification(with: notificationID)
mediator.syncNote(with: notificationID)
}
}
// MARK: - Computed Properties
//
private extension NotificationActionsService {
var commentService: CommentService {
return CommentService(managedObjectContext: managedObjectContext)
}
var siteService: ReaderSiteService {
return ReaderSiteService(managedObjectContext: managedObjectContext)
}
}
| 52f24f455c327247de13fe062493ed3e | 38.930796 | 125 | 0.65182 | false | false | false | false |
EasySwift/EasySwift | refs/heads/master | EasySwift_iOS/Core/EZNavigationController.swift | apache-2.0 | 2 | //
// EZNavigationController.swift
// medical
//
// Created by zhuchao on 15/4/24.
// Copyright (c) 2015年 zhuchao. All rights reserved.
//
import UIKit
open class EZNavigationController: UINavigationController, UINavigationControllerDelegate, UIGestureRecognizerDelegate {
open var popGestureRecognizerEnabled = true
override open func viewDidLoad() {
super.viewDidLoad()
self.configGestureRecognizer()
// Do any additional setup after loading the view.
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
open func configGestureRecognizer() {
if let target = self.interactivePopGestureRecognizer?.delegate {
let pan = UIPanGestureRecognizer(target: target, action: Selector(("handleNavigationTransition:")))
pan.delegate = self
self.view.addGestureRecognizer(pan)
}
// 禁掉系统的侧滑手势
weak var weekSelf = self
self.interactivePopGestureRecognizer?.isEnabled = false;
self.interactivePopGestureRecognizer?.delegate = weekSelf;
}
open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer != self.interactivePopGestureRecognizer && self.viewControllers.count > 1 && self.popGestureRecognizerEnabled {
return true
} else {
return false
}
}
override open func pushViewController(_ viewController: UIViewController, animated: Bool) {
self.interactivePopGestureRecognizer?.isEnabled = false
super.pushViewController(viewController, animated: animated)
}
// UINavigationControllerDelegate
open func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
if self.popGestureRecognizerEnabled {
self.interactivePopGestureRecognizer?.isEnabled = true
}
}
}
| 91c1db5b908ce0874cd37c322a08a840 | 34.701754 | 142 | 0.70172 | false | false | false | false |
StephenZhuang/Gongyinglian | refs/heads/master | Gongyinglian/Gongyinglian/ListViewController.swift | mit | 1 | //
// ListViewController.swift
// Gongyinglian
//
// Created by Stephen Zhuang on 14-7-3.
// Copyright (c) 2014年 udows. All rights reserved.
//
import UIKit
class ListViewController: UITableViewController {
var dataArray: NSMutableArray?
init(style: UITableViewStyle) {
super.init(style: style)
// Custom initialization
}
init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController.setNavigationBarHidden(false, animated: true)
self.addTitleView(title: "库存", subtitle: "库存查询")
self.dataArray = NSMutableArray()
self.refreshControl.addTarget(self, action: Selector("refreshControlValueChanged"), forControlEvents: .ValueChanged)
self.refreshControl!.beginRefreshing()
loadData()
}
func refreshControlValueChanged() {
if self.refreshControl.refreshing {
loadData()
}
}
func loadData() {
var params: NSMutableDictionary = NSMutableDictionary()
var dic: NSMutableDictionary = NSMutableDictionary()
dic.setObject("com.shqj.webservice.entity.UserKey", forKey: "class")
dic.setObject(ToolUtils.shareInstance().user!.key, forKey: "key")
let jsonString: NSString = dic.JSONString()
params.setObject(jsonString, forKey: "userkey")
var webservice: WebServiceRead = WebServiceRead()
webservice = WebServiceRead(self , selecter:Selector("webServiceFinished:"))
webservice.postWithMethodName("doQueryKc", params: params)
}
func webServiceFinished(data: NSString) {
var dic: NSDictionary = data.objectFromJSONString() as NSDictionary
var kcList: QueryKcList = QueryKcList()
kcList.build(dic)
self.dataArray!.removeAllObjects()
self.dataArray!.addObjectsFromArray(kcList.data)
self.tableView!.reloadData()
if self.refreshControl.refreshing {
self.refreshControl.endRefreshing()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #pragma mark - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return self.dataArray!.count
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
let cell : GoodsCell! = tableView!.dequeueReusableCellWithIdentifier("cell") as GoodsCell
// Configure the cell...
var querykc:QueryKc = self.dataArray!.objectAtIndex(indexPath!.row) as QueryKc
cell.nameLabel.text = querykc.spname?
cell.codeLabel.text = querykc.spcode?
cell.countLabel.text = querykc.spcount?.stringValue
return cell
}
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
tableView!.deselectRowAtIndexPath(indexPath , animated:true)
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView?, canEditRowAtIndexPath indexPath: NSIndexPath?) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView?, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath?) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView?, moveRowAtIndexPath fromIndexPath: NSIndexPath?, toIndexPath: NSIndexPath?) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView?, canMoveRowAtIndexPath indexPath: NSIndexPath?) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// #pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| 0929762e1ebd9fae1f16c5c8d15c5970 | 34.619048 | 159 | 0.671314 | false | false | false | false |
martinomamic/CarBooking | refs/heads/master | CarBooking/Services/Booking/BookingService.swift | mit | 1 | //
// BookingService.swift
// CarBooking
//
// Created by Martino Mamic on 29/07/2017.
// Copyright © 2017 Martino Mamic. All rights reserved.
//
import UIKit
import Foundation
class BookingService: BookingsStoreProtocol {
private let service = WebService()
func createBooking(newBooking: Booking, completionHandler: @escaping (() throws -> Booking?) -> Void) {
var json = RequestDictionary()
json["carId"] = "\(newBooking.car.id)"
json["startDate"] = newBooking.startDate.fullDateFormat()
json["endDate"] = newBooking.endDate.fullDateFormat()
json["isExpired"] = "\(false)"
json["duration"] = "\(newBooking.duration)"
service.create(params: json, resource: BookingResources.newBooking) { (createdBooking, error, response) in
if let booking = createdBooking {
completionHandler { return booking }
} else {
print(error ?? "no error")
print(response ?? "no response")
}
}
}
func fetchBookings(completionHandler: @escaping (() throws -> [Booking]) -> Void) {
service.get(resource: BookingResources.allBookings) { (bookingsArray, error, response) in
if let bookings = bookingsArray {
print(bookings)
for b in bookings {
print(b)
}
completionHandler { return bookings }
}
}
}
func fetchBooking(id: String, completionHandler: @escaping (() throws -> Booking?) -> Void) {
service.get(resource: BookingResources.fetchBooking(id)) { (fetchedBooking, error, response) in
if let booking = fetchedBooking {
print(booking)
completionHandler { return booking }
} else {
print(error ?? "no error")
print(response ?? "no response")
}
}
}
}
| 2921f39f178d3f2b93287ded1bb6152a | 35.111111 | 114 | 0.573846 | false | false | false | false |
kaphacius/Localize | refs/heads/master | GooglePlayParser_temp.swift | mit | 1 | #!/usr/bin/swift
import Foundation
enum Platform {
case Android, iOS
}
func parseOutputPlatformName(input: String) -> Platform? {
let platform: Platform?
switch input {
case "android":
platform = .Android
case "ios":
platform = .iOS
default:
platform = nil
}
return platform
}
func parseForPlatformName(input: String) -> [Platform] {
let platform: [Platform]
switch input {
case "android":
platform = [.Android]
case "ios":
platform = [.iOS]
case "not used":
platform = []
default:
platform = [.Android, .iOS]
}
return platform
}
dump(CommandLine.arguments)
let platformP = CommandLine.arguments[1]
let platform = parseOutputPlatformName(input: platformP) ?? .iOS
let fileP = CommandLine.arguments[2]
let path = NSURL(fileURLWithPath: fileP)
let data = NSData(contentsOf: path as URL)
let strings = String(data: data! as Data, encoding: String.Encoding.utf8)
let lines = strings!.components(separatedBy: "\n")
var splitted = lines.map { (string: String) -> [String] in
return string.trimmingCharacters(in: CharacterSet.newlines).components(separatedBy: "\t")
}
var firstRow = splitted.removeFirst()
firstRow.removeFirst() // "PLATFORM"
firstRow.removeFirst() // "KEY"
//Split by language
for line in splitted {
let forPlatform = parseForPlatformName(input: line[0])
let key = line[1]
for i in 2..<line.count {
let langIndex = i - 2
if key.hasPrefix("//") {
//Ignore
} else if line[i] != "" && (forPlatform.contains(platform)) {
let fileName = key.replacingOccurrences(of: "google_play_", with: "")
let langCode = firstRow[langIndex]
let regionCode: String?
switch langCode {
case "en": regionCode = "GB"
case "nl": regionCode = "NL"
case "de": regionCode = "DE"
case "fr": regionCode = "FR"
default: regionCode = nil
}
if let rc = regionCode {
let dirPath = path.deletingLastPathComponent?
.appendingPathComponent("fastlane")
.appendingPathComponent("metadata")
.appendingPathComponent("android")
.appendingPathComponent(langCode + "-" + rc)
try! FileManager.default.createDirectory(at: dirPath!, withIntermediateDirectories: true, attributes: nil)
let currentFilePath = dirPath!.appendingPathComponent(fileName + ".txt")
let value = line[i].replacingOccurrences(of: "\\n", with: "\n")
try! value.data(using: String.Encoding.utf8)?.write(to: currentFilePath, options: [])
print(currentFilePath)
}
}
}
}
| e086d1691be5e245cd81260c725a529c | 31.136364 | 122 | 0.598656 | false | false | false | false |
Sergtsaeb/twitter-client | refs/heads/master | TwitterClient/HomeTimelineViewController.swift | mit | 1 | //
// HomeTimelineViewController.swift
// TwitterClient
//
// Created by Sergelenbaatar Tsogtbaatar on 3/20/17.
// Copyright © 2017 Serg Tsogtbaatar. All rights reserved.
//
import UIKit
import Foundation
import FoldingCell
class HomeTimelineViewController: UIViewController,UINavigationControllerDelegate {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var tableView: UITableView!
var cellHeights = (100..<280).map { _ in C.CellHeight.close }
var allTweets = [Tweet]() {
didSet {
self.tableView.reloadData()
}
}
var userProfile: User?
fileprivate struct C {
struct CellHeight {
static let close: CGFloat = 100 // equal or greater foregroundView height
static let open: CGFloat = 280 // equal or greater containerView height
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self
self.tableView.delegate = self
self.navigationController?.delegate = self
let tweetNib = UINib(nibName: "MyFoldingCell", bundle: Bundle.main)
self.tableView.register(tweetNib, forCellReuseIdentifier: MyFoldingCell.identifier)
self.navigationItem.title = "My Timeline"
self.tableView.estimatedRowHeight = 100
self.tableView.rowHeight = UITableViewAutomaticDimension
setUpNavigationBarItems()
updateTimeline()
}
private func setUpNavigationBarItems() {
setUpTitleImage()
setUpProfileButton()
navigationController?.navigationBar.backgroundColor = .white
navigationController?.navigationBar.isTranslucent = false
}
private func setUpTitleImage() {
let titleImageView = UIImageView(image: #imageLiteral(resourceName: "title_icon"))
navigationItem.titleView = titleImageView
titleImageView.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
titleImageView.contentMode = .scaleAspectFit
}
func test() {
performSegue(withIdentifier: ProfileViewController.identifier, sender: nil)
}
private func setUpProfileButton() {
let profileButton = UIButton(type: .system)
profileButton.addTarget(self, action: #selector(HomeTimelineViewController.test), for: .touchUpInside)
profileButton.setImage(#imageLiteral(resourceName: "meIcon").withRenderingMode(.alwaysOriginal), for: .normal)
profileButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: profileButton)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if segue.identifier == TweetDetailViewController.identifier {
if let selectedIndex = self.tableView.indexPathForSelectedRow?.row {
let selectedTweet = self.allTweets[selectedIndex]
guard let destinationController = segue.destination as? TweetDetailViewController else { return }
destinationController.tweet = selectedTweet
}
}
if segue.identifier == ProfileViewController.identifier {
guard let destinationController = segue.destination as? ProfileViewController else { return }
API.shared.getUserInfo(callback: { (user) in
destinationController.user = user
})
}
}
func updateTimeline() {
self.activityIndicator.startAnimating()
API.shared.getTweets { (tweets) in
OperationQueue.main.addOperation {
self.allTweets = tweets ?? []
self.activityIndicator.stopAnimating()
}
}
// Creates a serial queue
OperationQueue.main.maxConcurrentOperationCount = 1
}
}
//MARK: MyFoldingCellDelegate
extension HomeTimelineViewController: MyFoldingCellDelegate {
func didTapMoreDetail(_ sender: Any?) {
performSegue(withIdentifier: TweetDetailViewController.identifier, sender: sender)
}
}
//MARK: UITableViewDelegate
extension HomeTimelineViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return cellHeights[indexPath.row]
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if let cell = cell as? MyFoldingCell {
if cellHeights[indexPath.row] == C.CellHeight.close {
cell.selectedAnimation(false, animated: false, completion: nil)
} else {
cell.selectedAnimation(true, animated: false, completion: nil)
}
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? MyFoldingCell else {
return
}
var duration = 0.0
if cellHeights[indexPath.row] == 100 {
cellHeights[indexPath.row] = 280
cell.selectedAnimation(true, animated: true, completion: nil)
duration = 0.5
} else {
// close
cellHeights[indexPath.row] = 100
cell.selectedAnimation(false, animated: true, completion: nil)
duration = 0.8
}
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
tableView.beginUpdates()
tableView.endUpdates()
}, completion: nil)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allTweets.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MyFoldingCell.identifier, for: indexPath) as! MyFoldingCell
cell.delegate = self
let tweet = self.allTweets[indexPath.row]
cell.tweet = tweet
cell.backViewColor = UIColor(red: 181/255, green: 180/255, blue: 193/255, alpha: 0.7)
return cell
}
}
| 4cfb3332221bc4618bda3321ba66b0eb | 34.274725 | 124 | 0.639408 | false | false | false | false |
cplaverty/KeitaiWaniKani | refs/heads/master | AlliCrab/ApplicationSettings.swift | mit | 1 | //
// ApplicationSettings.swift
// AlliCrab
//
// Copyright © 2017 Chris Laverty. All rights reserved.
//
import WaniKaniKit
enum ApplicationSettingKey: String {
case apiKey = "apiKeyV2"
case notificationStrategy = "notificationStrategy"
case purgeDatabase = "purgeDatabase"
case purgeCaches = "purgeCaches"
case disableLessonSwipe = "disableLessonSwipe"
case userScriptCloseButNoCigarEnabled = "userScript-CloseButNoCigar"
case userScriptJitaiEnabled = "userScript-Jitai"
case userScriptIgnoreAnswerEnabled = "userScript-IgnoreAnswer"
case userScriptShowSRSReviewLevel = "userScript-ShowSRSLevel"
case userScriptDoubleCheckEnabled = "userScript-DoubleCheck"
case userScriptWaniKaniImproveEnabled = "userScript-WaniKaniImprove"
case userScriptReorderUltimateEnabled = "userScript-ReorderUltimate"
case reviewTimelineFilterType = "reviewTimelineFilterType"
case reviewTimelineValueType = "reviewTimelineValueType"
}
extension UIColor {
class var globalTintColor: UIColor {
return UIColor(named: "Colours/GlobalTint")!
}
class var globalBarTintColor: UIColor {
return UIColor(named: "Colours/GlobalBarTint")!
}
}
struct ApplicationSettings {
static var userDefaults: UserDefaults {
return UserDefaults.standard
}
static var apiKey: String? {
get { return userDefaults.string(forKey: .apiKey) }
set { userDefaults.set(newValue, forKey: .apiKey) }
}
static var notificationStrategy: NotificationStrategy {
get { return userDefaults.rawValue(NotificationStrategy.self, forKey: .notificationStrategy) ?? .firstReviewSession }
set { userDefaults.set(newValue, forKey: .notificationStrategy) }
}
static var purgeDatabase: Bool {
get { return userDefaults.bool(forKey: .purgeDatabase) }
set { userDefaults.set(newValue, forKey: .purgeDatabase) }
}
static var purgeCaches: Bool {
get { return userDefaults.bool(forKey: .purgeCaches) }
set { userDefaults.set(newValue, forKey: .purgeCaches) }
}
static var disableLessonSwipe: Bool {
get { return userDefaults.bool(forKey: .disableLessonSwipe) }
set { userDefaults.set(newValue, forKey: .disableLessonSwipe) }
}
static var userScriptCloseButNoCigarEnabled: Bool {
get { return userDefaults.bool(forKey: .userScriptCloseButNoCigarEnabled) }
set { userDefaults.set(newValue, forKey: .userScriptCloseButNoCigarEnabled) }
}
static var userScriptJitaiEnabled: Bool {
get { return userDefaults.bool(forKey: .userScriptJitaiEnabled) }
set { userDefaults.set(newValue, forKey: .userScriptJitaiEnabled) }
}
static var userScriptIgnoreAnswerEnabled: Bool {
get { return userDefaults.bool(forKey: .userScriptIgnoreAnswerEnabled) }
set { userDefaults.set(newValue, forKey: .userScriptIgnoreAnswerEnabled) }
}
static var userScriptShowSRSReviewLevel: Bool {
get { return userDefaults.bool(forKey: .userScriptShowSRSReviewLevel) }
set { userDefaults.set(newValue, forKey: .userScriptShowSRSReviewLevel) }
}
static var userScriptDoubleCheckEnabled: Bool {
get { return userDefaults.bool(forKey: .userScriptDoubleCheckEnabled) }
set { userDefaults.set(newValue, forKey: .userScriptDoubleCheckEnabled) }
}
static var userScriptWaniKaniImproveEnabled: Bool {
get { return userDefaults.bool(forKey: .userScriptWaniKaniImproveEnabled) }
set { userDefaults.set(newValue, forKey: .userScriptWaniKaniImproveEnabled) }
}
static var userScriptReorderUltimateEnabled: Bool {
get { return userDefaults.bool(forKey: .userScriptReorderUltimateEnabled) }
set { userDefaults.set(newValue, forKey: .userScriptReorderUltimateEnabled) }
}
static var reviewTimelineFilterType: ReviewTimelineFilter {
get { return userDefaults.rawValue(ReviewTimelineFilter.self, forKey: .reviewTimelineFilterType) ?? .none }
set { userDefaults.set(newValue, forKey: .reviewTimelineFilterType) }
}
static var reviewTimelineValueType: ReviewTimelineCountMethod {
get { return userDefaults.rawValue(ReviewTimelineCountMethod.self, forKey: .reviewTimelineValueType) ?? .histogram }
set { userDefaults.set(newValue, forKey: .reviewTimelineValueType) }
}
static func resetToDefaults() {
apiKey = nil
notificationStrategy = .firstReviewSession
purgeDatabase = false
purgeCaches = false
disableLessonSwipe = false
userScriptCloseButNoCigarEnabled = false
userScriptJitaiEnabled = false
userScriptIgnoreAnswerEnabled = false
userScriptShowSRSReviewLevel = false
userScriptDoubleCheckEnabled = false
userScriptWaniKaniImproveEnabled = false
userScriptReorderUltimateEnabled = false
reviewTimelineFilterType = .none
reviewTimelineValueType = .histogram
}
}
extension UserDefaults {
func set(_ value: Any?, forKey defaultName: ApplicationSettingKey) {
set(value, forKey: defaultName.rawValue)
}
func set(_ value: Int, forKey defaultName: ApplicationSettingKey) {
set(value, forKey: defaultName.rawValue)
}
func set(_ value: Float, forKey defaultName: ApplicationSettingKey) {
set(value, forKey: defaultName.rawValue)
}
func set(_ value: Double, forKey defaultName: ApplicationSettingKey) {
set(value, forKey: defaultName.rawValue)
}
func set(_ value: Bool, forKey defaultName: ApplicationSettingKey) {
set(value, forKey: defaultName.rawValue)
}
func set(_ url: URL?, forKey defaultName: ApplicationSettingKey) {
set(url, forKey: defaultName.rawValue)
}
func set<T: RawRepresentable>(_ value: T?, forKey defaultName: ApplicationSettingKey) {
set(value?.rawValue, forKey: defaultName.rawValue)
}
func object(forKey defaultName: ApplicationSettingKey) -> Any? {
return object(forKey: defaultName.rawValue)
}
func string(forKey defaultName: ApplicationSettingKey) -> String? {
return string(forKey: defaultName.rawValue)
}
func bool(forKey defaultName: ApplicationSettingKey) -> Bool {
return bool(forKey: defaultName.rawValue)
}
func rawValue<T: RawRepresentable>(_ type: T.Type, forKey defaultName: ApplicationSettingKey) -> T? {
guard let rawValue = object(forKey: defaultName) as? T.RawValue else {
return nil
}
return type.init(rawValue: rawValue)
}
}
| b9d61921464de4df30d24330a53676ae | 37.016949 | 125 | 0.699658 | false | false | false | false |
naocanfen/CDNY | refs/heads/master | cdny/cdny/Tools/UserDefaultsTools.swift | mit | 1 | //
// UserDefaultsTools.swift
// ChengDuNongYe
//
// Created by MAC_HANMO on 2017/7/19.
// Copyright © 2017年 MAC_HANMO. All rights reserved.
//
import UIKit
// 本地文件
class UserDefaultsTools{
// 保存,或修改
class func saveInfo(_ name:String,_ key:String)
{
if (0 <= name.characters.count)
{
let userDefault = UserDefaults.standard
userDefault.set(name, forKey: key)
userDefault.synchronize()
// let alert = UIAlertView(title: "温馨提示", message: "保存成功", delegate: nil, cancelButtonTitle: "知道了")
// alert.show()
}
}
// 读取
class func readInfo(_ key:String) -> String
{
let userDefault = UserDefaults.standard
let name = userDefault.object(forKey: key) as? String
if (name != nil)
{
return name!
}
return "-1"
}
}
| 09cb029681e4e6d9717da82e44afb5a8 | 21.725 | 110 | 0.546755 | false | false | false | false |
KrishMunot/swift | refs/heads/master | test/attr/attr_specialize.swift | apache-2.0 | 5 | // RUN: %target-parse-verify-swift
// RUN: %target-swift-ide-test -print-ast-typechecked -source-filename=%s -disable-objc-attr-requires-foundation-module | FileCheck %s
struct S<T> {}
// Specialize freestanding functions with the correct number of concrete types.
// ----------------------------------------------------------------------------
// CHECK: @_specialize(Int)
@_specialize(Int)
// CHECK: @_specialize(S<Int>)
@_specialize(S<Int>)
@_specialize(Int, Int) // expected-error{{generic type 'oneGenericParam' specialized with too many type parameters (got 2, but expected 1)}},
@_specialize(T) // expected-error{{use of undeclared type 'T'}}
public func oneGenericParam<T>(_ t: T) -> T {
return t
}
// CHECK: @_specialize(Int, Int)
@_specialize(Int, Int)
@_specialize(Int) // expected-error{{generic type 'twoGenericParams' specialized with too few type parameters (got 1, but expected 2)}},
public func twoGenericParams<T, U>(_ t: T, u: U) -> (T, U) {
return (t, u)
}
// Specialize contextual types.
// ----------------------------
class G<T> {
// CHECK: @_specialize(Int)
@_specialize(Int)
@_specialize(T) // expected-error{{cannot partially specialize a generic function}}
@_specialize(S<T>) // expected-error{{cannot partially specialize a generic function}}
@_specialize(Int, Int) // expected-error{{generic type 'noGenericParams' specialized with too many type parameters (got 2, but expected 1)}}
func noGenericParams() {}
// CHECK: @_specialize(Int, Float)
@_specialize(Int, Float)
// CHECK: @_specialize(Int, S<Int>)
@_specialize(Int, S<Int>)
@_specialize(Int) // expected-error{{generic type 'oneGenericParam' specialized with too few type parameters (got 1, but expected 2)}},
func oneGenericParam<U>(_ t: T, u: U) -> (U, T) {
return (u, t)
}
}
// Specialize with requirements.
// -----------------------------
protocol Thing {}
struct AThing : Thing {}
// CHECK: @_specialize(AThing)
@_specialize(AThing)
@_specialize(Int) // expected-error{{argument type 'Int' does not conform to expected type 'Thing'}}
func oneRequirement<T : Thing>(_ t: T) {}
protocol HasElt {
associatedtype Element
}
struct IntElement : HasElt {
typealias Element = Int
}
struct FloatElement : HasElt {
typealias Element = Float
}
@_specialize(FloatElement)
@_specialize(IntElement) // expected-error{{'<T : HasElt where T.Element == Float> (T) -> ()' (aka '<T : HasElt where T.Element == Float> T -> ()') requires the types 'Element' (aka 'Int') and 'Float' be equivalent}}
func sameTypeRequirement<T : HasElt where T.Element == Float>(_ t: T) {}
class Base {}
class Sub : Base {}
class NonSub {}
@_specialize(Sub)
@_specialize(NonSub) // expected-error{{'<T : Base> (T) -> ()' (aka '<T : Base> T -> ()') requires that 'NonSub' inherit from 'Base'}}
func superTypeRequirement<T : Base>(_ t: T) {}
| b6117f1b7fbfbeb6f7ec13977a3b1659 | 35.935065 | 216 | 0.650492 | false | false | false | false |
tectijuana/patrones | refs/heads/master | Bloque1SwiftArchivado/PracticasSwift/Omar-Villegas/Ejercicios-Libro/Ejercicio73-5.swift | gpl-3.0 | 1 | /*
Created by Omar Villegas on 09/02/17.
Copyright © 2017 Omar Villegas. All rights reserved.
Materia: Patrones de Diseño
Alumno: Villegas Castillo Omar
No. de control: 13211106
Ejercicios del PDF "Problemas para Resolver por Computadora 1993"
PROBLEMA 73 CAPITULO 5
Determinar los arreglos posibles de una familia de seis miembros : papá , mamá, Tomás,
Guillermo , Nancy y Ruth en una mesa para ocho personas.
*/
import Foundation
var sillas = 8
var miembros = 6
var resultado = 1
//SIGUIENDO LA FÓRMULA DE PERMUTACIONES SIN REPETICIÓN DE n ELEMENTOS TOMADOS DE r EN r
// 8*7*6*5*4*3 CICLO FOR
for i in 3...8
{
var multiplicacion = i
resultado = resultado * multiplicacion
}
//IMPRIMIR RESULTADO
print ("\(resultado) diferentes maneras")
| 12cd7e7a243236e2afb608e90790e441 | 21.794118 | 87 | 0.731613 | false | false | false | false |
BasThomas/DPI | refs/heads/master | code/DPI/ViewController.swift | mit | 1 | //
// ViewController.swift
// DPI
//
// Created by Bas Broek on 5/26/16.
// Copyright © 2016 Bas Broek. All rights reserved.
//
import UIKit
public var allUsers: [User] = []
private let printer = Printer()
class ViewController: UIViewController {
@IBOutlet weak var notificationPicker: UIPickerView! {
didSet {
notificationPicker.selectRow(2, inComponent: 0, animated: true)
}
}
@IBOutlet weak var notificationMessage: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension ViewController {
@IBAction func send(sender: AnyObject) {
guard let message = notificationMessage.text else { return }
let topic = Topic.cases[notificationPicker.selectedRowInComponent(0)]
printer.send(notification: Notification(topic: topic, message: message))
notificationMessage.text = ""
}
}
extension ViewController: UIPickerViewDataSource {
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return Topic.cases.count
}
}
extension ViewController: UIPickerViewDelegate {
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return Topic.cases[row].rawValue
}
}
| 2f581987475e4bf15cc293f7d12e7aa4 | 23.4 | 107 | 0.718331 | false | false | false | false |
michikono/swift-using-typealiases-as-generics | refs/heads/master | swift-using-typealiases-as-generics-i.playground/Pages/typealias-for-self 1.xcplaygroundpage/Contents.swift | mit | 2 | //: Typealias for Self - Unintended Types
//: =======================================
//: [Previous](@previous)
protocol Material {}
struct Wood: Material {}
struct Glass: Material {}
struct Metal: Material {}
struct Cotton: Material {}
protocol HouseholdThing { }
protocol Furniture: HouseholdThing {
typealias M: Material
typealias M2: Material
typealias T: HouseholdThing
func mainMaterial() -> M
func secondaryMaterial() -> M2
static func factory() -> T
}
struct Chair: Furniture {
func mainMaterial() -> Wood {
return Wood()
}
func secondaryMaterial() -> Cotton {
return Cotton()
}
static func factory() -> Chair {
return Chair()
}
}
//: Notice the unintended return type of `factory()`
struct Lamp: Furniture {
func mainMaterial() -> Glass {
return Glass()
}
func secondaryMaterial() -> Metal {
return Metal()
}
static func factory() -> Chair {
return Chair() // <== this is not what we intended!
}
}
//: [Next](@next)
| 43f92edba26d297152ad63bb1db8c0ba | 20.571429 | 59 | 0.589404 | false | false | false | false |
openbuild-sheffield/jolt | refs/heads/master | Sources/OpenbuildExtensionPerfect/struct.RequestValidationTypeString.swift | gpl-2.0 | 1 | import Foundation
import OpenbuildExtensionCore
public struct RequestValidationTypeString: RequestValidationString {
public var min: Int?
public var max: Int?
public var regex: String?
public var email: Bool?
public var isString: String?
public init(){} //Used for validating something exists...
public init(isString: String){
self.isString = isString
}
public init(email: Bool){
self.email = email
}
public init(min: Int, max: Int){
self.min = min
self.max = max
}
public init(regex: String){
self.regex = regex
}
public init(min: Int, max: Int, regex: String){
self.min = min
self.max = max
self.regex = regex
}
public func validate(value: Any?, required: Bool) -> [String: Any] {
var errors: [String: Any] = [:]
if value == nil && required {
errors["required"] = "Is a required value."
}
if value != nil {
var isString = false
var realString: String? = nil
if let stringValue = value! as? String {
isString = true
realString = stringValue
}
if isString {
if self.min != nil && realString!.characters.count < self.min! {
errors["min"] = "Should be equal to \(self.min!) characters or higher."
}
if self.max != nil && realString!.characters.count > self.max! {
errors["max"] = "Should be equal to \(self.max!) characters or lower."
}
if self.regex != nil && (realString! !=~ self.regex!) {
errors["regex"] = "Should match \(self.regex!)."
}
if self.email != nil && self.email! == true {
if realString!.isEmail == false {
errors["email"] = "Should be a valid email address."
}
}
if self.isString != nil && (realString! != self.isString!) {
errors["match"] = "Should be equal to '\(self.isString!)'"
}
} else {
errors["is_string"] = "Should be a string."
}
}
return errors
}
public func cast(value: Any?) -> String?{
if value == nil {
return nil
}
if let stringValue = value! as? String {
if self.email != nil && self.email! == true {
return stringValue.lowercased()
} else {
return stringValue
}
}
return nil
}
public func describeRAML() -> [String] {
var description = [String]()
//FIXME / TODO ? email is not a valid type but....
if self.email != nil && self.email! {
description.append("type: email")
} else {
description.append("type: string")
}
if self.min != nil {
description.append("minLength: \(self.min!)")
}
if self.max != nil {
description.append("maxLength: \(self.max!)")
}
if self.regex != nil {
description.append("pattern: \(self.regex!)")
}
return description
}
} | 60fd0ef660d6970a8886461ff8b9e8e7 | 23.430657 | 91 | 0.485953 | false | false | false | false |
soapyigu/LeetCode_Swift | refs/heads/master | String/AddStrings.swift | mit | 1 | /**
* Question Link: https://leetcode.com/problems/add-strings/
* Primary idea: reverse two strings and add them using sum && carry idea
*
* Note: do not forget to reverse afterwards
*
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class AddStrings {
func addStrings(_ num1: String, _ num2: String) -> String {
let num1Chars = Array(num1.characters.reversed())
let num2Chars = Array(num2.characters.reversed())
var i = 0, j = 0, sum = 0, carry = 0
var res = ""
while i < num1Chars.count || j < num2Chars.count || carry != 0 {
sum = carry
if i < num1Chars.count {
sum += Int(String(num1Chars[i]))!
i += 1
}
if j < num2Chars.count {
sum += Int(String(num2Chars[j]))!
j += 1
}
carry = sum / 10
sum = sum % 10
res.append(String(sum))
}
return String(res.characters.reversed())
}
} | a90a1bb9cd74fa5b2d6b420f9856398e | 27.263158 | 73 | 0.48835 | false | false | false | false |
gowansg/firefox-ios | refs/heads/master | ClientTests/MockProfile.swift | mpl-2.0 | 1 | /* 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 Account
import ReadingList
import Shared
import Storage
import Sync
import XCTest
public class MockProfile: Profile {
private let name: String = "mockaccount"
func localName() -> String {
return name
}
lazy var db: BrowserDB = {
return BrowserDB(files: self.files)
} ()
lazy var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> = {
// Eventually this will be a SyncingBookmarksModel or an OfflineBookmarksModel, perhaps.
return BookmarksSqliteFactory(db: self.db)
} ()
lazy var searchEngines: SearchEngines = {
return SearchEngines(prefs: self.prefs)
} ()
lazy var prefs: Prefs = {
return MockProfilePrefs()
} ()
lazy var files: FileAccessor = {
return ProfileFileAccessor(profile: self)
} ()
lazy var favicons: Favicons = {
return SQLiteFavicons(db: self.db)
}()
lazy var history: BrowserHistory = {
return SQLiteHistory(db: self.db)
}()
lazy var readingList: ReadingListService? = {
return ReadingListService(profileStoragePath: self.files.rootPath)
}()
private lazy var remoteClientsAndTabs: RemoteClientsAndTabs = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
lazy var passwords: Passwords = {
return MockPasswords(files: self.files)
}()
lazy var thumbnails: Thumbnails = {
return SDWebThumbnails(files: self.files)
}()
let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration()
var account: FirefoxAccount? = nil
func getAccount() -> FirefoxAccount? {
return account
}
func setAccount(account: FirefoxAccount?) {
self.account = account
}
func getClients() -> Deferred<Result<[RemoteClient]>> {
return deferResult([])
}
func getClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> {
return deferResult([])
}
} | 7b31a5b84e76504029d55af238c6f3a7 | 25.963855 | 99 | 0.651319 | false | false | false | false |
dduan/swift | refs/heads/master | stdlib/public/SDK/Foundation/Foundation.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import CoreFoundation
import CoreGraphics
//===----------------------------------------------------------------------===//
// Enums
//===----------------------------------------------------------------------===//
// FIXME: one day this will be bridged from CoreFoundation and we
// should drop it here. <rdar://problem/14497260> (need support
// for CF bridging)
public var kCFStringEncodingASCII: CFStringEncoding { return 0x0600 }
// FIXME: <rdar://problem/16074941> NSStringEncoding doesn't work on 32-bit
public typealias NSStringEncoding = UInt
public var NSASCIIStringEncoding: UInt { return 1 }
public var NSNEXTSTEPStringEncoding: UInt { return 2 }
public var NSJapaneseEUCStringEncoding: UInt { return 3 }
public var NSUTF8StringEncoding: UInt { return 4 }
public var NSISOLatin1StringEncoding: UInt { return 5 }
public var NSSymbolStringEncoding: UInt { return 6 }
public var NSNonLossyASCIIStringEncoding: UInt { return 7 }
public var NSShiftJISStringEncoding: UInt { return 8 }
public var NSISOLatin2StringEncoding: UInt { return 9 }
public var NSUnicodeStringEncoding: UInt { return 10 }
public var NSWindowsCP1251StringEncoding: UInt { return 11 }
public var NSWindowsCP1252StringEncoding: UInt { return 12 }
public var NSWindowsCP1253StringEncoding: UInt { return 13 }
public var NSWindowsCP1254StringEncoding: UInt { return 14 }
public var NSWindowsCP1250StringEncoding: UInt { return 15 }
public var NSISO2022JPStringEncoding: UInt { return 21 }
public var NSMacOSRomanStringEncoding: UInt { return 30 }
public var NSUTF16StringEncoding: UInt { return NSUnicodeStringEncoding }
public var NSUTF16BigEndianStringEncoding: UInt { return 0x90000100 }
public var NSUTF16LittleEndianStringEncoding: UInt { return 0x94000100 }
public var NSUTF32StringEncoding: UInt { return 0x8c000100 }
public var NSUTF32BigEndianStringEncoding: UInt { return 0x98000100 }
public var NSUTF32LittleEndianStringEncoding: UInt { return 0x9c000100 }
//===----------------------------------------------------------------------===//
// NSObject
//===----------------------------------------------------------------------===//
// These conformances should be located in the `ObjectiveC` module, but they can't
// be placed there because string bridging is not available there.
extension NSObject : CustomStringConvertible {}
extension NSObject : CustomDebugStringConvertible {}
//===----------------------------------------------------------------------===//
// Strings
//===----------------------------------------------------------------------===//
@available(*, unavailable, message: "Please use String or NSString")
public class NSSimpleCString {}
@available(*, unavailable, message: "Please use String or NSString")
public class NSConstantString {}
@warn_unused_result
@_silgen_name("swift_convertStringToNSString")
public // COMPILER_INTRINSIC
func _convertStringToNSString(string: String) -> NSString {
return string._bridgeToObjectiveC()
}
extension NSString : StringLiteralConvertible {
/// Create an instance initialized to `value`.
public required convenience init(unicodeScalarLiteral value: StaticString) {
self.init(stringLiteral: value)
}
public required convenience init(
extendedGraphemeClusterLiteral value: StaticString
) {
self.init(stringLiteral: value)
}
/// Create an instance initialized to `value`.
public required convenience init(stringLiteral value: StaticString) {
var immutableResult: NSString
if value.hasPointerRepresentation {
immutableResult = NSString(
bytesNoCopy: UnsafeMutablePointer<Void>(value.utf8Start),
length: Int(value.utf8CodeUnitCount),
encoding: value.isASCII ? NSASCIIStringEncoding : NSUTF8StringEncoding,
freeWhenDone: false)!
} else {
var uintValue = value.unicodeScalar
immutableResult = NSString(
bytes: &uintValue,
length: 4,
encoding: NSUTF32StringEncoding)!
}
self.init(string: immutableResult as String)
}
}
//===----------------------------------------------------------------------===//
// New Strings
//===----------------------------------------------------------------------===//
//
// Conversion from NSString to Swift's native representation
//
extension String {
public init(_ cocoaString: NSString) {
self = String(_cocoaString: cocoaString)
}
}
extension String : _ObjectiveCBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSString {
// This method should not do anything extra except calling into the
// implementation inside core. (These two entry points should be
// equivalent.)
return unsafeBitCast(_bridgeToObjectiveCImpl(), to: NSString.self)
}
public static func _forceBridgeFromObjectiveC(
x: NSString,
result: inout String?
) {
result = String(x)
}
public static func _conditionallyBridgeFromObjectiveC(
x: NSString,
result: inout String?
) -> Bool {
self._forceBridgeFromObjectiveC(x, result: &result)
return result != nil
}
public static func _unconditionallyBridgeFromObjectiveC(
source: NSString?
) -> String {
// `nil` has historically been used as a stand-in for an empty
// string; map it to an empty string.
if _slowPath(source == nil) { return String() }
return String(source!)
}
}
//===----------------------------------------------------------------------===//
// Numbers
//===----------------------------------------------------------------------===//
// Conversions between NSNumber and various numeric types. The
// conversion to NSNumber is automatic (auto-boxing), while conversion
// back to a specific numeric type requires a cast.
// FIXME: Incomplete list of types.
extension Int : _ObjectiveCBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public init(_ number: NSNumber) {
self = number.integerValue
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSNumber {
return NSNumber(integer: self)
}
public static func _forceBridgeFromObjectiveC(
x: NSNumber,
result: inout Int?
) {
result = x.integerValue
}
public static func _conditionallyBridgeFromObjectiveC(
x: NSNumber,
result: inout Int?
) -> Bool {
self._forceBridgeFromObjectiveC(x, result: &result)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(
source: NSNumber?
) -> Int {
return source!.integerValue
}
}
extension UInt : _ObjectiveCBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public init(_ number: NSNumber) {
self = number.unsignedIntegerValue
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSNumber {
return NSNumber(unsignedInteger: self)
}
public static func _forceBridgeFromObjectiveC(
x: NSNumber,
result: inout UInt?
) {
result = x.unsignedIntegerValue
}
public static func _conditionallyBridgeFromObjectiveC(
x: NSNumber,
result: inout UInt?
) -> Bool {
self._forceBridgeFromObjectiveC(x, result: &result)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(
source: NSNumber?
) -> UInt {
return source!.unsignedIntegerValue
}
}
extension Float : _ObjectiveCBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public init(_ number: NSNumber) {
self = number.floatValue
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSNumber {
return NSNumber(float: self)
}
public static func _forceBridgeFromObjectiveC(
x: NSNumber,
result: inout Float?
) {
result = x.floatValue
}
public static func _conditionallyBridgeFromObjectiveC(
x: NSNumber,
result: inout Float?
) -> Bool {
self._forceBridgeFromObjectiveC(x, result: &result)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(
source: NSNumber?
) -> Float {
return source!.floatValue
}
}
extension Double : _ObjectiveCBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public init(_ number: NSNumber) {
self = number.doubleValue
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSNumber {
return NSNumber(double: self)
}
public static func _forceBridgeFromObjectiveC(
x: NSNumber,
result: inout Double?
) {
result = x.doubleValue
}
public static func _conditionallyBridgeFromObjectiveC(
x: NSNumber,
result: inout Double?
) -> Bool {
self._forceBridgeFromObjectiveC(x, result: &result)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(
source: NSNumber?
) -> Double {
return source!.doubleValue
}
}
extension Bool: _ObjectiveCBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public init(_ number: NSNumber) {
self = number.boolValue
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSNumber {
return NSNumber(bool: self)
}
public static func _forceBridgeFromObjectiveC(
x: NSNumber,
result: inout Bool?
) {
result = x.boolValue
}
public static func _conditionallyBridgeFromObjectiveC(
x: NSNumber,
result: inout Bool?
) -> Bool {
self._forceBridgeFromObjectiveC(x, result: &result)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(
source: NSNumber?
) -> Bool {
return source!.boolValue
}
}
// CGFloat bridging.
extension CGFloat : _ObjectiveCBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public init(_ number: NSNumber) {
self.native = CGFloat.NativeType(number)
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSNumber {
return self.native._bridgeToObjectiveC()
}
public static func _forceBridgeFromObjectiveC(
x: NSNumber,
result: inout CGFloat?
) {
var nativeResult: CGFloat.NativeType? = 0.0
CGFloat.NativeType._forceBridgeFromObjectiveC(x, result: &nativeResult)
result = CGFloat(nativeResult!)
}
public static func _conditionallyBridgeFromObjectiveC(
x: NSNumber,
result: inout CGFloat?
) -> Bool {
self._forceBridgeFromObjectiveC(x, result: &result)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(
source: NSNumber?
) -> CGFloat {
return CGFloat(
CGFloat.NativeType._unconditionallyBridgeFromObjectiveC(source))
}
}
// Literal support for NSNumber
extension NSNumber : FloatLiteralConvertible, IntegerLiteralConvertible,
BooleanLiteralConvertible {
/// Create an instance initialized to `value`.
public required convenience init(integerLiteral value: Int) {
self.init(integer: value)
}
/// Create an instance initialized to `value`.
public required convenience init(floatLiteral value: Double) {
self.init(double: value)
}
/// Create an instance initialized to `value`.
public required convenience init(booleanLiteral value: Bool) {
self.init(bool: value)
}
}
public let NSNotFound: Int = .max
//===----------------------------------------------------------------------===//
// Arrays
//===----------------------------------------------------------------------===//
extension NSArray : ArrayLiteralConvertible {
/// Create an instance initialized with `elements`.
public required convenience init(arrayLiteral elements: AnyObject...) {
// + (instancetype)arrayWithObjects:(const id [])objects count:(NSUInteger)cnt;
let x = _extractOrCopyToNativeArrayBuffer(elements._buffer)
self.init(
objects: UnsafeMutablePointer(x.firstElementAddress), count: x.count)
_fixLifetime(x)
}
}
extension Array : _ObjectiveCBridgeable {
/// Private initializer used for bridging.
///
/// The provided `NSArray` will be copied to ensure that the copy can
/// not be mutated by other code.
internal init(_cocoaArray: NSArray) {
_sanityCheck(_isBridgedVerbatimToObjectiveC(Element.self),
"Array can be backed by NSArray only when the element type can be bridged verbatim to Objective-C")
// FIXME: We would like to call CFArrayCreateCopy() to avoid doing an
// objc_msgSend() for instances of CoreFoundation types. We can't do that
// today because CFArrayCreateCopy() copies array contents unconditionally,
// resulting in O(n) copies even for immutable arrays.
//
// <rdar://problem/19773555> CFArrayCreateCopy() is >10x slower than
// -[NSArray copyWithZone:]
//
// The bug is fixed in: OS X 10.11.0, iOS 9.0, all versions of tvOS
// and watchOS.
self = Array(
_immutableCocoaArray:
unsafeBitCast(_cocoaArray.copy(), to: _NSArrayCore.self))
}
public static func _isBridgedToObjectiveC() -> Bool {
return Swift._isBridgedToObjectiveC(Element.self)
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSArray {
return unsafeBitCast(self._buffer._asCocoaArray(), to: NSArray.self)
}
public static func _forceBridgeFromObjectiveC(
source: NSArray,
result: inout Array?
) {
_precondition(
Swift._isBridgedToObjectiveC(Element.self),
"array element type is not bridged to Objective-C")
// If we have the appropriate native storage already, just adopt it.
if let native =
Array._bridgeFromObjectiveCAdoptingNativeStorageOf(source) {
result = native
return
}
if _fastPath(_isBridgedVerbatimToObjectiveC(Element.self)) {
// Forced down-cast (possible deferred type-checking)
result = Array(_cocoaArray: source)
return
}
result = _arrayForceCast([AnyObject](_cocoaArray: source))
}
public static func _conditionallyBridgeFromObjectiveC(
source: NSArray,
result: inout Array?
) -> Bool {
// Construct the result array by conditionally bridging each element.
let anyObjectArr = [AnyObject](_cocoaArray: source)
result = _arrayConditionalCast(anyObjectArr)
return result != nil
}
public static func _unconditionallyBridgeFromObjectiveC(
source: NSArray?
) -> Array {
_precondition(
Swift._isBridgedToObjectiveC(Element.self),
"array element type is not bridged to Objective-C")
// `nil` has historically been used as a stand-in for an empty
// array; map it to an empty array instead of failing.
if _slowPath(source == nil) { return Array() }
// If we have the appropriate native storage already, just adopt it.
if let native =
Array._bridgeFromObjectiveCAdoptingNativeStorageOf(source!) {
return native
}
if _fastPath(_isBridgedVerbatimToObjectiveC(Element.self)) {
// Forced down-cast (possible deferred type-checking)
return Array(_cocoaArray: source!)
}
return _arrayForceCast([AnyObject](_cocoaArray: source!))
}
}
//===----------------------------------------------------------------------===//
// Dictionaries
//===----------------------------------------------------------------------===//
extension NSDictionary : DictionaryLiteralConvertible {
public required convenience init(
dictionaryLiteral elements: (NSCopying, AnyObject)...
) {
self.init(
objects: elements.map { (AnyObject?)($0.1) },
forKeys: elements.map { (NSCopying?)($0.0) },
count: elements.count)
}
}
extension Dictionary {
/// Private initializer used for bridging.
///
/// The provided `NSDictionary` will be copied to ensure that the copy can
/// not be mutated by other code.
public init(_cocoaDictionary: _NSDictionary) {
_sanityCheck(
_isBridgedVerbatimToObjectiveC(Key.self) &&
_isBridgedVerbatimToObjectiveC(Value.self),
"Dictionary can be backed by NSDictionary storage only when both key and value are bridged verbatim to Objective-C")
// FIXME: We would like to call CFDictionaryCreateCopy() to avoid doing an
// objc_msgSend() for instances of CoreFoundation types. We can't do that
// today because CFDictionaryCreateCopy() copies dictionary contents
// unconditionally, resulting in O(n) copies even for immutable dictionaries.
//
// <rdar://problem/20690755> CFDictionaryCreateCopy() does not call copyWithZone:
//
// The bug is fixed in: OS X 10.11.0, iOS 9.0, all versions of tvOS
// and watchOS.
self = Dictionary(
_immutableCocoaDictionary:
unsafeBitCast(_cocoaDictionary.copy(with: nil), to: _NSDictionary.self))
}
}
// Dictionary<Key, Value> is conditionally bridged to NSDictionary
extension Dictionary : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSDictionary {
return unsafeBitCast(_bridgeToObjectiveCImpl(), to: NSDictionary.self)
}
public static func _forceBridgeFromObjectiveC(
d: NSDictionary,
result: inout Dictionary?
) {
if let native = [Key : Value]._bridgeFromObjectiveCAdoptingNativeStorageOf(
d as AnyObject) {
result = native
return
}
if _isBridgedVerbatimToObjectiveC(Key.self) &&
_isBridgedVerbatimToObjectiveC(Value.self) {
result = [Key : Value](
_cocoaDictionary: unsafeBitCast(d, to: _NSDictionary.self))
return
}
// `Dictionary<Key, Value>` where either `Key` or `Value` is a value type
// may not be backed by an NSDictionary.
var builder = _DictionaryBuilder<Key, Value>(count: d.count)
d.enumerateKeysAndObjects({
(anyObjectKey: AnyObject, anyObjectValue: AnyObject,
stop: UnsafeMutablePointer<ObjCBool>) in
builder.add(
key: Swift._forceBridgeFromObjectiveC(anyObjectKey, Key.self),
value: Swift._forceBridgeFromObjectiveC(anyObjectValue, Value.self))
})
result = builder.take()
}
public static func _conditionallyBridgeFromObjectiveC(
x: NSDictionary,
result: inout Dictionary?
) -> Bool {
let anyDict = x as [NSObject : AnyObject]
if _isBridgedVerbatimToObjectiveC(Key.self) &&
_isBridgedVerbatimToObjectiveC(Value.self) {
result = Swift._dictionaryDownCastConditional(anyDict)
return result != nil
}
result = Swift._dictionaryBridgeFromObjectiveCConditional(anyDict)
return result != nil
}
public static func _isBridgedToObjectiveC() -> Bool {
return Swift._isBridgedToObjectiveC(Key.self) &&
Swift._isBridgedToObjectiveC(Value.self)
}
public static func _unconditionallyBridgeFromObjectiveC(
d: NSDictionary?
) -> Dictionary {
// `nil` has historically been used as a stand-in for an empty
// dictionary; map it to an empty dictionary.
if _slowPath(d == nil) { return Dictionary() }
if let native = [Key : Value]._bridgeFromObjectiveCAdoptingNativeStorageOf(
d! as AnyObject) {
return native
}
if _isBridgedVerbatimToObjectiveC(Key.self) &&
_isBridgedVerbatimToObjectiveC(Value.self) {
return [Key : Value](
_cocoaDictionary: unsafeBitCast(d!, to: _NSDictionary.self))
}
// `Dictionary<Key, Value>` where either `Key` or `Value` is a value type
// may not be backed by an NSDictionary.
var builder = _DictionaryBuilder<Key, Value>(count: d!.count)
d!.enumerateKeysAndObjects({
(anyObjectKey: AnyObject, anyObjectValue: AnyObject,
stop: UnsafeMutablePointer<ObjCBool>) in
builder.add(
key: Swift._forceBridgeFromObjectiveC(anyObjectKey, Key.self),
value: Swift._forceBridgeFromObjectiveC(anyObjectValue, Value.self))
})
return builder.take()
}
}
//===----------------------------------------------------------------------===//
// Fast enumeration
//===----------------------------------------------------------------------===//
// NB: This is a class because fast enumeration passes around interior pointers
// to the enumeration state, so the state cannot be moved in memory. We will
// probably need to implement fast enumeration in the compiler as a primitive
// to implement it both correctly and efficiently.
final public class NSFastEnumerationIterator : IteratorProtocol {
var enumerable: NSFastEnumeration
var state: [NSFastEnumerationState]
var n: Int
var count: Int
/// Size of ObjectsBuffer, in ids.
var STACK_BUF_SIZE: Int { return 4 }
// FIXME: Replace with _CocoaFastEnumerationStackBuf.
/// Must have enough space for STACK_BUF_SIZE object references.
struct ObjectsBuffer {
var buf: (OpaquePointer, OpaquePointer, OpaquePointer, OpaquePointer) =
(nil, nil, nil, nil)
}
var objects: [ObjectsBuffer]
public func next() -> AnyObject? {
if n == count {
// FIXME: Is this check necessary before refresh()?
if count == 0 { return nil }
refresh()
if count == 0 { return nil }
}
let next: AnyObject = state[0].itemsPtr[n]!
n += 1
return next
}
func refresh() {
n = 0
count = enumerable.countByEnumerating(
with: state._baseAddressIfContiguous,
objects: AutoreleasingUnsafeMutablePointer(
objects._baseAddressIfContiguous),
count: STACK_BUF_SIZE)
}
public init(_ enumerable: NSFastEnumeration) {
self.enumerable = enumerable
self.state = [ NSFastEnumerationState(
state: 0, itemsPtr: nil,
mutationsPtr: _fastEnumerationStorageMutationsPtr,
extra: (0, 0, 0, 0, 0)) ]
self.objects = [ ObjectsBuffer() ]
self.n = -1
self.count = -1
}
}
extension NSArray : Sequence {
/// Return an *iterator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
final public func makeIterator() -> NSFastEnumerationIterator {
return NSFastEnumerationIterator(self)
}
}
/* TODO: API review
extension NSArray : Swift.Collection {
final public var startIndex: Int {
return 0
}
final public var endIndex: Int {
return count
}
}
*/
extension Set {
/// Private initializer used for bridging.
///
/// The provided `NSSet` will be copied to ensure that the copy can
/// not be mutated by other code.
public init(_cocoaSet: _NSSet) {
_sanityCheck(_isBridgedVerbatimToObjectiveC(Element.self),
"Set can be backed by NSSet _variantStorage only when the member type can be bridged verbatim to Objective-C")
// FIXME: We would like to call CFSetCreateCopy() to avoid doing an
// objc_msgSend() for instances of CoreFoundation types. We can't do that
// today because CFSetCreateCopy() copies dictionary contents
// unconditionally, resulting in O(n) copies even for immutable dictionaries.
//
// <rdar://problem/20697680> CFSetCreateCopy() does not call copyWithZone:
//
// The bug is fixed in: OS X 10.11.0, iOS 9.0, all versions of tvOS
// and watchOS.
self = Set(
_immutableCocoaSet:
unsafeBitCast(_cocoaSet.copy(with: nil), to: _NSSet.self))
}
}
extension NSSet : Sequence {
/// Return an *iterator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func makeIterator() -> NSFastEnumerationIterator {
return NSFastEnumerationIterator(self)
}
}
extension NSOrderedSet : Sequence {
/// Return an *iterator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func makeIterator() -> NSFastEnumerationIterator {
return NSFastEnumerationIterator(self)
}
}
// FIXME: move inside NSIndexSet when the compiler supports this.
public struct NSIndexSetIterator : IteratorProtocol {
public typealias Element = Int
internal let _set: NSIndexSet
internal var _first: Bool = true
internal var _current: Int?
internal init(set: NSIndexSet) {
self._set = set
self._current = nil
}
public mutating func next() -> Int? {
if _first {
_current = _set.firstIndex
_first = false
} else if let c = _current {
_current = _set.indexGreaterThanIndex(c)
} else {
// current is already nil
}
if _current == NSNotFound {
_current = nil
}
return _current
}
}
extension NSIndexSet : Sequence {
/// Return an *iterator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func makeIterator() -> NSIndexSetIterator {
return NSIndexSetIterator(set: self)
}
}
// Set<Element> is conditionally bridged to NSSet
extension Set : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSSet {
return unsafeBitCast(_bridgeToObjectiveCImpl(), to: NSSet.self)
}
public static func _forceBridgeFromObjectiveC(s: NSSet, result: inout Set?) {
if let native =
Set<Element>._bridgeFromObjectiveCAdoptingNativeStorageOf(s as AnyObject) {
result = native
return
}
if _isBridgedVerbatimToObjectiveC(Element.self) {
result = Set<Element>(_cocoaSet: unsafeBitCast(s, to: _NSSet.self))
return
}
// `Set<Element>` where `Element` is a value type may not be backed by
// an NSSet.
var builder = _SetBuilder<Element>(count: s.count)
s.enumerateObjects({
(anyObjectMember: AnyObject, stop: UnsafeMutablePointer<ObjCBool>) in
builder.add(member: Swift._forceBridgeFromObjectiveC(
anyObjectMember, Element.self))
})
result = builder.take()
}
public static func _conditionallyBridgeFromObjectiveC(
x: NSSet, result: inout Set?
) -> Bool {
let anySet = x as Set<NSObject>
if _isBridgedVerbatimToObjectiveC(Element.self) {
result = Swift._setDownCastConditional(anySet)
return result != nil
}
result = Swift._setBridgeFromObjectiveCConditional(anySet)
return result != nil
}
public static func _unconditionallyBridgeFromObjectiveC(s: NSSet?) -> Set {
// `nil` has historically been used as a stand-in for an empty
// set; map it to an empty set.
if _slowPath(s == nil) { return Set() }
if let native =
Set<Element>._bridgeFromObjectiveCAdoptingNativeStorageOf(s! as AnyObject) {
return native
}
if _isBridgedVerbatimToObjectiveC(Element.self) {
return Set<Element>(_cocoaSet: unsafeBitCast(s!, to: _NSSet.self))
}
// `Set<Element>` where `Element` is a value type may not be backed by
// an NSSet.
var builder = _SetBuilder<Element>(count: s!.count)
s!.enumerateObjects({
(anyObjectMember: AnyObject, stop: UnsafeMutablePointer<ObjCBool>) in
builder.add(member: Swift._forceBridgeFromObjectiveC(
anyObjectMember, Element.self))
})
return builder.take()
}
public static func _isBridgedToObjectiveC() -> Bool {
return Swift._isBridgedToObjectiveC(Element.self)
}
}
extension NSDictionary : Sequence {
// FIXME: A class because we can't pass a struct with class fields through an
// [objc] interface without prematurely destroying the references.
final public class Iterator : IteratorProtocol {
var _fastIterator: NSFastEnumerationIterator
var _dictionary: NSDictionary {
return _fastIterator.enumerable as! NSDictionary
}
public func next() -> (key: AnyObject, value: AnyObject)? {
if let key = _fastIterator.next() {
// Deliberately avoid the subscript operator in case the dictionary
// contains non-copyable keys. This is rare since NSMutableDictionary
// requires them, but we don't want to paint ourselves into a corner.
return (key: key, value: _dictionary.object(forKey: key)!)
}
return nil
}
internal init(_ _dict: NSDictionary) {
_fastIterator = NSFastEnumerationIterator(_dict)
}
}
/// Return an *iterator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func makeIterator() -> Iterator {
return Iterator(self)
}
}
extension NSEnumerator : Sequence {
/// Return an *iterator* over the *enumerator*.
///
/// - Complexity: O(1).
public func makeIterator() -> NSFastEnumerationIterator {
return NSFastEnumerationIterator(self)
}
}
//===----------------------------------------------------------------------===//
// Ranges
//===----------------------------------------------------------------------===//
extension NSRange {
public init(_ x: Range<Int>) {
location = x.startIndex
length = x.count
}
@warn_unused_result
public func toRange() -> Range<Int>? {
if location == NSNotFound { return nil }
return location..<(location+length)
}
}
//===----------------------------------------------------------------------===//
// NSLocalizedString
//===----------------------------------------------------------------------===//
/// Returns a localized string, using the main bundle if one is not specified.
@warn_unused_result
public
func NSLocalizedString(key: String,
tableName: String? = nil,
bundle: NSBundle = NSBundle.main(),
value: String = "",
comment: String) -> String {
return bundle.localizedString(forKey: key, value:value, table:tableName)
}
//===----------------------------------------------------------------------===//
// NSLog
//===----------------------------------------------------------------------===//
public func NSLog(format: String, _ args: CVarArg...) {
withVaList(args) { NSLogv(format, $0) }
}
#if os(OSX)
//===----------------------------------------------------------------------===//
// NSRectEdge
//===----------------------------------------------------------------------===//
// In the SDK, the following NS*Edge constants are defined as macros for the
// corresponding CGRectEdge enumerators. Thus, in the SDK, NS*Edge constants
// have CGRectEdge type. This is not correct for Swift (as there is no
// implicit conversion to NSRectEdge).
@available(*, unavailable, renamed: "NSRectEdge.MinX")
public var NSMinXEdge: NSRectEdge {
fatalError("unavailable property can't be accessed")
}
@available(*, unavailable, renamed: "NSRectEdge.MinY")
public var NSMinYEdge: NSRectEdge {
fatalError("unavailable property can't be accessed")
}
@available(*, unavailable, renamed: "NSRectEdge.MaxX")
public var NSMaxXEdge: NSRectEdge {
fatalError("unavailable property can't be accessed")
}
@available(*, unavailable, renamed: "NSRectEdge.MaxY")
public var NSMaxYEdge: NSRectEdge {
fatalError("unavailable property can't be accessed")
}
extension NSRectEdge {
public init(rectEdge: CGRectEdge) {
self = NSRectEdge(rawValue: UInt(rectEdge.rawValue))!
}
}
extension CGRectEdge {
public init(rectEdge: NSRectEdge) {
self = CGRectEdge(rawValue: UInt32(rectEdge.rawValue))!
}
}
#endif
//===----------------------------------------------------------------------===//
// NSError (as an out parameter).
//===----------------------------------------------------------------------===//
public typealias NSErrorPointer = AutoreleasingUnsafeMutablePointer<NSError?>
// Note: NSErrorPointer becomes ErrorPointer in Swift 3.
public typealias ErrorPointer = NSErrorPointer
public // COMPILER_INTRINSIC
let _nilObjCError: ErrorProtocol = _GenericObjCError.nilError
@warn_unused_result
@_silgen_name("swift_convertNSErrorToErrorProtocol")
public // COMPILER_INTRINSIC
func _convertNSErrorToErrorProtocol(error: NSError?) -> ErrorProtocol {
if let error = error {
return error
}
return _nilObjCError
}
@warn_unused_result
@_silgen_name("swift_convertErrorProtocolToNSError")
public // COMPILER_INTRINSIC
func _convertErrorProtocolToNSError(error: ErrorProtocol) -> NSError {
return unsafeDowncast(_bridgeErrorProtocolToNSError(error), to: NSError.self)
}
//===----------------------------------------------------------------------===//
// Variadic initializers and methods
//===----------------------------------------------------------------------===//
extension NSPredicate {
// + (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat, ...;
public
convenience init(format predicateFormat: String, _ args: CVarArg...) {
let va_args = getVaList(args)
self.init(format: predicateFormat, arguments: va_args)
}
}
extension NSExpression {
// + (NSExpression *) expressionWithFormat:(NSString *)expressionFormat, ...;
public
convenience init(format expressionFormat: String, _ args: CVarArg...) {
let va_args = getVaList(args)
self.init(format: expressionFormat, arguments: va_args)
}
}
extension NSString {
public convenience init(format: NSString, _ args: CVarArg...) {
// We can't use withVaList because 'self' cannot be captured by a closure
// before it has been initialized.
let va_args = getVaList(args)
self.init(format: format as String, arguments: va_args)
}
public convenience init(
format: NSString, locale: NSLocale?, _ args: CVarArg...
) {
// We can't use withVaList because 'self' cannot be captured by a closure
// before it has been initialized.
let va_args = getVaList(args)
self.init(format: format as String, locale: locale, arguments: va_args)
}
@warn_unused_result
public class func localizedStringWithFormat(
format: NSString, _ args: CVarArg...
) -> Self {
return withVaList(args) {
self.init(format: format as String, locale: NSLocale.current(), arguments: $0)
}
}
@warn_unused_result
public func appendingFormat(format: NSString, _ args: CVarArg...)
-> NSString {
return withVaList(args) {
self.appending(NSString(format: format as String, arguments: $0) as String) as NSString
}
}
}
extension NSMutableString {
public func appendFormat(format: NSString, _ args: CVarArg...) {
return withVaList(args) {
self.append(NSString(format: format as String, arguments: $0) as String)
}
}
}
extension NSArray {
// Overlay: - (instancetype)initWithObjects:(id)firstObj, ...
public convenience init(objects elements: AnyObject...) {
// - (instancetype)initWithObjects:(const id [])objects count:(NSUInteger)cnt;
let x = _extractOrCopyToNativeArrayBuffer(elements._buffer)
// Use Imported:
// @objc(initWithObjects:count:)
// init(withObjects objects: UnsafePointer<AnyObject?>,
// count cnt: Int)
self.init(objects: UnsafeMutablePointer(x.firstElementAddress), count: x.count)
_fixLifetime(x)
}
}
extension NSOrderedSet {
// - (instancetype)initWithObjects:(id)firstObj, ...
public convenience init(objects elements: AnyObject...) {
self.init(array: elements)
}
}
extension NSSet {
// - (instancetype)initWithObjects:(id)firstObj, ...
public convenience init(objects elements: AnyObject...) {
self.init(array: elements)
}
}
extension NSSet : ArrayLiteralConvertible {
public required convenience init(arrayLiteral elements: AnyObject...) {
self.init(array: elements)
}
}
extension NSOrderedSet : ArrayLiteralConvertible {
public required convenience init(arrayLiteral elements: AnyObject...) {
self.init(array: elements)
}
}
//===--- "Copy constructors" ----------------------------------------------===//
// These are needed to make Cocoa feel natural since we eliminated
// implicit bridging conversions from Objective-C to Swift
//===----------------------------------------------------------------------===//
extension NSArray {
/// Initializes a newly allocated array by placing in it the objects
/// contained in a given array.
///
/// - Returns: An array initialized to contain the objects in
/// `anArray``. The returned object might be different than the
/// original receiver.
///
/// Discussion: After an immutable array has been initialized in
/// this way, it cannot be modified.
@objc(_swiftInitWithArray_NSArray:)
public convenience init(array anArray: NSArray) {
self.init(array: anArray as Array)
}
}
extension NSString {
/// Returns an `NSString` object initialized by copying the characters
/// from another given string.
///
/// - Returns: An `NSString` object initialized by copying the
/// characters from `aString`. The returned object may be different
/// from the original receiver.
@objc(_swiftInitWithString_NSString:)
public convenience init(string aString: NSString) {
self.init(string: aString as String)
}
}
extension NSSet {
/// Initializes a newly allocated set and adds to it objects from
/// another given set.
///
/// - Returns: An initialized objects set containing the objects from
/// `set`. The returned set might be different than the original
/// receiver.
@objc(_swiftInitWithSet_NSSet:)
public convenience init(set anSet: NSSet) {
self.init(set: anSet as Set)
}
}
extension NSDictionary {
/// Initializes a newly allocated dictionary and adds to it objects from
/// another given dictionary.
///
/// - Returns: An initialized dictionary—which might be different
/// than the original receiver—containing the keys and values
/// found in `otherDictionary`.
@objc(_swiftInitWithDictionary_NSDictionary:)
public convenience init(dictionary otherDictionary: NSDictionary) {
self.init(dictionary: otherDictionary as Dictionary)
}
}
//===----------------------------------------------------------------------===//
// NSUndoManager
//===----------------------------------------------------------------------===//
@_silgen_name("NS_Swift_NSUndoManager_registerUndoWithTargetHandler")
internal func NS_Swift_NSUndoManager_registerUndoWithTargetHandler(
self_: AnyObject,
_ target: AnyObject,
_ handler: @convention(block) (AnyObject) -> Void)
extension NSUndoManager {
@available(OSX 10.11, iOS 9.0, *)
public func registerUndoWithTarget<TargetType : AnyObject>(
target: TargetType, handler: (TargetType) -> Void
) {
// The generic blocks use a different ABI, so we need to wrap the provided
// handler in something ObjC compatible.
let objcCompatibleHandler: (AnyObject) -> Void = { internalTarget in
handler(internalTarget as! TargetType)
}
NS_Swift_NSUndoManager_registerUndoWithTargetHandler(
self as AnyObject, target as AnyObject, objcCompatibleHandler)
}
}
//===----------------------------------------------------------------------===//
// NSCoder
//===----------------------------------------------------------------------===//
@warn_unused_result
@_silgen_name("NS_Swift_NSCoder_decodeObject")
internal func NS_Swift_NSCoder_decodeObject(
self_: AnyObject,
_ error: NSErrorPointer) -> AnyObject?
@warn_unused_result
@_silgen_name("NS_Swift_NSCoder_decodeObjectForKey")
internal func NS_Swift_NSCoder_decodeObjectForKey(
self_: AnyObject,
_ key: AnyObject,
_ error: NSErrorPointer) -> AnyObject?
@warn_unused_result
@_silgen_name("NS_Swift_NSCoder_decodeObjectOfClassForKey")
internal func NS_Swift_NSCoder_decodeObjectOfClassForKey(
self_: AnyObject,
_ cls: AnyObject,
_ key: AnyObject,
_ error: NSErrorPointer) -> AnyObject?
@warn_unused_result
@_silgen_name("NS_Swift_NSCoder_decodeObjectOfClassesForKey")
internal func NS_Swift_NSCoder_decodeObjectOfClassesForKey(
self_: AnyObject,
_ classes: NSSet?,
_ key: AnyObject,
_ error: NSErrorPointer) -> AnyObject?
@available(OSX 10.11, iOS 9.0, *)
internal func resolveError(error: NSError?) throws {
if let error = error where error.code != NSCoderValueNotFoundError {
throw error
}
}
extension NSCoder {
@warn_unused_result
public func decodeObjectOfClass<DecodedObjectType: NSCoding where DecodedObjectType: NSObject>(cls: DecodedObjectType.Type, forKey key: String) -> DecodedObjectType? {
let result = NS_Swift_NSCoder_decodeObjectOfClassForKey(self as AnyObject, cls as AnyObject, key as AnyObject, nil)
return result as! DecodedObjectType?
}
@warn_unused_result
@nonobjc
public func decodeObjectOfClasses(classes: NSSet?, forKey key: String) -> AnyObject? {
var classesAsNSObjects: Set<NSObject>? = nil
if let theClasses = classes {
classesAsNSObjects =
Set(IteratorSequence(NSFastEnumerationIterator(theClasses)).map {
unsafeBitCast($0, to: NSObject.self)
})
}
return self.__decodeObject(ofClasses: classesAsNSObjects, forKey: key)
}
@warn_unused_result
@available(OSX 10.11, iOS 9.0, *)
public func decodeTopLevelObject() throws -> AnyObject? {
var error: NSError?
let result = NS_Swift_NSCoder_decodeObject(self as AnyObject, &error)
try resolveError(error)
return result
}
@warn_unused_result
@available(OSX 10.11, iOS 9.0, *)
public func decodeTopLevelObjectForKey(key: String) throws -> AnyObject? {
var error: NSError?
let result = NS_Swift_NSCoder_decodeObjectForKey(self as AnyObject, key as AnyObject, &error)
try resolveError(error)
return result
}
@warn_unused_result
@available(OSX 10.11, iOS 9.0, *)
public func decodeTopLevelObjectOfClass<DecodedObjectType: NSCoding where DecodedObjectType: NSObject>(cls: DecodedObjectType.Type, forKey key: String) throws -> DecodedObjectType? {
var error: NSError?
let result = NS_Swift_NSCoder_decodeObjectOfClassForKey(self as AnyObject, cls as AnyObject, key as AnyObject, &error)
try resolveError(error)
return result as! DecodedObjectType?
}
@warn_unused_result
@available(OSX 10.11, iOS 9.0, *)
public func decodeTopLevelObjectOfClasses(classes: NSSet?, forKey key: String) throws -> AnyObject? {
var error: NSError?
let result = NS_Swift_NSCoder_decodeObjectOfClassesForKey(self as AnyObject, classes, key as AnyObject, &error)
try resolveError(error)
return result
}
}
//===----------------------------------------------------------------------===//
// NSKeyedUnarchiver
//===----------------------------------------------------------------------===//
@warn_unused_result
@_silgen_name("NS_Swift_NSKeyedUnarchiver_unarchiveObjectWithData")
internal func NS_Swift_NSKeyedUnarchiver_unarchiveObjectWithData(
self_: AnyObject,
_ data: AnyObject,
_ error: NSErrorPointer) -> AnyObject?
extension NSKeyedUnarchiver {
@warn_unused_result
@available(OSX 10.11, iOS 9.0, *)
public class func unarchiveTopLevelObjectWithData(data: NSData) throws -> AnyObject? {
var error: NSError?
let result = NS_Swift_NSKeyedUnarchiver_unarchiveObjectWithData(self, data as AnyObject, &error)
try resolveError(error)
return result
}
}
//===----------------------------------------------------------------------===//
// NSURL
//===----------------------------------------------------------------------===//
extension NSURL : _FileReferenceLiteralConvertible {
private convenience init(failableFileReferenceLiteral path: String) {
let fullPath = NSBundle.main().path(forResource: path, ofType: nil)!
self.init(fileURLWithPath: fullPath)
}
public required convenience init(fileReferenceLiteral path: String) {
self.init(failableFileReferenceLiteral: path)
}
}
public typealias _FileReferenceLiteralType = NSURL
//===----------------------------------------------------------------------===//
// Mirror/Quick Look Conformance
//===----------------------------------------------------------------------===//
extension NSURL : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .url(absoluteString)
}
}
extension NSRange : CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: ["location": location, "length": length])
}
}
extension NSRange : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .range(Int64(location), Int64(length))
}
}
extension NSDate : CustomPlaygroundQuickLookable {
var summary: String {
let df = NSDateFormatter()
df.dateStyle = .mediumStyle
df.timeStyle = .shortStyle
return df.string(from: self)
}
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text(summary)
}
}
extension NSSet : CustomReflectable {
public var customMirror: Mirror {
return Mirror(reflecting: self as Set<NSObject>)
}
}
extension NSString : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text(self as String)
}
}
extension NSArray : CustomReflectable {
public var customMirror: Mirror {
return Mirror(reflecting: self as [AnyObject])
}
}
extension NSDictionary : CustomReflectable {
public var customMirror: Mirror {
return Mirror(reflecting: self as [NSObject : AnyObject])
}
}
| 5bea47f3ca94201b414d140ba5681c59 | 30.840621 | 184 | 0.653909 | false | false | false | false |
Glenmax-ltd/GLXSegmentedControl | refs/heads/master | GLXSegmentedControl/GLXSegment.swift | mit | 1 | //
// GLXSegment.swift
// GLXSegmentedControl
//
// Created by Si MA on 03/01/2015.
// Copyright (c) 2015 Si Ma and Glenmax Ltd. All rights reserved.
//
import UIKit
open class GLXSegment: UIView {
// UI components
fileprivate lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = UIViewContentMode.scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
lazy var label: UILabel = {
let label = UILabel()
label.textAlignment = NSTextAlignment.center
label.translatesAutoresizingMaskIntoConstraints = false
label.adjustsFontSizeToFitWidth = true
label.baselineAdjustment = .alignCenters
label.setContentCompressionResistancePriority(UILayoutPriorityDefaultLow, for: .horizontal)
return label
}()
// Title
open var title: String? {
didSet {
self.label.text = self.title
}
}
// Image
open var onSelectionImage: UIImage?
open var offSelectionImage: UIImage?
// Appearance
open var appearance: GLXSegmentAppearance
internal var didSelectSegment: ((_ segment: GLXSegment)->())?
open internal(set) var index: Int = 0
open fileprivate(set) var isSelected: Bool = false
// Init
internal init(appearance: GLXSegmentAppearance?) {
if let app = appearance {
self.appearance = app
}
else {
self.appearance = GLXSegmentAppearance()
}
super.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal func setupUIElements() {
var verticalMargin: CGFloat = 0.0
verticalMargin = appearance.contentVerticalMargin
let imagePresent = (self.offSelectionImage != nil) || (self.onSelectionImage != nil)
var titlePresent = false
if let title = self.title {
titlePresent = (title != "")
}
if imagePresent && titlePresent {
// we have both image and title so we need to center them together
let view = UIView(frame: CGRect.zero) // this will be used to hold the image and label inside
view.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(self.imageView)
view.addSubview(self.label)
self.imageView.image = self.offSelectionImage
view.leadingAnchor.constraint(equalTo: self.imageView.leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: self.label.trailingAnchor).isActive = true
self.label.leadingAnchor.constraint(equalTo: self.imageView.trailingAnchor, constant: 3.0).isActive = true // this is used to separate image and label
view.topAnchor.constraint(lessThanOrEqualTo: self.imageView.topAnchor).isActive = true
view.topAnchor.constraint(lessThanOrEqualTo: self.label.topAnchor).isActive = true
view.centerYAnchor.constraint(equalTo: self.imageView.centerYAnchor).isActive = true
view.centerYAnchor.constraint(equalTo: self.label.centerYAnchor).isActive = true
self.addSubview(view)
self.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
self.topAnchor.constraint(lessThanOrEqualTo: view.topAnchor, constant:-verticalMargin).isActive = true
self.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
self.leadingAnchor.constraint(lessThanOrEqualTo: view.leadingAnchor, constant:-appearance.contentHorizontalMargin).isActive = true
}
else if imagePresent {
// only image is present
self.addSubview(self.imageView)
self.imageView.image = self.offSelectionImage
self.centerXAnchor.constraint(equalTo: self.imageView.centerXAnchor).isActive = true
self.centerYAnchor.constraint(equalTo: self.imageView.centerYAnchor).isActive = true
self.topAnchor.constraint(lessThanOrEqualTo: self.imageView.topAnchor, constant: -verticalMargin).isActive = true
self.leadingAnchor.constraint(lessThanOrEqualTo: self.imageView.leadingAnchor).isActive = true
}
else if titlePresent {
// only label is present
self.addSubview(self.label)
self.centerXAnchor.constraint(equalTo: self.label.centerXAnchor).isActive = true
self.centerYAnchor.constraint(equalTo: self.label.centerYAnchor).isActive = true
self.topAnchor.constraint(lessThanOrEqualTo: self.label.topAnchor, constant: -verticalMargin).isActive = true
self.leadingAnchor.constraint(lessThanOrEqualTo: self.label.leadingAnchor, constant:-appearance.contentHorizontalMargin).isActive = true
}
self.backgroundColor = appearance.segmentOffSelectionColor
if titlePresent {
self.label.font = appearance.titleOffSelectionFont
self.label.textColor = appearance.titleOffSelectionColor
}
}
// MARK: Selections
internal func setSelected(_ selected: Bool) {
self.isSelected = selected
if selected == true {
self.backgroundColor = self.appearance.segmentOnSelectionColor
self.label.textColor = self.appearance.titleOnSelectionColor
self.label.font = self.appearance.titleOnSelectionFont
self.imageView.image = self.onSelectionImage
}
else {
self.backgroundColor = self.appearance.segmentOffSelectionColor
self.label.textColor = self.appearance.titleOffSelectionColor
self.label.font = self.appearance.titleOffSelectionFont
self.imageView.image = self.offSelectionImage
}
}
// MARK: Handle touch
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if self.isSelected == false {
self.backgroundColor = self.appearance.segmentTouchDownColor
}
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if self.isSelected == false{
self.didSelectSegment?(self)
}
}
}
| e6b860c86f74daeb40becf4e4851b38e | 39.246914 | 162 | 0.65046 | false | false | false | false |
mennovf/Swift-MathEagle | refs/heads/master | MathEagleTests/OptimizationTests.swift | mit | 1 | //
// OptimizationTests.swift
// SwiftMath
//
// Created by Rugen Heidbuchel on 27/01/15.
// Copyright (c) 2015 Jorestha Solutions. All rights reserved.
//
import Cocoa
import XCTest
import MathEagle
class OptimizationTests: XCTestCase {
func testGoldenSection() {
var x = Optimization.goldenSection(-3.0, 3.0){ $0**2 + $0 - 4 }
XCTAssertEqualWithAccuracy(-0.5, x, accuracy: ACCURACY)
let f = { (x: Double) -> Double in
(log(x**2 + 1) + exp(x))/x
}
x = Optimization.goldenSection(0.5, 2.0, f: f)
XCTAssertEqualWithAccuracy(0.8754963230, x, accuracy: ACCURACY)
x = Optimization.goldenSection(-2.0, 1.5){ -sin($0)/$0 }
XCTAssertEqualWithAccuracy(0.0, x, accuracy: ACCURACY)
}
func testGoldenSectionPerformance() {
let f = { (x: Double) -> Double in
(log(x**2 + 1) + exp(x))/x
}
let time = timeBlock(n: 1000){
Optimization.goldenSection(0.5, 2.0, f: f)
}
let baseline = 1.0
print("Golden section time = \(time)\nBaseline = \(baseline)\n\(baseline/time) times faster than baseline")
}
} | 36f5ee528020251888aa0ed9a6163d85 | 25.208333 | 115 | 0.545744 | false | true | false | false |
phelgo/Vectors | refs/heads/master | Vectors/Vector2D.swift | mit | 1 | // Vector structs for Swift
// Copyright (c) 2015 phelgo. MIT licensed.
import CoreGraphics
public struct Vector2D: CustomDebugStringConvertible, CustomStringConvertible, Equatable, Hashable {
public let x: Double
public let y: Double
public init(_ x: Double, _ y: Double) {
self.x = x
self.y = y
}
public var magnitude: Double {
return sqrt(x * x + y * y)
}
public var squaredMagnitude: Double {
return x * x + y * y
}
public var normalized: Vector2D {
return Vector2D(x / magnitude, y / magnitude)
}
public var description: String {
return "Vector2D(\(x), \(y))"
}
public var debugDescription: String {
return "Vector2D(\(x), \(y)), magnitude: \(magnitude)"
}
public var hashValue: Int {
return x.hashValue ^ y.hashValue
}
public static let zero = Vector2D(0, 0)
public static let one = Vector2D(1, 1)
public static let left = Vector2D(-1, 0)
public static let right = Vector2D(1, 0)
public static let up = Vector2D(0, 1)
public static let down = Vector2D(0, -1)
}
public func == (left: Vector2D, right: Vector2D) -> Bool {
return (left.x == right.x) && (left.y == right.y)
}
public func + (left: Vector2D, right: Vector2D) -> Vector2D {
return Vector2D(left.x + right.x, left.y + right.y)
}
public func - (left: Vector2D, right: Vector2D) -> Vector2D {
return Vector2D(left.x - right.x, left.y - right.y)
}
public func += (inout left: Vector2D, right: Vector2D) {
left = left + right
}
public func -= (inout left: Vector2D, right: Vector2D) {
left = left - right
}
public func * (value: Double, vector: Vector2D) -> Vector2D {
return Vector2D(value * vector.x, value * vector.y)
}
public func * (vector: Vector2D, value: Double) -> Vector2D {
return value * vector
}
public prefix func - (vector: Vector2D) -> Vector2D {
return Vector2D(-vector.x, -vector.y)
}
public func dotProduct(vectorA: Vector2D, vectorB:Vector2D) -> Double {
return vectorA.x * vectorB.x + vectorA.y * vectorB.y
}
infix operator -* { associativity left }
public func -*(left: Vector2D, right:Vector2D) -> Double {
return dotProduct(left, vectorB: right)
}
public extension CGVector {
init (_ value: Vector2D) {
self.dx = CGFloat(value.x)
self.dy = CGFloat(value.y)
}
}
public prefix func ~ (vector: Vector2D) -> CGVector {
return CGVector(vector)
}
| 23d965418943e3eb29a7bbd739906d7b | 24.520408 | 100 | 0.62495 | false | false | false | false |
fiveagency/ios-five-persistence | refs/heads/master | FivePersistence/Tests/Extensions/UIImageTests.swift | mit | 1 | //
// UIImageTests.swift
// FivePersistence
//
// Created by Miran Brajsa on 30/09/16.
// Copyright © 2016 Five Agency. All rights reserved.
//
import CoreGraphics
import XCTest
@testable import FivePersistence
#if os(iOS)
class UIImageTests: XCTestCase {
fileprivate let keeper = Keeper()
}
// MARK: Asynchronous
extension UIImageTests {
func testThatImageIsCorrectlyStoredAndReadAsync() {
let dummyKey = "asyncImageTestKey"
guard let fiveIcon = UIImage(named: "FiveIcon40", in: Bundle(for: UIImageTests.self), compatibleWith: nil) else {
XCTFail("Unable to read image.")
return
}
let expectation = self.expectation(description: "Test that image is being saved and read correctly.")
keeper.save(image: fiveIcon, forKey: dummyKey) { [weak self] success, _, error in
if let error = error, !success {
XCTFail("Failed saving image with error: \(error.localizedDescription)")
}
self?.keeper.image(forKey: dummyKey) { readSuccess, readImage, readError in
if let readError = readError, !readSuccess {
XCTFail("Failed reading image with error: \(readError.localizedDescription)")
}
XCTAssert(readSuccess, "Unable to read saved image data.")
guard let readIcon = readImage else {
XCTFail("Unable to read image.")
return
}
let originalImageData = UIImagePNGRepresentation(fiveIcon)
let readImageData = UIImagePNGRepresentation(readIcon)
XCTAssert(originalImageData == readImageData, "Read image doesn't equal saved data.")
expectation.fulfill()
}
}
waitForExpectations(timeout: 1.0) { error in
print("Failed with error: \(error)")
}
}
}
// MARK: Synchronous
extension UIImageTests {
func testThatImageIsCorrectlyStoredAndReadSync() {
let dummyKey = "syncImageTestKey"
guard let fiveIcon = UIImage(named: "FiveIcon40", in: Bundle(for: UIImageTests.self), compatibleWith: nil) else {
XCTFail("Unable to read image.")
return
}
let (success, _, error) = keeper.save(image: fiveIcon, forKey: dummyKey)
if let error = error, !success {
XCTFail("Failed saving image with error: \(error.localizedDescription)")
}
let (readSuccess, readImage, readError) = keeper.image(forKey: dummyKey)
if let readError = readError, !readSuccess {
XCTFail("Failed reading image with error: \(readError.localizedDescription)")
}
XCTAssert(readSuccess, "Unable to read saved image data.")
guard let readIcon = readImage else {
XCTFail("Unable to read image.")
return
}
let originalImageData = UIImagePNGRepresentation(fiveIcon)
let readImageData = UIImagePNGRepresentation(readIcon)
XCTAssert(originalImageData == readImageData, "Read image doesn't equal saved data.")
}
}
#endif
| bee4e6401d005e34a40c0caffcf8c144 | 35.149425 | 121 | 0.623847 | false | true | false | false |
JGiola/swift-corelibs-foundation | refs/heads/master | TestFoundation/TestScanner.swift | apache-2.0 | 2 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
class TestScanner : XCTestCase {
static var allTests: [(String, (TestScanner) -> () throws -> Void)] {
return [
("test_scanInteger", test_scanInteger),
("test_scanFloat", test_scanFloat),
("test_scanString", test_scanString),
("test_charactersToBeSkipped", test_charactersToBeSkipped),
]
}
func test_scanInteger() {
let scanner = Scanner(string: "123")
var value: Int = 0
XCTAssert(scanner.scanInt(&value), "An Integer should be found in the string `123`.")
XCTAssertEqual(value, 123, "Scanned Integer value of the string `123` should be `123`.")
XCTAssertTrue(scanner.isAtEnd)
}
func test_scanFloat() {
let scanner = Scanner(string: "-350000000000000000000000000000000000000000")
var value: Float = 0
XCTAssert(scanner.scanFloat(&value), "A Float should be found in the string `-350000000000000000000000000000000000000000`.")
XCTAssert(value.isInfinite, "Scanned Float value of the string `-350000000000000000000000000000000000000000` should be infinite`.")
}
func test_scanString() {
let scanner = Scanner(string: "apple sauce")
guard let firstPart = scanner.scanString("apple ") else {
XCTFail()
return
}
XCTAssertEqual(firstPart, "apple ")
XCTAssertFalse(scanner.isAtEnd)
let _ = scanner.scanString("sauce")
XCTAssertTrue(scanner.isAtEnd)
}
func test_charactersToBeSkipped() {
let scanner = Scanner(string: "xyz ")
scanner.charactersToBeSkipped = .whitespaces
let _ = scanner.scanString("xyz")
XCTAssertTrue(scanner.isAtEnd)
}
}
| 15429fcb60d286ad1efbe5773977bdd0 | 34.931034 | 139 | 0.650192 | false | true | false | false |
shrtlist/UniversalDemo | refs/heads/master | UniversalDemo/AppDelegate.swift | apache-2.0 | 1 | /*
* Copyright 2020 [email protected]
*
* 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 UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
splitViewController.delegate = self
let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController
let controller = masterNavigationController.topViewController as! MasterViewController
controller.managedObjectContext = self.persistentContainer.viewContext
return true
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: Split view
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? EmployeeViewController else { return false }
if topAsDetailController.employee == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
// MARK: Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "UniversalDemo")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 78b22ea3b0ee1cc6405b190a7587824e | 48.712871 | 199 | 0.699462 | false | false | false | false |
coodly/ios-gambrinus | refs/heads/main | Packages/Sources/KioskCore/Persistence/Persistence+BeerStyles.swift | apache-2.0 | 1 | /*
* Copyright 2018 Coodly LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 CoreData
extension NSManagedObjectContext {
internal func update(styles: [CloudStyle]) {
let ids = styles.compactMap({ $0.rbId })
let predicate = NSPredicate(format: "identifier IN %@", ids)
let existing: [BeerStyle] = fetch(predicate: predicate)
for style in styles {
let saved: BeerStyle = existing.first(where: { $0.identifier == style.rbId }) ?? insertEntity()
saved.identifier = style.rbId
saved.name = style.name
saved.markForSync(needed: false)
guard let beers = saved.beers else {
return
}
for beer in beers {
guard let posts = beer.posts else {
continue
}
for post in posts {
post.isDirty = true
}
}
}
}
}
| 22e409c1e5e3bbffc207a31bafcd8145 | 31.122449 | 107 | 0.57751 | false | false | false | false |
einsteinx2/iSub | refs/heads/master | Carthage/Checkouts/XCGLogger/DemoApps/macOSDemo/macOSDemo/AppDelegate.swift | gpl-3.0 | 2 | //
// AppDelegate.swift
// XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
// Created by Dave Wood on 2014-06-06.
// Copyright © 2014 Dave Wood, Cerebral Gardens.
// Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
import Cocoa
import XCGLogger
let appDelegate = NSApplication.shared().delegate as! AppDelegate
let log: XCGLogger = {
// Setup XCGLogger (Advanced/Recommended Usage)
// Create a logger object with no destinations
let log = XCGLogger(identifier: "advancedLogger", includeDefaultDestinations: false)
// Create a destination for the system console log (via NSLog)
let systemDestination = AppleSystemLogDestination(identifier: "advancedLogger.appleSystemLogDestination")
// Optionally set some configuration options
systemDestination.outputLevel = .debug
systemDestination.showLogIdentifier = false
systemDestination.showFunctionName = true
systemDestination.showThreadName = true
systemDestination.showLevel = true
systemDestination.showFileName = true
systemDestination.showLineNumber = true
// Add colour to the console destination.
// - Note: You need the XcodeColors Plug-in https://github.com/robbiehanson/XcodeColors installed in Xcode
// - to see colours in the Xcode console. Plug-ins have been disabled in Xcode 8, so offically you can not see
// - coloured logs in Xcode 8.
//let xcodeColorsLogFormatter: XcodeColorsLogFormatter = XcodeColorsLogFormatter()
//xcodeColorsLogFormatter.colorize(level: .verbose, with: .lightGrey)
//xcodeColorsLogFormatter.colorize(level: .debug, with: .darkGrey)
//xcodeColorsLogFormatter.colorize(level: .info, with: .blue)
//xcodeColorsLogFormatter.colorize(level: .warning, with: .orange)
//xcodeColorsLogFormatter.colorize(level: .error, with: .red)
//xcodeColorsLogFormatter.colorize(level: .severe, with: .white, on: .red)
//systemDestination.formatters = [xcodeColorsLogFormatter]
// Add the destination to the logger
log.add(destination: systemDestination)
// Create a file log destination
let logPath: String = "/tmp/XCGLogger_macOSDemo.log"
let autoRotatingFileDestination = AutoRotatingFileDestination(writeToFile: logPath, identifier: "advancedLogger.fileDestination", shouldAppend: true,
maxFileSize: 1024 * 5, // 5k, not a good size for production (default is 1 megabyte)
maxTimeInterval: 60) // 1 minute, also not good for production (default is 10 minutes)
// Optionally set some configuration options
autoRotatingFileDestination.outputLevel = .debug
autoRotatingFileDestination.showLogIdentifier = false
autoRotatingFileDestination.showFunctionName = true
autoRotatingFileDestination.showThreadName = true
autoRotatingFileDestination.showLevel = true
autoRotatingFileDestination.showFileName = true
autoRotatingFileDestination.showLineNumber = true
autoRotatingFileDestination.showDate = true
autoRotatingFileDestination.targetMaxLogFiles = 10 // probably good for this demo and production, (default is 10, max is 255)
// Process this destination in the background
autoRotatingFileDestination.logQueue = XCGLogger.logQueue
// Add colour (using the ANSI format) to our file log, you can see the colour when `cat`ing or `tail`ing the file in Terminal on macOS
let ansiColorLogFormatter: ANSIColorLogFormatter = ANSIColorLogFormatter()
ansiColorLogFormatter.colorize(level: .verbose, with: .colorIndex(number: 244), options: [.faint])
ansiColorLogFormatter.colorize(level: .debug, with: .black)
ansiColorLogFormatter.colorize(level: .info, with: .blue, options: [.underline])
ansiColorLogFormatter.colorize(level: .warning, with: .red, options: [.faint])
ansiColorLogFormatter.colorize(level: .error, with: .red, options: [.bold])
ansiColorLogFormatter.colorize(level: .severe, with: .white, on: .red)
autoRotatingFileDestination.formatters = [ansiColorLogFormatter]
// Add the destination to the logger
log.add(destination: autoRotatingFileDestination)
// Add basic app info, version info etc, to the start of the logs
log.logAppDetails()
return log
}()
let dateHashFormatter: DateFormatter = {
let dateHashFormatter = DateFormatter()
dateHashFormatter.locale = NSLocale.current
dateHashFormatter.dateFormat = "yyyy-MM-dd_HHmmss_SSS"
return dateHashFormatter
}()
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
// MARK: - Properties
@IBOutlet var window: NSWindow!
@IBOutlet var logLevelTextField: NSTextField!
@IBOutlet var currentLogLevelTextField: NSTextField!
@IBOutlet var generateTestLogTextField: NSTextField!
@IBOutlet var logLevelSlider: NSSlider!
// MARK: - Life cycle methods
func applicationDidFinishLaunching(_ notification: Notification) {
// Insert code here to initialize your application
updateView()
}
func applicationWillTerminate(_ notification: Notification) {
// Insert code here to tear down your application
}
// MARK: - Main View
@IBAction func verboseButtonTouchUpInside(_ sender: AnyObject) {
log.verbose("Verbose button tapped")
log.verbose {
// add expensive code required only for logging, then return an optional String
return "Executed verbose code block" // or nil
}
}
@IBAction func debugButtonTouchUpInside(_ sender: AnyObject) {
log.debug("Debug button tapped")
log.debug {
// add expensive code required only for logging, then return an optional String
return "Executed debug code block" // or nil
}
}
@IBAction func infoButtonTouchUpInside(_ sender: AnyObject) {
log.info("Info button tapped")
log.info {
// add expensive code required only for logging, then return an optional String
return "Executed info code block" // or nil
}
}
@IBAction func warningButtonTouchUpInside(_ sender: AnyObject) {
log.warning("Warning button tapped")
log.warning {
// add expensive code required only for logging, then return an optional String
return "Executed warning code block" // or nil
}
}
@IBAction func errorButtonTouchUpInside(_ sender: AnyObject) {
log.error("Error button tapped")
log.error {
// add expensive code required only for logging, then return an optional String
return "Executed error code block" // or nil
}
}
@IBAction func severeButtonTouchUpInside(_ sender: AnyObject) {
log.severe("Severe button tapped")
log.severe {
// add expensive code required only for logging, then return an optional String
return "Executed severe code block" // or nil
}
}
@IBAction func rotateLogFileButtonTouchUpInside(_ sender: AnyObject) {
if let fileDestination = log.destination(withIdentifier: "advancedLogger.fileDestination") as? FileDestination {
let dateHash: String = dateHashFormatter.string(from: Date())
let archiveFilePath: String = ("~/Desktop/XCGLogger_Log_\(dateHash).txt" as NSString).expandingTildeInPath
fileDestination.rotateFile(to: archiveFilePath)
}
}
@IBAction func logLevelSliderValueChanged(_ sender: AnyObject) {
var logLevel: XCGLogger.Level = .verbose
if (0 <= logLevelSlider.floatValue && logLevelSlider.floatValue < 1) {
logLevel = .verbose
}
else if (1 <= logLevelSlider.floatValue && logLevelSlider.floatValue < 2) {
logLevel = .debug
}
else if (2 <= logLevelSlider.floatValue && logLevelSlider.floatValue < 3) {
logLevel = .info
}
else if (3 <= logLevelSlider.floatValue && logLevelSlider.floatValue < 4) {
logLevel = .warning
}
else if (4 <= logLevelSlider.floatValue && logLevelSlider.floatValue < 5) {
logLevel = .error
}
else if (5 <= logLevelSlider.floatValue && logLevelSlider.floatValue < 6) {
logLevel = .severe
}
else {
logLevel = .none
}
log.outputLevel = logLevel
updateView()
}
func updateView() {
logLevelSlider.floatValue = Float(log.outputLevel.rawValue)
currentLogLevelTextField.stringValue = "\(log.outputLevel)"
}
}
| 42845ddffc49ec3be030da06b8fc9c15 | 41.082524 | 153 | 0.687392 | false | false | false | false |
dsantosp12/DResume | refs/heads/master | Sources/App/Models/Language.swift | mit | 1 | //
// Language.swift
// App
//
// Created by Daniel Santos on 10/2/17.
//
import Vapor
import FluentProvider
import HTTP
final class Language: Model {
let storage = Storage()
var name: String
private var mLevel: Int
var level: Skill.Level {
get {
return Skill.Level(level: self.mLevel)
} set {
mLevel = newValue.rawValue
}
}
let userID: Identifier?
static let nameKey = "name"
static let levelKey = "level"
static let userIDKey = "user_id"
init(
name: String,
level: Int,
user: User
) {
self.name = name
self.userID = user.id
self.mLevel = level
self.level = Skill.Level(level: level)
}
required init(row: Row) throws {
self.name = try row.get(Language.nameKey)
self.mLevel = try row.get(Language.levelKey)
self.userID = try row.get(User.foreignIdKey)
self.level = Skill.Level(level: self.mLevel)
}
func makeRow() throws -> Row {
var row = Row()
try row.set(Language.nameKey, self.name)
try row.set(Language.levelKey, self.mLevel)
try row.set(User.foreignIdKey, self.userID)
return row
}
func update(with json: JSON) throws {
self.name = try json.get(Language.nameKey)
self.level = Skill.Level(level: try json.get(Language.levelKey))
try self.save()
}
}
// MARK: Relationship
extension Language {
var owner: Parent<Language, User> {
return parent(id: self.userID)
}
}
// MARK: JSON
extension Language: JSONConvertible {
convenience init(json: JSON) throws {
let userID: Identifier = try json.get(Language.userIDKey)
guard let user = try User.find(userID) else {
throw Abort.badRequest
}
try self.init(
name: json.get(Language.nameKey),
level: json.get(Language.levelKey),
user: user
)
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set(Language.idKey, self.id)
try json.set(Language.nameKey, self.name)
try json.set(Language.levelKey, self.level.rawValue)
try json.set(Language.userIDKey, self.userID)
return json
}
}
// MARK: HTTP
extension Language: ResponseRepresentable { }
extension Language: Preparation {
static func prepare(_ database: Database) throws {
try database.create(self) { builder in
builder.id()
builder.string(Language.nameKey)
builder.string(Language.levelKey)
builder.parent(User.self)
}
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
| 422e41e21d23872cf1288cebebbc7873 | 20.15 | 68 | 0.646572 | false | false | false | false |
22377832/swiftdemo | refs/heads/master | BitcoinSwift/Sources/3rd/CryptoSwift/BlockMode/OFB.swift | apache-2.0 | 13 | //
// OFB.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 08/03/16.
// Copyright © 2016 Marcin Krzyzanowski. All rights reserved.
//
// Output Feedback (OFB)
//
struct OFBModeWorker: BlockModeWorker {
typealias Element = Array<UInt8>
let cipherOperation: CipherOperationOnBlock
private let iv: Element
private var prev: Element?
init(iv: Array<UInt8>, cipherOperation: @escaping CipherOperationOnBlock) {
self.iv = iv
self.cipherOperation = cipherOperation
}
mutating func encrypt(_ plaintext: ArraySlice<UInt8>) -> Array<UInt8> {
guard let ciphertext = cipherOperation(prev ?? iv) else {
return Array(plaintext)
}
prev = ciphertext
return xor(plaintext, ciphertext)
}
mutating func decrypt(_ ciphertext: ArraySlice<UInt8>) -> Array<UInt8> {
guard let decrypted = cipherOperation(prev ?? iv) else {
return Array(ciphertext)
}
let plaintext = xor(decrypted, ciphertext)
self.prev = decrypted
return plaintext
}
}
| df43acf84df8465445f66bb435addb42 | 26.846154 | 79 | 0.64733 | false | false | false | false |
phillfarrugia/appstore-clone | refs/heads/master | AppStoreClone/CollectionViewCells/BaseRoundedCardCell.swift | mit | 1 | //
// BaseRoundedCardCell.swift
// AppStoreClone
//
// Created by Phillip Farrugia on 6/17/17.
// Copyright © 2017 Phill Farrugia. All rights reserved.
//
import UIKit
import CoreMotion
internal class BaseRoundedCardCell: UICollectionViewCell {
internal static let cellHeight: CGFloat = 470.0
private static let kInnerMargin: CGFloat = 20.0
/// Core Motion Manager
private let motionManager = CMMotionManager()
/// Long Press Gesture Recognizer
private var longPressGestureRecognizer: UILongPressGestureRecognizer? = nil
/// Is Pressed State
private var isPressed: Bool = false
/// Shadow View
private weak var shadowView: UIView?
override func awakeFromNib() {
super.awakeFromNib()
configureGestureRecognizer()
}
override func layoutSubviews() {
super.layoutSubviews()
configureShadow()
}
// MARK: - Shadow
private func configureShadow() {
// Shadow View
self.shadowView?.removeFromSuperview()
let shadowView = UIView(frame: CGRect(x: BaseRoundedCardCell.kInnerMargin,
y: BaseRoundedCardCell.kInnerMargin,
width: bounds.width - (2 * BaseRoundedCardCell.kInnerMargin),
height: bounds.height - (2 * BaseRoundedCardCell.kInnerMargin)))
insertSubview(shadowView, at: 0)
self.shadowView = shadowView
// Roll/Pitch Dynamic Shadow
if motionManager.isDeviceMotionAvailable {
motionManager.deviceMotionUpdateInterval = 0.02
motionManager.startDeviceMotionUpdates(to: .main, withHandler: { (motion, error) in
if let motion = motion {
let pitch = motion.attitude.pitch * 10 // x-axis
let roll = motion.attitude.roll * 10 // y-axis
self.applyShadow(width: CGFloat(roll), height: CGFloat(pitch))
}
})
}
}
private func applyShadow(width: CGFloat, height: CGFloat) {
if let shadowView = shadowView {
let shadowPath = UIBezierPath(roundedRect: shadowView.bounds, cornerRadius: 14.0)
shadowView.layer.masksToBounds = false
shadowView.layer.shadowRadius = 8.0
shadowView.layer.shadowColor = UIColor.black.cgColor
shadowView.layer.shadowOffset = CGSize(width: width, height: height)
shadowView.layer.shadowOpacity = 0.35
shadowView.layer.shadowPath = shadowPath.cgPath
}
}
// MARK: - Gesture Recognizer
private func configureGestureRecognizer() {
// Long Press Gesture Recognizer
longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture(gestureRecognizer:)))
longPressGestureRecognizer?.minimumPressDuration = 0.1
addGestureRecognizer(longPressGestureRecognizer!)
}
internal func handleLongPressGesture(gestureRecognizer: UILongPressGestureRecognizer) {
if gestureRecognizer.state == .began {
handleLongPressBegan()
} else if gestureRecognizer.state == .ended || gestureRecognizer.state == .cancelled {
handleLongPressEnded()
}
}
private func handleLongPressBegan() {
guard !isPressed else {
return
}
isPressed = true
UIView.animate(withDuration: 0.5,
delay: 0.0,
usingSpringWithDamping: 0.8,
initialSpringVelocity: 0.2,
options: .beginFromCurrentState,
animations: {
self.transform = CGAffineTransform(scaleX: 0.95, y: 0.95)
}, completion: nil)
}
private func handleLongPressEnded() {
guard isPressed else {
return
}
UIView.animate(withDuration: 0.5,
delay: 0.0,
usingSpringWithDamping: 0.4,
initialSpringVelocity: 0.2,
options: .beginFromCurrentState,
animations: {
self.transform = CGAffineTransform.identity
}) { (finished) in
self.isPressed = false
}
}
}
| f081813270243073d9d62ce4f80c6c2f | 33.484615 | 142 | 0.581753 | false | false | false | false |
JmoVxia/CLPlayer | refs/heads/master | CLPlayer/CLFullScreenController/CLAnimationTransitioning.swift | mit | 1 | //
// CLAnimationTransitioning.swift
// CLPlayer
//
// Created by Chen JmoVxia on 2021/10/27.
//
import SnapKit
import UIKit
extension CLAnimationTransitioning {
enum CLAnimationType {
case present
case dismiss
}
enum CLAnimationOrientation {
case left
case right
case fullRight
}
}
class CLAnimationTransitioning: NSObject {
private let keyWindow: UIWindow? = {
if #available(iOS 13.0, *) {
return UIApplication.shared.windows.filter { $0.isKeyWindow }.last
} else {
return UIApplication.shared.keyWindow
}
}()
private weak var player: CLPlayer?
private weak var parentView: UIView?
private var centerInParent: CGPoint = .zero
private var originSize: CGSize = .zero
private var orientation: CLAnimationOrientation = .left
var animationType: CLAnimationType = .present
init(playView: CLPlayer, orientation: CLAnimationOrientation) {
player = playView
self.orientation = orientation
parentView = playView.superview
centerInParent = playView.center
originSize = playView.frame.size
}
}
extension CLAnimationTransitioning: UIViewControllerAnimatedTransitioning {
func transitionDuration(using _: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.25
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let playView = player else { return }
if animationType == .present {
guard let toView = transitionContext.view(forKey: .to) else { return }
guard let fromController = transitionContext.viewController(forKey: .from) else { return }
let fromCenter = transitionContext.containerView.convert(playView.center, from: playView.superview)
let fromSize = transitionContext.containerView.convert(playView.frame, from: nil).size
transitionContext.containerView.addSubview(toView)
toView.addSubview(playView)
if orientation == .left,
!(fromController.shouldAutorotate && fromController.supportedInterfaceOrientations.contains(.landscapeLeft))
{
toView.transform = .init(rotationAngle: -Double.pi * 0.5)
} else if orientation == .right,
!(fromController.shouldAutorotate && fromController.supportedInterfaceOrientations.contains(.landscapeRight))
{
toView.transform = .init(rotationAngle: Double.pi * 0.5)
} else if orientation == .fullRight {
toView.transform = .init(rotationAngle: -Double.pi * 0.5)
}
toView.snp.remakeConstraints { make in
make.center.equalTo(fromCenter)
make.size.equalTo(fromSize)
}
playView.snp.remakeConstraints { make in
make.edges.equalToSuperview()
}
transitionContext.containerView.setNeedsLayout()
transitionContext.containerView.layoutIfNeeded()
toView.snp.updateConstraints { make in
make.center.equalTo(transitionContext.containerView.center)
make.size.equalTo(transitionContext.containerView.bounds.size)
}
if #available(iOS 11.0, *) {
playView.contentView.animationLayout(safeAreaInsets: keyWindow?.safeAreaInsets ?? .zero, to: .fullScreen)
} else {
playView.contentView.animationLayout(safeAreaInsets: .zero, to: .fullScreen)
}
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: .layoutSubviews, animations: {
toView.transform = .identity
transitionContext.containerView.setNeedsLayout()
transitionContext.containerView.layoutIfNeeded()
playView.contentView.setNeedsLayout()
playView.contentView.layoutIfNeeded()
}) { _ in
toView.transform = .identity
transitionContext.completeTransition(true)
UIViewController.attemptRotationToDeviceOrientation()
}
} else {
guard let parentView = parentView else { return }
guard let fromView = transitionContext.view(forKey: .from) else { return }
guard let toView = transitionContext.view(forKey: .to) else { return }
toView.frame = transitionContext.containerView.bounds
let fromCenter = CGPoint(x: toView.frame.width * 0.5, y: toView.frame.height * 0.5)
let fromSize = transitionContext.containerView.convert(playView.frame, from: nil).size
transitionContext.containerView.addSubview(toView)
transitionContext.containerView.addSubview(fromView)
fromView.addSubview(playView)
fromView.snp.remakeConstraints { make in
make.center.equalTo(fromCenter)
make.size.equalTo(fromSize)
}
playView.snp.remakeConstraints { make in
make.edges.equalToSuperview()
}
transitionContext.containerView.setNeedsLayout()
transitionContext.containerView.layoutIfNeeded()
let center = transitionContext.containerView.convert(centerInParent, from: parentView)
fromView.snp.updateConstraints { make in
make.center.equalTo(center)
make.size.equalTo(originSize)
}
playView.contentView.animationLayout(safeAreaInsets: .zero, to: .small)
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, options: .layoutSubviews, animations: {
fromView.transform = .identity
transitionContext.containerView.setNeedsLayout()
transitionContext.containerView.layoutIfNeeded()
playView.contentView.setNeedsLayout()
playView.contentView.layoutIfNeeded()
}) { _ in
fromView.transform = .identity
parentView.addSubview(playView)
playView.snp.remakeConstraints { make in
make.center.equalTo(self.centerInParent)
make.size.equalTo(self.originSize)
}
fromView.removeFromSuperview()
transitionContext.completeTransition(true)
UIViewController.attemptRotationToDeviceOrientation()
}
}
}
}
| 8bde48955d46ba19a1ead05f1ff6b471 | 39.323171 | 138 | 0.632088 | false | false | false | false |
KevinCoble/AIToolbox | refs/heads/master | AIToolbox/MLView.swift | apache-2.0 | 1 | import Cocoa
public enum MLViewError: Error {
case dataSetNotRegression
case dataSetNotClassification
case inputVectorNotOfCorrectSize
case inputIndexOutsideOfRange
case outputIndexOutsideOfRange
case allClassificationLabelsNotCovered
}
public enum MLViewAxisSource {
case dataInput
case dataOutput
case classLabel // Ignores index
}
public enum MLPlotSymbolShape {
case circle
case rectangle
case plus
case minus
}
public enum MLViewLegendLocation {
case upperLeft
case upperRight
case lowerLeft
case lowerRight
case custom
}
/// Class for symbols showing locations on the plot
open class MLPlotSymbol {
// Symbol information
open var symbolColor: NSColor
open var symbolSize: CGFloat = 7.0
open var symbolShape: MLPlotSymbolShape = .circle
public init(color: NSColor) {
symbolColor = color
}
public convenience init(color: NSColor, symbolShape: MLPlotSymbolShape, symbolSize: CGFloat) {
self.init(color: color)
self.symbolShape = symbolShape
self.symbolSize = symbolSize
}
open func drawAt(_ point: CGPoint) {
// Set the color
symbolColor.set()
switch (symbolShape) {
case .circle:
let circleRect = NSMakeRect(point.x - (symbolSize * 0.5), point.y - (symbolSize * 0.5), symbolSize, symbolSize)
let cPath: NSBezierPath = NSBezierPath(ovalIn: circleRect)
cPath.fill()
case .rectangle:
let rect = NSMakeRect(point.x - (symbolSize * 0.5), point.y - (symbolSize * 0.5), symbolSize, symbolSize)
NSRectFill(rect)
case .plus:
let hrect = NSMakeRect(point.x - (symbolSize * 0.5), point.y - (symbolSize * 0.1), symbolSize, symbolSize * 0.2)
NSRectFill(hrect)
let vrect = NSMakeRect(point.x - (symbolSize * 0.1), point.y - (symbolSize * 0.5), symbolSize * 0.2, symbolSize)
NSRectFill(vrect)
case .minus:
let rect = NSMakeRect(point.x - (symbolSize * 0.5), point.y - (symbolSize * 0.1), symbolSize, symbolSize * 0.2)
NSRectFill(rect)
}
}
}
public protocol MLViewItem {
func setColor(_ color: NSColor) // Sets the default color for the item
func setScale(_ scale: (minX: Double, maxX: Double, minY: Double, maxY: Double)) // Sets the scale to the provided factors, or the item can calculate it's own
func draw(_ bounds: CGRect)
func getScale() -> (minX: Double, maxX: Double, minY: Double, maxY: Double)? // Return the scale factors used by the item
func setInputVector(_ vector: [Double]) throws // Set the input vector used to get values. Plot variable index (if used) is ignored
func setXAxisSource(_ source: MLViewAxisSource, index: Int) throws
func setYAxisSource(_ source: MLViewAxisSource, index: Int) throws
}
/// Class for drawing a regression style data set onto a plot
open class MLViewRegressionDataSet: MLViewItem {
// DataSet to be drawn
let dataset : MLRegressionDataSet
// Axis data source
var sourceTypeXAxis = MLViewAxisSource.dataInput
var sourceIndexXAxis = 0
var sourceTypeYAxis = MLViewAxisSource.dataOutput
var sourceIndexYAxis = 0
// Scale parameters
open var scaleToData = true
open var roundScales = true
// Symbol information
open var symbol = MLPlotSymbol(color: NSColor.green)
// Axis scaling ranges
var minX = 0.0
var maxX = 100.0
var minY = 0.0
var maxY = 100.0
public init(dataset: MLRegressionDataSet) throws {
if (dataset.dataType != .regression) {throw MLViewError.dataSetNotRegression}
self.dataset = dataset
}
public convenience init(dataset: DataSet, color: NSColor) throws {
try self.init(dataset: dataset)
setColor(color)
}
public convenience init(dataset: DataSet, symbol: MLPlotSymbol) throws {
try self.init(dataset: dataset)
self.symbol = symbol
}
open func scaleToData(_ calculateScale : Bool) {
scaleToData = calculateScale
}
open func setColor(_ color: NSColor) // Sets the default color for the item
{
symbol.symbolColor = color
}
open func setScale(_ scale: (minX: Double, maxX: Double, minY: Double, maxY: Double)) {
// Store the scale to be used
minX = scale.minX
maxX = scale.maxX
minY = scale.minY
maxY = scale.maxY
}
open func draw(_ bounds: CGRect) {
// Get the scaling factors
let scaleFactorX = CGFloat(1.0 / (maxX - minX))
let scaleFactorY = CGFloat(1.0 / (maxY - minY))
// Iterate through each point
do {
for point in 0..<dataset.size {
// Get the source of the X axis value
var x_source : [Double]
if (sourceTypeXAxis == .dataInput) {
x_source = try dataset.getInput(point)
}
else {
x_source = try dataset.getOutput(point)
}
// Get the source of the Y axis value
var y_source : [Double]
if (sourceTypeYAxis == .dataInput) {
y_source = try dataset.getInput(point)
}
else {
y_source = try dataset.getOutput(point)
}
// Calculate the plot position and draw
let x = (CGFloat(x_source[sourceIndexXAxis] - minX) * scaleFactorX) * bounds.width + bounds.origin.x
let y = (CGFloat(y_source[sourceIndexYAxis] - minY) * scaleFactorY) * bounds.height + bounds.origin.y
symbol.drawAt(CGPoint(x: x, y: y))
}
}
catch {
// Skip this dataset
}
}
open func getScale() -> (minX: Double, maxX: Double, minY: Double, maxY: Double)? {
// If we are scaling to the data, determine the scale factors now
if (scaleToData) {
// Get the source of the X axis range
var x_range : [(minimum: Double, maximum: Double)]
if (sourceTypeXAxis == .dataInput) {
x_range = dataset.getInputRange()
}
else {
x_range = dataset.getOutputRange()
}
// Get the x axis range
if (roundScales) {
let x_scale = MLView.roundScale(x_range[sourceIndexXAxis].minimum, max: x_range[sourceIndexXAxis].maximum)
minX = x_scale.min
maxX = x_scale.max
}
else {
minY = x_range[sourceIndexXAxis].minimum
maxY = x_range[sourceIndexXAxis].maximum
}
// Get the source of the Y axis range
var y_range : [(minimum: Double, maximum: Double)]
if (sourceTypeYAxis == .dataInput) {
y_range = dataset.getInputRange()
}
else {
y_range = dataset.getOutputRange()
}
// Get the y axis range
if (roundScales) {
let y_scale = MLView.roundScale(y_range[sourceIndexYAxis].minimum, max: y_range[sourceIndexYAxis].maximum)
minY = y_scale.min
maxY = y_scale.max
}
else {
minY = y_range[sourceIndexYAxis].minimum
maxY = y_range[sourceIndexYAxis].maximum
}
}
return (minX: minX, maxX: maxX, minY: minY, maxY: maxY)
}
open func setInputVector(_ vector: [Double]) throws {
// Not needed for a data set
}
open func setXAxisSource(_ source: MLViewAxisSource, index: Int) throws {
switch (source) {
case .dataInput:
if (index > dataset.inputDimension) { throw MLViewError.inputIndexOutsideOfRange }
case .dataOutput:
if (dataset.dataType != .regression) { throw MLViewError.dataSetNotRegression }
if (index > dataset.outputDimension) { throw MLViewError.outputIndexOutsideOfRange }
case .classLabel: // Ignores index
throw MLViewError.dataSetNotClassification
}
sourceTypeXAxis = source
sourceIndexXAxis = index
}
open func setYAxisSource(_ source: MLViewAxisSource, index: Int) throws {
switch (source) {
case .dataInput:
if (index > dataset.inputDimension) { throw MLViewError.inputIndexOutsideOfRange }
case .dataOutput:
if (dataset.dataType != .regression) { throw MLViewError.dataSetNotRegression }
if (index > dataset.outputDimension) { throw MLViewError.outputIndexOutsideOfRange }
case .classLabel: // Ignores index
throw MLViewError.dataSetNotClassification
}
sourceTypeYAxis = source
sourceIndexYAxis = index
}
}
/// Class for drawing a classification style data set onto a plot
open class MLViewClassificationDataSet: MLViewItem {
// DataSet to be drawn
var dataset : MLClassificationDataSet
// Axis data source
var sourceTypeXAxis = MLViewAxisSource.dataInput
var sourceIndexXAxis = 0
var sourceTypeYAxis = MLViewAxisSource.dataInput
var sourceIndexYAxis = 1
// Scale parameters
open var scaleToData = true
open var roundScales = true
// Symbol information
open var symbols : [MLPlotSymbol]
// Axis scaling ranges
var minX = 0.0
var maxX = 100.0
var minY = 0.0
var maxY = 100.0
public init(dataset: MLClassificationDataSet) throws {
if (dataset.dataType != .classification) {throw MLViewError.dataSetNotClassification}
self.dataset = dataset
// Get the classes
let optionalData = try dataset.groupClasses()
self.dataset.optionalData = optionalData
// Set a symbol for each of them
symbols = []
let colors = [
NSColor.green,
NSColor.red,
NSColor.blue,
NSColor.cyan,
NSColor.magenta,
NSColor.yellow,
NSColor.gray,
NSColor.black
]
let shapes = [
MLPlotSymbolShape.circle,
MLPlotSymbolShape.rectangle,
MLPlotSymbolShape.plus,
MLPlotSymbolShape.minus
]
var colorIndex = 0
var shapeIndex = 0
var size : CGFloat = 6.0
for _ in 0..<optionalData.numClasses {
symbols.append(MLPlotSymbol(color: colors[colorIndex], symbolShape: shapes[shapeIndex], symbolSize: size))
colorIndex += 1
if (colorIndex >= colors.count) {
colorIndex = 0
shapeIndex += 1
if (shapeIndex >= shapes.count) {
shapeIndex = 0
size += 2.0
}
}
}
}
public convenience init(dataset: DataSet, symbols: [MLPlotSymbol]) throws {
try self.init(dataset: dataset)
let optionalData = try dataset.groupClasses()
dataset.optionalData = optionalData
if (symbols.count < optionalData.numClasses) {throw MLViewError.allClassificationLabelsNotCovered}
self.symbols = symbols
}
// Sets ALL symbols to the specified color
open func setColor(_ color: NSColor) // Sets the default color for the item
{
for symbol in symbols {
symbol.symbolColor = color
}
}
open func scaleToData(_ calculateScale : Bool) {
scaleToData = calculateScale
}
open func setScale(_ scale: (minX: Double, maxX: Double, minY: Double, maxY: Double)) {
// Store the scale to be used
minX = scale.minX
maxX = scale.maxX
minY = scale.minY
maxY = scale.maxY
}
open func draw(_ bounds: CGRect) {
// Get the classes
do {
let optionalData = try dataset.groupClasses()
dataset.optionalData = optionalData
}
catch {
// Error getting class information for data set, return
return
}
let optionalData = dataset.optionalData as! ClassificationData
// Get the scaling factors
let scaleFactorX = CGFloat(1.0 / (maxX - minX))
let scaleFactorY = CGFloat(1.0 / (maxY - minY))
// Iterate through each point
do {
for point in 0..<dataset.size {
// Get the source of the X axis value
var x_source : [Double]
if (sourceTypeXAxis == .dataInput) {
x_source = try dataset.getInput(point)
}
else {
let pointClass = try dataset.getClass(point)
x_source = [Double(pointClass)]
}
// Get the source of the Y axis value
var y_source : [Double]
if (sourceTypeYAxis == .dataInput) {
y_source = try dataset.getInput(point)
}
else {
let pointClass = try dataset.getClass(point)
y_source = [Double(pointClass)]
}
// Calculate the plot position
let x = (CGFloat(x_source[sourceIndexXAxis] - minX) * scaleFactorX) * bounds.width + bounds.origin.x
let y = (CGFloat(y_source[sourceIndexYAxis] - minY) * scaleFactorY) * bounds.height + bounds.origin.y
// Get the label index
do {
let label = try dataset.getClass(point)
var labelIndex = 0
for i in 0..<optionalData.numClasses {
if (label == optionalData.foundLabels[i]) {
labelIndex = i
break
}
}
symbols[labelIndex].drawAt(CGPoint(x: x, y: y))
}
catch {
// Skip this point if an error getting the label
}
}
}
catch {
// Skip this dataset
}
}
open func getScale() -> (minX: Double, maxX: Double, minY: Double, maxY: Double)? {
// If we are scaling to the data, determine the scale factors now
if (scaleToData) {
// Get the source of the X axis range
var x_range : [(minimum: Double, maximum: Double)]
if (sourceTypeXAxis == .dataInput) {
x_range = dataset.getInputRange()
}
else {
do {
let classificationData = try dataset.groupClasses()
x_range = [(minimum: 0.0, maximum: Double(classificationData.numClasses-1))]
}
catch {
// Error getting classification data
x_range = [(minimum: 0.0, maximum: 1.0)]
}
}
// Get the x axis range
if (roundScales) {
let x_scale = MLView.roundScale(x_range[sourceIndexXAxis].minimum, max: x_range[sourceIndexXAxis].maximum)
minX = x_scale.min
maxX = x_scale.max
}
else {
minY = x_range[sourceIndexXAxis].minimum
maxY = x_range[sourceIndexXAxis].maximum
}
// Get the source of the Y axis range
var y_range : [(minimum: Double, maximum: Double)]
if (sourceTypeYAxis == .dataInput) {
y_range = dataset.getInputRange()
}
else {
do {
let classificationData = try dataset.groupClasses()
y_range = [(minimum: 0.0, maximum: Double(classificationData.numClasses-1))]
}
catch {
// Error getting classification data
y_range = [(minimum: 0.0, maximum: 1.0)]
}
}
// Get the y axis range
if (roundScales) {
let y_scale = MLView.roundScale(y_range[sourceIndexYAxis].minimum, max: y_range[sourceIndexYAxis].maximum)
minY = y_scale.min
maxY = y_scale.max
}
else {
minY = y_range[sourceIndexYAxis].minimum
maxY = y_range[sourceIndexYAxis].maximum
}
}
return (minX: minX, maxX: maxX, minY: minY, maxY: maxY)
}
open func setInputVector(_ vector: [Double]) throws {
// Not needed for a data set
}
open func setXAxisSource(_ source: MLViewAxisSource, index: Int) throws {
switch (source) {
case .dataInput:
if (index > dataset.inputDimension) { throw MLViewError.inputIndexOutsideOfRange }
case .dataOutput:
throw MLViewError.dataSetNotRegression
case .classLabel: // Ignores index
if (index > 0) { throw MLViewError.outputIndexOutsideOfRange }
}
sourceTypeXAxis = source
sourceIndexXAxis = index
}
open func setYAxisSource(_ source: MLViewAxisSource, index: Int) throws {
switch (source) {
case .dataInput:
if (index > dataset.inputDimension) { throw MLViewError.inputIndexOutsideOfRange }
case .dataOutput:
throw MLViewError.dataSetNotRegression
case .classLabel: // Ignores index
if (index > 0) { throw MLViewError.outputIndexOutsideOfRange }
}
sourceTypeYAxis = source
sourceIndexYAxis = index
}
}
/// Class for drawing a regression line
open class MLViewRegressionLine: MLViewItem {
// Regression line to be drawn
let regressor : Regressor
// Axis data source
var sourceTypeXAxis = MLViewAxisSource.dataInput
var sourceIndexXAxis = 0
var sourceTypeYAxis = MLViewAxisSource.dataOutput
var sourceIndexYAxis = 0
var inputVector : [Double] = []
// Line information
open var lineColor = NSColor.red
open var lineThickness : CGFloat = 1.0
// Axis scaling ranges
var minX = 0.0
var maxX = 100.0
var minY = 0.0
var maxY = 100.0
public init(regressor: Regressor) {
self.regressor = regressor
inputVector = [Double](repeating: 0.0, count: regressor.getInputDimension())
}
public convenience init(regressor: Regressor, color: NSColor) {
self.init(regressor: regressor)
setColor(color)
}
open func setColor(_ color: NSColor) // Sets the default color for the item
{
lineColor = color
}
open func setScale(_ scale: (minX: Double, maxX: Double, minY: Double, maxY: Double)) {
// Store the scale
minX = scale.minX
maxX = scale.maxX
minY = scale.minY
maxY = scale.maxY
}
open func draw(_ bounds: CGRect) {
// Save the current state
NSGraphicsContext.saveGraphicsState()
// Set a clip region - the lines aren't usually with the bounds
NSRectClip(bounds)
// Get the scaling factors
let scaleFactorX = CGFloat(1.0 / (maxX - minX))
let scaleFactorY = CGFloat(1.0 / (maxY - minY))
// Set the color
lineColor.setStroke()
// Get the pixel granularity
let pixelX = (maxX - minX) / Double(bounds.width)
let path = NSBezierPath()
path.lineWidth = lineThickness
do {
// Get the first pixel
var xIterator = minX - (pixelX * 0.5)
var inputs = inputVector
if (sourceTypeXAxis == .dataInput) {
inputs[sourceIndexXAxis] = xIterator
}
let outputs = try regressor.predictOne(inputs)
// Get the X axis value
var xValue : Double
if (sourceTypeXAxis == .dataInput) {
xValue = inputs[sourceIndexXAxis]
}
else {
xValue = outputs[sourceIndexXAxis]
}
// Get the Y axis value
var yValue : Double
if (sourceTypeYAxis == .dataInput) {
yValue = inputs[sourceIndexYAxis]
}
else {
yValue = outputs[sourceIndexYAxis]
}
// Get the point coordinates
let x = (CGFloat(xValue - minX) * scaleFactorX) * bounds.width + bounds.origin.x
let y = (CGFloat(yValue - minY) * scaleFactorY) * bounds.height + bounds.origin.y
path.move(to: CGPoint(x: x, y: y))
// Iterate through each pixel
while (xIterator < maxX) {
inputs = inputVector
if (sourceTypeXAxis == .dataInput) {
inputs[sourceIndexXAxis] = xIterator
}
let outputs = try regressor.predictOne(inputs)
// Get the X axis value
if (sourceTypeXAxis == .dataInput) {
xValue = inputs[sourceIndexXAxis]
}
else {
xValue = outputs[sourceIndexXAxis]
}
// Get the Y axis value
if (sourceTypeYAxis == .dataInput) {
yValue = inputs[sourceIndexYAxis]
}
else {
yValue = outputs[sourceIndexYAxis]
}
// Get the point coordinates
let x = (CGFloat(xValue - minX) * scaleFactorX) * bounds.width + bounds.origin.x
let y = (CGFloat(yValue - minY) * scaleFactorY) * bounds.height + bounds.origin.y
xIterator += pixelX
path.line(to: CGPoint(x: x, y: y))
}
// Draw the line
path.stroke()
}
catch {
// Skip this regressor
}
// Restore the current state
NSGraphicsContext.restoreGraphicsState()
}
open func getScale() -> (minX: Double, maxX: Double, minY: Double, maxY: Double)? {
return nil
}
open func setInputVector(_ vector: [Double]) throws {
if (regressor.getInputDimension() > vector.count) { throw MLViewError.inputVectorNotOfCorrectSize}
inputVector = vector
}
open func setXAxisSource(_ source: MLViewAxisSource, index: Int) throws {
switch (source) {
case .dataInput:
if (index > regressor.getInputDimension()) { throw MLViewError.inputIndexOutsideOfRange }
case .dataOutput:
if (index > regressor.getOutputDimension()) { throw MLViewError.outputIndexOutsideOfRange }
case .classLabel: // Ignores index
throw MLViewError.dataSetNotClassification
}
sourceTypeXAxis = source
sourceIndexXAxis = index
}
open func setYAxisSource(_ source: MLViewAxisSource, index: Int) throws {
switch (source) {
case .dataInput:
if (index > regressor.getInputDimension()) { throw MLViewError.inputIndexOutsideOfRange }
case .dataOutput:
if (index > regressor.getOutputDimension()) { throw MLViewError.outputIndexOutsideOfRange }
case .classLabel: // Ignores index
throw MLViewError.dataSetNotClassification
}
sourceTypeYAxis = source
sourceIndexYAxis = index
}
}
/// Class for drawing a classification area onto a plot
open class MLViewClassificationArea: MLViewItem {
// Classifier to be drawn
let classifier : Classifier
// Axis data source
var sourceTypeXAxis = MLViewAxisSource.dataInput
var sourceIndexXAxis = 0
var sourceTypeYAxis = MLViewAxisSource.dataInput
var sourceIndexYAxis = 1
var inputVector : [Double] = []
// Label color information
open var unknownColor = NSColor.white
open var colors : [NSColor]
open var granularity = 4 /// Size of 'pixels' area is drawn in
// Axis scaling ranges
var minX = 0.0
var maxX = 100.0
var minY = 0.0
var maxY = 100.0
public init(classifier: Classifier) {
self.classifier = classifier
let startColors = [
NSColor.green,
NSColor.red,
NSColor.blue,
NSColor.cyan,
NSColor.magenta,
NSColor.yellow,
NSColor.gray,
NSColor.black
]
let numClasses = classifier.getNumberOfClasses()
colors = []
var colorIndex = 0
var fadeValue : CGFloat = 0.5
for _ in 0..<numClasses {
let red = (1.0 - startColors[colorIndex].redComponent) * fadeValue + startColors[colorIndex].redComponent
let green = (1.0 - startColors[colorIndex].greenComponent) * fadeValue + startColors[colorIndex].greenComponent
let blue = (1.0 - startColors[colorIndex].blueComponent) * fadeValue + startColors[colorIndex].blueComponent
let color = NSColor(red: red, green: green, blue: blue, alpha: 1.0)
colors.append(color)
colorIndex += 1
if (colorIndex >= startColors.count) {
colorIndex = 0
fadeValue += (1.0 - fadeValue) * 0.5
}
}
inputVector = [Double](repeating: 0.0, count: classifier.getInputDimension())
}
// Convenience constructor to create plot object and set colors for the classification labels
public convenience init(classifier: Classifier, colors: [NSColor]) {
self.init(classifier: classifier)
self.colors = colors
}
open func setColor(_ color: NSColor) // Sets the default color for the item
{
unknownColor = color
}
open func setScale(_ scale: (minX: Double, maxX: Double, minY: Double, maxY: Double)) {
// Store the scale
minX = scale.minX
maxX = scale.maxX
minY = scale.minY
maxY = scale.maxY
}
open func draw(_ bounds: CGRect) {
// draw the 'other' color
unknownColor.setFill()
NSRectFill(bounds)
// Get the scaling factors
let scaleFactorX = CGFloat(1.0 / (maxX - minX))
let scaleFactorY = CGFloat(1.0 / (maxY - minY))
// Get the pixel granularity
var grainWidth : CGFloat
var grainHeight : CGFloat
if (granularity == 0) {
grainWidth = 0.5
grainHeight = 0.5
}
else {
grainWidth = CGFloat(granularity)
grainHeight = CGFloat(granularity)
}
let pixelX = (maxX - minX) * Double(grainWidth) / Double(bounds.width)
let pixelY = (maxY - minY) * Double(grainWidth) / Double(bounds.height)
do {
// Get the first pixel
var xIterator = minX
// Iterate through each pixel
while (xIterator < maxX) {
var yIterator = minY
// Iterate through each pixel
while (yIterator < maxY) {
// Get the rectangle start coordinates
let x = (CGFloat(xIterator - minX) * scaleFactorX) * bounds.width + bounds.origin.x
let y = (CGFloat(yIterator - minY) * scaleFactorY) * bounds.height + bounds.origin.y
// Get the rectangle
let rect = CGRect(x: x, y: y, width: grainWidth, height: grainHeight)
// Get the class
var inputs = inputVector
if (sourceTypeXAxis == .dataInput) {
inputs[sourceIndexXAxis] = xIterator + (pixelX * 0.5)
}
if (sourceTypeYAxis == .dataInput) {
inputs[sourceIndexYAxis] = yIterator + (pixelY * 0.5)
}
let label = try classifier.classifyOne(inputs)
// Get the label index
//!! May need to look into adding label list to classifier
// var labelIndex = 0
// for i in 0..<optionalData.numClasses {
// if (label == optionalData.foundLabels[i]) {
// labelIndex = i
// break
// }
// }
// Set the color
if (label >= 0 && label < colors.count) {
colors[label].set()
// Fill the rectangle
let bp = NSBezierPath(rect: rect)
bp.fill()
bp.stroke()
}
yIterator += pixelY
}
xIterator += pixelX
}
}
catch {
// Skip this classifier
}
}
open func getScale() -> (minX: Double, maxX: Double, minY: Double, maxY: Double)? {
return nil
}
open func setInputVector(_ vector: [Double]) throws {
if (classifier.getInputDimension() > vector.count) { throw MLViewError.inputVectorNotOfCorrectSize}
inputVector = vector
}
open func setXAxisSource(_ source: MLViewAxisSource, index: Int) throws {
switch (source) {
case .dataInput:
if (index > classifier.getInputDimension()) { throw MLViewError.inputIndexOutsideOfRange }
case .dataOutput:
throw MLViewError.dataSetNotRegression
case .classLabel: // Ignores index
break
}
sourceTypeXAxis = source
sourceIndexXAxis = index
}
open func setYAxisSource(_ source: MLViewAxisSource, index: Int) throws {
switch (source) {
case .dataInput:
if (index > classifier.getInputDimension()) { throw MLViewError.inputIndexOutsideOfRange }
case .dataOutput:
throw MLViewError.dataSetNotRegression
case .classLabel: // Ignores index
break
}
sourceTypeYAxis = source
sourceIndexYAxis = index
}
}
/// Class for showing axis labels
open class MLViewAxisLabel: MLViewItem {
open var showXAxis : Bool
open var showYAxis : Bool
// Drawing offset
var xOffset : CGFloat = 0.0
var yOffset : CGFloat = 0.0
var xAxisHeight : CGFloat = 0.0
var yAxisWidth : CGFloat = 0.0
// Axis scaling ranges
var minX = 0.0
var maxX = 100.0
var minY = 0.0
var maxY = 100.0
// Axis appearance
open var XAxisColor = NSColor.gray
open var YAxisColor = NSColor.gray
open var MajorTickDivisions = 5
open var MinorTicksDivisionsPerMajorTick = 5
open var XAxisMajorTickHeight : CGFloat = 6.0
open var XAxisMinorTickHeight : CGFloat = 3.0
open var YAxisMajorTickWidth : CGFloat = 6.0
open var YAxisMinorTickWidth : CGFloat = 3.0
open var labelFont = NSFont(name: "Helvetica Neue", size: 10.0)
open var XAxisLabelDecimalDigits = 2
open var YAxisLabelDecimalDigits = 2
// Internal draw variables
var xLabelHeight : CGFloat = 0.0
var yMaxLabelWidth : CGFloat = 0.0
public init(showX: Bool, showY: Bool) {
showXAxis = showX
showYAxis = showY
}
open func setOffsets(_ x: CGFloat, y: CGFloat) {
xOffset = x
yOffset = y
}
open func setColor(_ color: NSColor) {
XAxisColor = color
YAxisColor = color
}
open func setScale(_ scale: (minX: Double, maxX: Double, minY: Double, maxY: Double)) {
// Store the scale
minX = scale.minX
maxX = scale.maxX
minY = scale.minY
maxY = scale.maxY
}
open func draw(_ bounds: CGRect) {
if (showXAxis) {
// Get the label font attributes
let labelParaStyle = NSMutableParagraphStyle()
labelParaStyle.lineSpacing = 0.0
labelParaStyle.alignment = NSTextAlignment.center
let labelAttributes = [
NSForegroundColorAttributeName: XAxisColor,
NSParagraphStyleAttributeName: labelParaStyle,
NSFontAttributeName: labelFont!
] as [String : Any]
let format = String(format: "%%.%df", XAxisLabelDecimalDigits)
XAxisColor.set()
let path = NSBezierPath()
let yPos = yOffset + xLabelHeight + 2.0
path.move(to: CGPoint(x: bounds.origin.x, y: yPos))
path.line(to: CGPoint(x: bounds.origin.x + bounds.width, y: yPos))
path.stroke()
for i in 0...MajorTickDivisions {
let xpos = bounds.width * CGFloat(i) / CGFloat(MajorTickDivisions) + bounds.origin.x
path.removeAllPoints()
path.move(to: CGPoint(x: xpos, y: yPos))
path.line(to: CGPoint(x: xpos, y: yPos + XAxisMajorTickHeight))
path.stroke()
let value = (maxX - minX) * Double(i) / Double(MajorTickDivisions) + minX
let label = String(format: format, value)
let labelSize = label.size(withAttributes: labelAttributes)
let labelRect = CGRect(x: xpos - labelSize.width * 0.5, y: yPos - 2.0 - labelSize.height, width: labelSize.width, height: labelSize.height)
label.draw(in: labelRect, withAttributes: labelAttributes)
if (MinorTicksDivisionsPerMajorTick > 1) {
for j in 1..<MinorTicksDivisionsPerMajorTick {
let minorXpos = bounds.width * CGFloat(j) / CGFloat(MajorTickDivisions * MinorTicksDivisionsPerMajorTick) + xpos
path.removeAllPoints()
path.move(to: CGPoint(x: minorXpos, y: yPos))
path.line(to: CGPoint(x: minorXpos, y: yPos + XAxisMinorTickHeight))
path.stroke()
}
}
}
}
if (showYAxis) {
// Get the label font attributes
let labelParaStyle = NSMutableParagraphStyle()
labelParaStyle.lineSpacing = 0.0
labelParaStyle.alignment = NSTextAlignment.right
let labelAttributes = [
NSForegroundColorAttributeName: YAxisColor,
NSParagraphStyleAttributeName: labelParaStyle,
NSFontAttributeName: labelFont!
] as [String : Any]
let format = String(format: "%%.%df", YAxisLabelDecimalDigits)
YAxisColor.set()
let path = NSBezierPath()
let xPos = xOffset + yMaxLabelWidth + 2.0
path.move(to: CGPoint(x: xPos, y: bounds.origin.y))
path.line(to: CGPoint(x: xPos, y: bounds.origin.y + bounds.height))
path.stroke()
for i in 0...MajorTickDivisions {
let ypos = bounds.height * CGFloat(i) / CGFloat(MajorTickDivisions) + bounds.origin.y
path.removeAllPoints()
path.move(to: CGPoint(x: xPos, y: ypos))
path.line(to: CGPoint(x: xPos + YAxisMajorTickWidth, y: ypos))
path.stroke()
let value = (maxY - minY) * Double(i) / Double(MajorTickDivisions) + minY
let label = String(format: format, value)
let labelSize = label.size(withAttributes: labelAttributes)
let labelRect = CGRect(x: xOffset, y: ypos - (labelSize.height * 0.5), width: yMaxLabelWidth, height: labelSize.height)
label.draw(in: labelRect, withAttributes: labelAttributes)
if (MinorTicksDivisionsPerMajorTick > 1) {
for j in 1..<MinorTicksDivisionsPerMajorTick {
let minorYpos = bounds.height * CGFloat(j) / CGFloat(MajorTickDivisions * MinorTicksDivisionsPerMajorTick) + ypos
path.removeAllPoints()
path.move(to: CGPoint(x: xPos, y: minorYpos))
path.line(to: CGPoint(x: xPos + YAxisMinorTickWidth, y: minorYpos))
path.stroke()
}
}
}
}
}
open func getScale() -> (minX: Double, maxX: Double, minY: Double, maxY: Double)? {
return nil
}
func getXAxisHeight() -> CGFloat {
// If not showing one, return 0
xAxisHeight = 0.0
if (!showXAxis) { return 0.0 }
// Get the label font sizing
let labelParaStyle = NSMutableParagraphStyle()
labelParaStyle.lineSpacing = 0.0
labelParaStyle.alignment = NSTextAlignment.center
let labelAttributes = [
NSForegroundColorAttributeName: XAxisColor,
NSParagraphStyleAttributeName: labelParaStyle,
//NSTextAlignment: textalign,
NSFontAttributeName: labelFont!
] as [String : Any]
let labelSize = "123.4".size(withAttributes: labelAttributes)
xAxisHeight = XAxisMajorTickHeight + 2.0 // Tick plus marging
xAxisHeight += labelSize.height
xLabelHeight = labelSize.height
return xAxisHeight
}
func getYAxisWidth() -> CGFloat {
// If not showing one, return 0
yAxisWidth = 0.0
if (!showYAxis) { return 0.0 }
// Get the label font attributes
let labelParaStyle = NSMutableParagraphStyle()
labelParaStyle.lineSpacing = 0.0
labelParaStyle.alignment = NSTextAlignment.center
let labelAttributes = [
NSForegroundColorAttributeName: XAxisColor,
NSParagraphStyleAttributeName: labelParaStyle,
//NSTextAlignment: textalign,
NSFontAttributeName: labelFont!
] as [String : Any]
// Check the width of each label
yMaxLabelWidth = 0.0
let format = String(format: "%%.%df", YAxisLabelDecimalDigits)
for i in 0...MajorTickDivisions {
let value = (maxY - minY) * Double(i) / Double(MajorTickDivisions) + minY
let label = String(format: format, value)
let labelSize = label.size(withAttributes: labelAttributes)
if (labelSize.width > yMaxLabelWidth) { yMaxLabelWidth = labelSize.width }
}
yAxisWidth = YAxisMajorTickWidth + 2.0 // Tick plus marging
yAxisWidth += yMaxLabelWidth
return yAxisWidth
}
open func setInputVector(_ vector: [Double]) throws {
// Not needed for labels
}
open func setXAxisSource(_ source: MLViewAxisSource, index: Int) throws {
// Not needed for labels
}
open func setYAxisSource(_ source: MLViewAxisSource, index: Int) throws {
// Not needed for labels
}
}
/// Class for an item in a legend
open class MLLegendItem {
var label = "item"
var symbol: MLPlotSymbol? // If nil, then line style item
var lineColor = NSColor.red
var lineThickness : CGFloat = 1.0
var itemHeight : CGFloat = 0.0
public init() {
}
public convenience init(label: String, dataSetPlotItem : MLViewRegressionDataSet) {
self.init()
self.symbol = dataSetPlotItem.symbol
self.label = label
}
public convenience init(label: String, regressionLinePlotItem : MLViewRegressionLine) {
self.init()
self.symbol = nil
lineColor = regressionLinePlotItem.lineColor
lineThickness = regressionLinePlotItem.lineThickness
self.label = label
}
public convenience init(label: String, plotSymbol : MLPlotSymbol) {
self.init()
self.symbol = plotSymbol
self.label = label
}
open static func createClassLegendArray(_ labelStart: String, classificationDataSet: MLViewClassificationDataSet) -> [MLLegendItem] {
var array : [MLLegendItem] = []
// Iterate through each class label
//!! currently this is index - need to add label processing everywhere in classification
var labelIndex = 0
for plotSymbol in classificationDataSet.symbols {
let label = labelStart + "\(labelIndex)"
array.append(MLLegendItem(label: label, plotSymbol : plotSymbol))
labelIndex += 1
}
return array
}
}
/// Class for drawing a legend
open class MLViewLegend: MLViewItem {
// Location
var location = MLViewLegendLocation.lowerRight
var xPosition : CGFloat = 0.0
var yPosition : CGFloat = 0.0
// Text information
open var fontColor = NSColor.black
open var titleFont = NSFont(name: "Helvetica Neue", size: 14.0)
open var itemFont = NSFont(name: "Helvetica Neue", size: 12.0)
open var title = ""
// Items
var items : [MLLegendItem] = []
public init() {
}
public convenience init(location: MLViewLegendLocation, title: String) {
self.init()
self.location = location
self.title = title
}
open func addItem(_ item: MLLegendItem) {
items.append(item)
}
open func addItems(_ items: [MLLegendItem]) {
self.items += items
}
open func setColor(_ color: NSColor) {
fontColor = color
}
open func setScale(_ scale: (minX: Double, maxX: Double, minY: Double, maxY: Double)) {
// Unused
}
open func draw(_ bounds: CGRect) {
// Get the attributes for drawing
let paraStyle = NSMutableParagraphStyle()
paraStyle.lineSpacing = 6.0
paraStyle.alignment = NSTextAlignment.center
let titleAttributes = [
NSForegroundColorAttributeName: fontColor,
NSParagraphStyleAttributeName: paraStyle,
//NSTextAlignment: textalign,
NSFontAttributeName: titleFont!
] as [String : Any]
let labelParaStyle = NSMutableParagraphStyle()
labelParaStyle.lineSpacing = 6.0
labelParaStyle.alignment = NSTextAlignment.right
let labelAttributes = [
NSForegroundColorAttributeName: fontColor,
NSParagraphStyleAttributeName: labelParaStyle,
//NSTextAlignment: textalign,
NSFontAttributeName: itemFont!
] as [String : Any]
// Get the required size of the legend title
var titleSize = CGSize.zero
var legendSize = CGSize.zero
if (!title.isEmpty) {
titleSize = title.size(withAttributes: titleAttributes)
legendSize = titleSize
}
// Add all the item sizes
var maxLabelSize : CGFloat = 0.0
var maxSymbolSize : CGFloat = 0.0
for item in items {
let labelSize = item.label.size(withAttributes: titleAttributes)
var itemHeight = labelSize.height
if (labelSize.width > maxLabelSize) { maxLabelSize = labelSize.width }
if let symbol = item.symbol {
if (symbol.symbolSize > itemHeight) { itemHeight = symbol.symbolSize }
if (symbol.symbolSize > maxSymbolSize) { maxSymbolSize = symbol.symbolSize }
}
else {
if (item.lineThickness > itemHeight) { itemHeight = item.lineThickness }
if (item.lineThickness > maxSymbolSize) { maxSymbolSize = item.lineThickness }
if (30.0 > maxSymbolSize) { maxSymbolSize = 30.0 } // legend line will be at least 30 points long
}
item.itemHeight = itemHeight
legendSize.height += itemHeight + 2.0
}
let itemWidth = 2.0 + maxLabelSize + 4.0 + maxSymbolSize + 2.0 // Include margins
if (itemWidth > legendSize.width) { legendSize.width = itemWidth }
// Get the legend position
switch (location) {
case .upperLeft:
xPosition = bounds.origin.x
yPosition = bounds.height + bounds.origin.y
case .upperRight:
xPosition = bounds.width - legendSize.width + bounds.origin.x
yPosition = bounds.height + bounds.origin.y
case .lowerLeft:
xPosition = bounds.origin.x
yPosition = legendSize.height + bounds.origin.y
case .lowerRight:
xPosition = bounds.width - legendSize.width + bounds.origin.x
yPosition = legendSize.height + bounds.origin.y
case .custom:
break // position already set
}
// If specified, draw the title
if (!title.isEmpty) {
let rect = CGRect(x: xPosition, y: yPosition - titleSize.height, width: legendSize.width, height: titleSize.height)
title.draw(in: rect, withAttributes: titleAttributes)
}
// Draw each item
var labelRect = CGRect(x: xPosition + 2.0, y: yPosition - titleSize.height, width: maxLabelSize, height: 1.0)
var symbolRect = CGRect(x: xPosition + 2.0 + maxLabelSize + 4.0, y: yPosition - titleSize.height, width: maxSymbolSize, height: 1.0)
for item in items {
// Move the rectangles down
labelRect.origin.y -= item.itemHeight
symbolRect.origin.y -= item.itemHeight
// Set the height of the rectangles to the item height
labelRect.size.height = item.itemHeight + 2.0
symbolRect.size.height = item.itemHeight + 2.0
// Draw the label
item.label.draw(in: labelRect, withAttributes: labelAttributes)
// Draw the symbol
if let symbol = item.symbol {
let center = CGPoint(x: symbolRect.origin.x + (symbolRect.width * 0.5), y: symbolRect.origin.y + (item.itemHeight * 0.5))
symbol.drawAt(center)
}
else {
let path = NSBezierPath()
item.lineColor.setStroke()
path.lineWidth = item.lineThickness
let y = symbolRect.origin.y + (item.itemHeight * 0.5)
path.move(to: CGPoint(x: symbolRect.origin.x + item.lineThickness, y: y))
path.line(to: CGPoint(x: symbolRect.origin.x + symbolRect.width - item.lineThickness, y: y))
path.stroke()
}
}
}
open func getScale() -> (minX: Double, maxX: Double, minY: Double, maxY: Double)? {
return nil
}
open func setInputVector(_ vector: [Double]) throws {
// Not needed for legends
}
open func setXAxisSource(_ source: MLViewAxisSource, index: Int) throws {
// Not needed for legends
}
open func setYAxisSource(_ source: MLViewAxisSource, index: Int) throws {
// Not needed for legends
}
}
/// Class to view Machine Learning data, include data sets, regression lines, classification zones
open class MLView: NSView {
// Machine learning items to plot
var plotItems : [MLViewItem] = []
var scalingItem: MLViewItem?
var margin: CGFloat = 3.0 // Margin for data and lines, in percent
override public init(frame: CGRect) {
super.init(frame: frame)
}
convenience init() {
self.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// Function to add an item to be plotted
open func addPlotItem(_ plotItem: MLViewItem) {
plotItems.append(plotItem)
setNeedsDisplay(bounds)
}
/// Function to set the item that the initial scale will be retrieved from
open func setInitialScaleItem(_ plotItem: MLViewItem) {
scalingItem = plotItem
setNeedsDisplay(bounds)
}
override open func draw(_ rect: CGRect) {
// draw the background
NSColor.white.setFill()
NSRectFill(bounds)
// Start the initial scaling at 0-100
var currentScaling = (minX: 0.0, maxX: 100.0, minY: 0.0, maxY: 100.0)
// If there is an initial item to get the scale from, do so
if let scalingItem = scalingItem {
let newScale = scalingItem.getScale()
if let newScale = newScale {
currentScaling = newScale
}
}
// See how much room we have to leave for axis labels
var drawRect = bounds
let xMargin = (margin * 0.01) * drawRect.size.width
let yMargin = (margin * 0.01) * drawRect.size.height
var xAxisLabelSpace : CGFloat = yMargin
var yAxisLabelSpace : CGFloat = xMargin
for plotItem in plotItems {
if plotItem is MLViewAxisLabel {
let axisLabel = plotItem as! MLViewAxisLabel
axisLabel.setOffsets(yAxisLabelSpace, y: xAxisLabelSpace)
xAxisLabelSpace += axisLabel.getXAxisHeight()
yAxisLabelSpace += axisLabel.getYAxisWidth()
}
}
// Get the draw rectangle without the margins and labels
drawRect.origin.x += yAxisLabelSpace
drawRect.origin.y += xAxisLabelSpace
drawRect.size.width -= xMargin + yAxisLabelSpace
drawRect.size.height -= yMargin + xAxisLabelSpace
// Iterate through each plot item
for plotItem in plotItems {
// Set the scaling factors
plotItem.setScale(currentScaling)
// Draw the item
plotItem.draw(drawRect)
// Get the scaling used for the next item
let newScale = plotItem.getScale()
if let newScale = newScale {
currentScaling = newScale
}
}
}
/// Method to set the input vector on ALL items
open func setInputVector(_ vector: [Double]) throws {
for plotItem in plotItems {
try plotItem.setInputVector(vector)
}
}
/// Method to set the X axis source on ALL items
open func setXAxisSource(_ source: MLViewAxisSource, index: Int) throws {
for plotItem in plotItems {
try plotItem.setXAxisSource(source, index: index)
}
}
/// Method to set the Y axis source on ALL items
open func setYAxisSource(_ source: MLViewAxisSource, index: Int) throws {
for plotItem in plotItems {
try plotItem.setYAxisSource(source, index: index)
}
}
/// Routine to round/extend a scale to more 'human-readable' values.
open static func roundScale(_ min: Double, max: Double, logScale: Bool = false) -> (min: Double, max: Double) {
var Y : Double
var Z : Double
// Set the temporary limit values
var upper = max
var lower = min
// If logarithmic, just round the min and max to the nearest power of 10
if (logScale) {
// Round the upper limit
if (upper <= 0.0) { upper = 1000.0 }
Y = log10(upper)
Z = Double(Int(Y))
if (Y != Z && Y > 0.0) { Z += 1.0 }
upper = pow(10.0, Z)
// round the lower limit
if (lower <= 0.0) { lower = 0.1}
Y = log10(lower)
Z = Double(Int(Y))
if (Y != Z && Y < 0.0) { Z -= 1.0 }
lower = pow(10.0, Z)
// Make sure the limits are not the same
if (lower == upper) {
Y = log10(max)
upper = pow(10.0, Y+1.0)
lower = pow(10.0, Y-1.0)
}
return (min: lower, max: upper)
}
// Get the difference between the limits
var bRoundLimits = true
var bNegative = false
while (bRoundLimits) {
bRoundLimits = false
let difference = upper - lower
if (!difference.isFinite) {
lower = 0.0
upper = 0.0
return (min: lower, max: upper)
}
// Calculate the upper limit
if (upper != 0) {
// Convert negatives to positives
bNegative = false
if (upper < 0.0) {
bNegative = true
upper *= -1.0
}
// If the limits match, use value for rounding
if (difference == 0.0) {
Z = Double(Int(log10(upper)))
if (Z < 0.0) { Z -= 1.0 }
Z -= 1.0
}
// If the limits don't match, use difference for rounding
else {
Z = Double(Int(log10(difference)))
}
// Get the normalized limit
Y = upper / pow(10.0, Z)
// Make sure we don't round down due to value storage limitations
let NY = Y + Double.ulpOfOne * 100.0
if (Int(log10(Y)) != Int(log10(NY))) {
Y = NY * 0.1
Z += 1.0
}
// Round by integerizing the normalized number
if (Y != Double(Int(Y))) {
Y = Double(Int(Y))
if (!bNegative) {
Y += 1.0
}
upper = Y * pow(10.0, Z)
}
if (bNegative) { upper *= -1.0 }
}
// Calclate the lower limit
if (lower != 0) {
// Convert negatives to positives
bNegative = false
if (lower < 0.0) {
bNegative = true
lower *= -1.0
}
// If the limits match, use value for rounding
if (difference == 0.0) {
Z = Double(Int(log10(lower)))
if (Z < 0.0) { Z -= 1.0 }
Z -= 1.0
}
// If the limits don't match, use difference for rounding
else {
Z = Double(Int(log10(difference)))
}
// Get the normalized limit
Y = lower / pow(10.0, Z)
// Make sure we don't round down due to value storage limitations
let NY = Y + Double.ulpOfOne * 100.0
if (Int(log10(Y)) != Int(log10(NY))) {
Y = NY * 0.1
Z += 1.0
}
// Round by integerizing the normalized number
if (Y != Double(Int(Y))) {
Y = Double(Int(Y))
if (bNegative) {
Y += 1.0
}
else {
if (difference == 0.0) { Y -= 1.0 }
}
lower = Y * pow(10.0, Z)
}
if (bNegative) { lower *= -1.0 }
// Make sure both are not 0
if (upper == 0.0 && lower == 0.0) {
upper = 1.0;
lower = -1.0;
}
// If the limits still match offset by a percent each and recalculate
if (upper == lower) {
if (lower > 0.0) {
lower *= 0.99
}
else {
lower *= 1.01
}
if (upper > 0.0) {
upper *= 1.01
}
else {
upper *= 0.99
}
bRoundLimits = true
}
}
}
return (min: lower, max: upper)
}
}
| 0ed8e9c595621c6bd8c7284e13ae4b74 | 35.56701 | 168 | 0.541796 | false | false | false | false |
Look-ARound/LookARound2 | refs/heads/hd-callouts | lookaround2/Views/ARCalloutView.swift | apache-2.0 | 1 | //
// ARCalloutView.swift
// lookaround2
//
// Created by Angela Yu on 10/23/17.
// Copyright © 2017 Angela Yu. All rights reserved.
//
import Mapbox
class ARCalloutView: UIView, MGLCalloutView {
var representedObject: MGLAnnotation
// Allow the callout to remain open during panning.
let dismissesAutomatically: Bool = false
let isAnchoredToAnnotation: Bool = true
// https://github.com/mapbox/mapbox-gl-native/issues/9228
override var center: CGPoint {
set {
var newCenter = newValue
newCenter.y = newCenter.y - bounds.midY
super.center = newCenter
}
get {
return super.center
}
}
lazy var leftAccessoryView = UIView() /* unused */
lazy var rightAccessoryView = UIView() /* unused */
weak var delegate: MGLCalloutViewDelegate?
let tipHeight: CGFloat = 10.0
let tipWidth: CGFloat = 20.0
let mainBody: UIButton
required init(representedObject: MGLAnnotation) {
self.representedObject = representedObject
self.mainBody = UIButton(type: .system)
super.init(frame: .zero)
backgroundColor = .clear
mainBody.backgroundColor = .darkGray
mainBody.tintColor = .white
mainBody.contentEdgeInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0)
mainBody.layer.cornerRadius = 4.0
addSubview(mainBody)
}
required init?(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - MGLCalloutView API
func presentCallout(from rect: CGRect, in view: UIView, constrainedTo constrainedView: UIView, animated: Bool) {
if !representedObject.responds(to: #selector(getter: MGLAnnotation.title)) {
return
}
view.addSubview(self)
// Prepare title label
var fullTitle = ""
if let title = representedObject.title as? String {
fullTitle = title
if let subtitle = representedObject.subtitle as? String {
print(subtitle)
mainBody.titleLabel!.lineBreakMode = .byWordWrapping
mainBody.titleLabel!.numberOfLines = 2
fullTitle += "\n\(subtitle)"
}
}
mainBody.setTitle(fullTitle, for: .normal)
mainBody.sizeToFit()
if isCalloutTappable() {
// Handle taps and eventually try to send them to the delegate (usually the map view)
mainBody.addTarget(self, action: #selector(ARCalloutView.calloutTapped), for: .touchUpInside)
} else {
// Disable tapping and highlighting
mainBody.isUserInteractionEnabled = false
}
// Prepare our frame, adding extra space at the bottom for the tip
let frameWidth = mainBody.bounds.size.width
let frameHeight = mainBody.bounds.size.height + tipHeight
let frameOriginX = rect.origin.x + (rect.size.width/2.0) - (frameWidth/2.0)
let frameOriginY = rect.origin.y - frameHeight
frame = CGRect(x: frameOriginX, y: frameOriginY, width: frameWidth, height: frameHeight)
if animated {
alpha = 0
UIView.animate(withDuration: 0.2) { [weak self] in
self?.alpha = 1
}
}
}
func dismissCallout(animated: Bool) {
if (superview != nil) {
if animated {
UIView.animate(withDuration: 0.2, animations: { [weak self] in
self?.alpha = 0
}, completion: { [weak self] _ in
self?.removeFromSuperview()
})
} else {
removeFromSuperview()
}
}
}
// MARK: - Callout interaction handlers
func isCalloutTappable() -> Bool {
if let delegate = delegate {
if delegate.responds(to: #selector(MGLCalloutViewDelegate.calloutViewShouldHighlight)) {
return delegate.calloutViewShouldHighlight!(self)
}
}
return false
}
@objc func calloutTapped() {
if isCalloutTappable() && delegate!.responds(to: #selector(MGLCalloutViewDelegate.calloutViewTapped)) {
delegate!.calloutViewTapped!(self)
}
}
// MARK: - Custom view styling
override func draw(_ rect: CGRect) {
// Draw the pointed tip at the bottom
let fillColor : UIColor = .darkGray
let tipLeft = rect.origin.x + (rect.size.width / 2.0) - (tipWidth / 2.0)
let tipBottom = CGPoint(x: rect.origin.x + (rect.size.width / 2.0), y: rect.origin.y + rect.size.height)
let heightWithoutTip = rect.size.height - tipHeight - 1
let currentContext = UIGraphicsGetCurrentContext()!
let tipPath = CGMutablePath()
tipPath.move(to: CGPoint(x: tipLeft, y: heightWithoutTip))
tipPath.addLine(to: CGPoint(x: tipBottom.x, y: tipBottom.y))
tipPath.addLine(to: CGPoint(x: tipLeft + tipWidth, y: heightWithoutTip))
tipPath.closeSubpath()
fillColor.setFill()
currentContext.addPath(tipPath)
currentContext.fillPath()
}
}
| 0d7af3c958b6f50ec15805c4ceb940d4 | 32.675 | 116 | 0.584633 | false | false | false | false |
iosphere/ISHPullUp | refs/heads/master | ISHPullUpSample/ISHPullUpSample/ContentVC.swift | mit | 1 | //
// ContentVC.swift
// ISHPullUpSample
//
// Created by Felix Lamouroux on 27.06.16.
// Copyright © 2016 iosphere GmbH. All rights reserved.
//
import MapKit
import ISHPullUp
class ContentVC: UIViewController, ISHPullUpContentDelegate {
@IBOutlet private weak var mapView: MKMapView!
@IBOutlet private weak var layoutAnnotationLabel: UILabel!
// we use a root view to rely on the edge inset
// (this cannot be set on the VC's view directly)
@IBOutlet private weak var rootView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
layoutAnnotationLabel.layer.cornerRadius = 2;
// The mapView should preserve the rootView's layout margins only
// on iOS 10 and earlier to correctly update the legal label
// and coordinate region.
// On iOS 11 and later this is done automatically via the safeAreaInsets.
if #available(iOS 11.0, *) {
mapView.preservesSuperviewLayoutMargins = false
} else {
mapView.preservesSuperviewLayoutMargins = true
}
}
// MARK: ISHPullUpContentDelegate
func pullUpViewController(_ vc: ISHPullUpViewController, update edgeInsets: UIEdgeInsets, forContentViewController _: UIViewController) {
if #available(iOS 11.0, *) {
additionalSafeAreaInsets = edgeInsets
rootView.layoutMargins = .zero
} else {
// update edgeInsets
rootView.layoutMargins = edgeInsets
}
// call layoutIfNeeded right away to participate in animations
// this method may be called from within animation blocks
rootView.layoutIfNeeded()
}
}
| 9267701512a6a7b577ca7272910efaa0 | 32.78 | 141 | 0.668443 | false | false | false | false |
donbytyqi/WatchBox | refs/heads/master | WatchBox Reborn/MoveAPIService.swift | mit | 1 | //
// MoveAPIService.swift
// WatchBox Reborn
//
// Created by Don Bytyqi on 5/1/17.
// Copyright © 2017 Don Bytyqi. All rights reserved.
//
import UIKit
enum Genre: String {
case action = "28"
case adventure = "12"
case animation = "16"
case comedy = "35"
case crime = "80"
case documentary = "99"
case drama = "18"
case family = "10751"
case fantasy = "14"
case history = "36"
case horror = "27"
case music = "10402"
case mystery = "9648"
case romance = "10749"
case scienceFiction = "878"
case tvMovie = "10770"
case thriller = "53"
case war = "10752"
case western = "37"
case none = ""
}
class MovieAPIService: NSObject {
static let shared = MovieAPIService()
var title: String?
var year: String?
var id = ""
func fetchMovies(url: String? = "", isMovie: String? = "movie", page: Int, type: String? = "popular", genre: Genre? = .none, query: String?, completion: @escaping ([Movie]) -> ()) {
var b = "https://api.themoviedb.org/3/"
var t = type ?? "popular"
var m = isMovie ?? "movie"
var baseURL = b + m + "/" + t + "?api_key=your_api_key&language=en-US&page=\(page)"
var stringToURL: URL?
stringToURL = URL(string: baseURL)
UIApplication.shared.isNetworkActivityIndicatorVisible = true
if query != "" {
let bb = "https://api.themoviedb.org/3/search/"
baseURL = bb + "multi" + "?api_key=087d599aa9589c52c4271a3eb196016e&query=\(query!)&language=en-US&page=\(page)"
print(baseURL)
if let link = URL(string: baseURL) {
stringToURL = link
print(stringToURL!)
}
}
if genre != .none {
m = "movies"
b = "https://api.themoviedb.org/3/genre/"
t = type ?? "popular"
baseURL = b + String(describing: (genre?.rawValue)!) + "/" + m + "?api_key=087d599aa9589c52c4271a3eb196016e&language=en-US&page=\(page)"
print(baseURL)
stringToURL = URL(string: baseURL)
}
URLSession.shared.dataTask(with: stringToURL!) { (data, response, error) in
var movies = [Movie()]
print(stringToURL!)
if error != nil {
self.showError(error as! String)
}
do {
let jsonData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
guard let results = jsonData["results"] as? NSArray else { return }
for movie in 0..<results.count {
guard let movieDictionary = results[movie] as? [String : AnyObject] else { return }
let movie = Movie()
movie.setValuesForKeys(movieDictionary)
movies.insert(movie, at: movies.count - 1)
}
DispatchQueue.main.async {
completion(movies)
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
catch {
self.showError(error as! String)
}
}.resume()
}
func similarMovies(withID: Int, isMovie: String, page: Int, completion: @escaping ([Movie]) -> ()) {
let url = URL(string: "https://api.themoviedb.org/3/\(isMovie)/\(withID)/similar?api_key=087d599aa9589c52c4271a3eb196016e&language=en-US&page=\(page)")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
var movies = [Movie()]
print(url!)
if error != nil {
self.showError(error as! String)
}
do {
let jsonData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
guard let results = jsonData["results"] as? NSArray else { return }
for movie in 0..<results.count {
guard let movieDictionary = results[movie] as? [String : AnyObject] else { return }
let movie = Movie()
movie.setValuesForKeys(movieDictionary)
movies.insert(movie, at: movies.count - 1)
}
DispatchQueue.main.async {
completion(movies)
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
catch {
self.showError(error as! String)
}
}.resume()
}
func getCast(movieID: Int, isMovie: String, completion: @escaping ([Cast]) -> ()) {
let url = URL(string: "https://api.themoviedb.org/3/\(isMovie)/\(movieID)/credits?api_key=087d599aa9589c52c4271a3eb196016e")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
var casts = [Cast()]
if error != nil {
self.showError(error as! String)
}
do {
let jsonData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
guard let cast = jsonData["cast"] as? NSArray else { return }
for i in 0..<cast.count {
guard let castDictionary = cast[i] as? [String : AnyObject] else { return }
let castClass = Cast()
castClass.setValuesForKeys(castDictionary)
casts.insert(castClass, at: casts.count - 1)
}
DispatchQueue.main.async {
completion(casts)
UIApplication.shared.isNetworkActivityIndicatorVisible = false
return
}
}
catch {
self.showError(error as! String)
}
}.resume()
}
func fetchCastMovies(byID: Int, isMovie: String, completion: @escaping ([Movie]) -> ()) {
let url = URL(string: "https://api.themoviedb.org/3/person/\(byID)/\(isMovie)_credits?api_key=087d599aa9589c52c4271a3eb196016e&language=en-US")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
var movies = [Movie()]
print(url!)
if error != nil {
self.showError(error as! String)
}
do {
let jsonData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
guard let results = jsonData["cast"] as? NSArray else { return }
for movie in 0..<results.count {
guard let movieDictionary = results[movie] as? [String : AnyObject] else { return }
let movie = Movie()
print(movieDictionary)
movie.setValuesForKeys(movieDictionary)
movies.insert(movie, at: movies.count - 1)
}
DispatchQueue.main.async {
completion(movies)
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
catch {
self.showError(error as! String)
}
}.resume()
}
func showError(_ error: String) {
guard let window = UIApplication.shared.keyWindow else { return }
Alert().show(title: "Something happened", message: error, controller: window.rootViewController!)
return
}
}
| f4ae0449a3ba6d49a8c7b8a66be8ab46 | 36.134259 | 185 | 0.505797 | false | false | false | false |
nicemohawk/nmf-ios | refs/heads/master | nmf/ScheduleItem.swift | apache-2.0 | 1 | //
// Schedule.swift
// nmf
//
// Created by Daniel Pagan on 4/6/16.
// Copyright © 2017 Nelsonville Music Festival. All rights reserved.
//
import Foundation
@objcMembers class ScheduleItem: NSObject, NSCoding {
var objectId: String?
var artistName: String?
var startTime: Date?
var stage: String?
var day: String?
// local-only
var _starred: Bool = false
var _updated: Bool = false
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
objectId = aDecoder.decodeObject(forKey: "oid") as? String
artistName = aDecoder.decodeObject(forKey: "artist") as? String
startTime = aDecoder.decodeObject(forKey: "start") as? Date
day = aDecoder.decodeObject(forKey: "day") as? String
stage = aDecoder.decodeObject(forKey: "stage") as? String
_starred = aDecoder.decodeBool(forKey: "starred")
_updated = aDecoder.decodeBool(forKey: "updated")
}
func encode(with aCoder: NSCoder) {
aCoder.encode(objectId, forKey: "oid")
aCoder.encode(artistName, forKey: "artist")
aCoder.encode(startTime, forKey: "start")
aCoder.encode(day, forKey: "day")
aCoder.encode(stage, forKey: "stage")
aCoder.encode(_starred, forKey: "starred")
aCoder.encode(_updated, forKey: "updated")
}
// MARK: - Custom methods
func update(_ otherItem: ScheduleItem) {
guard objectId == otherItem.objectId else {
return
}
artistName = otherItem.artistName
startTime = otherItem.startTime
day = otherItem.day
stage = otherItem.stage
// we don't merge starred
_updated = true
}
//MARK: - date formatting
static let hourFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "h:mma"
return formatter
}()
static let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "EEEE h:mma"
return formatter
}()
func timeString() -> String {
if let startDate = startTime {
let components = Calendar.current.dateComponents([.hour,.minute], from: startDate)
if let hour = components.hour, let minute = components.minute {
switch (hour, minute) {
case (23, 59):
return "12:00AM"
default:
return ScheduleItem.hourFormatter.string(from: startDate)
}
}
return ScheduleItem.hourFormatter.string(from: startDate)
}
return ""
}
func dateString() -> String {
if let startDate = startTime {
return ScheduleItem.dateFormatter.string(from: startDate)
}
return ""
}
}
| c5bd2a6b6956770420d8220482c55bdf | 25.918919 | 94 | 0.569612 | false | false | false | false |
blstream/StudyBox_iOS | refs/heads/master | StudyBox_iOS/Array+FindUnique.swift | apache-2.0 | 1 | //
// Array+findUnique.swift
// StudyBox_iOS
//
// Created by Damian Malarczyk on 04.03.2016.
// Copyright © 2016 BLStream. All rights reserved.
//
import Foundation
extension Array where Element: UniquelyIdentifiable {
func findUniqe(withId idUniqe: String) -> Element? {
for element in self {
if element.serverID == idUniqe {
return element
}
}
return nil
}
func indexOfUnique(idUniqe: String) -> Int? {
for (index, element) in self.enumerate() {
if element.serverID == idUniqe {
return index
}
}
return nil
}
func unqiueElements() -> [Element] {
var uniques = [Element]()
self.forEach {
if uniques.findUniqe(withId: $0.serverID) == nil {
uniques.append($0)
}
}
return uniques
}
}
| 7190f64c1847add29289e0fbe68c6349 | 21.380952 | 62 | 0.520213 | false | false | false | false |
poodarchu/iDaily | refs/heads/master | iDaily/iDaily/iDailyAnimator.swift | gpl-3.0 | 1 | //
// iDailyAnimator.swift
// iDaily
//
// Created by P. Chu on 5/31/16.
// Copyright © 2016 Poodar. All rights reserved.
//
import UIKit
//iDailyAnimator定义了转场的过渡动画效果
//@protocol: UIViewControllerAnimatedTransitioning
// The methods in this protocol let you define an animator object,
// which creates the animations for transitioning a view controller on or off screen in a fixed amount of time.
// 使用这个协议创建的动画必须是可交互的
// 为了创建可交互的动画对象,必须将该动画对象和其他控制动画时间的对象结合使用
// 实现了协议的类必须实现以下方法
// 1. public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval
// 2. public func animateTransition(transitionContext: UIViewControllerContextTransitioning)
// 3. optional public func animationEnded(transitionCompleted: Bool) 第三个方法是可选的
class iDailyAnimator: NSObject, UIViewControllerAnimatedTransitioning
{
//These constants define the type of navigation controller transitions that can occur.
//case None
//case Push
//case Pop
var operation: UINavigationControllerOperation!
//转场时长
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.4
}
//转场参数的变化
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
//获取转场舞台
//即动画view的父view
//The view that acts as the superview for the views involved in the transition.
let containerView = transitionContext.containerView()
//从x场景
//Identifies the view controller that is visible at the beginning of the transition
let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
let fromView = fromVC!.view
//转到x场景
let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
let toView = toVC!.view
//起始时,设置toView为透明状态
toView.alpha = 0.0
//UINavigationControllerOperation.Pop用于判断是转入还是转出
if operation == UINavigationControllerOperation.Pop {
//如果要返回旧场景,那么设置要转入的场景初始缩放为原始大小
toView.transform = CGAffineTransformMakeScale(1.0, 1.0)
}
else {
//如果是转到新场景,设置新场景的初始缩放为0.3
toView.transform = CGAffineTransformMakeScale(0.3, 0.3)
}
//在舞台上插入场景
containerView!.insertSubview(toView, aboveSubview: fromView)
//开始动画
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
if self.operation == UINavigationControllerOperation.Pop {
//放大要转出的场景
fromView.transform = CGAffineTransformMakeScale(3.3, 3.3) //1.0 -> 3.3
}
else {
//从原始大小的0.3倍逐渐开始还原为原始场景的大小
toView.transform = CGAffineTransformMakeScale(1.0, 1.0) //0.3 -> 1.0
}
toView.alpha = 1.0 //将toView置为可见
}, completion: { finished in
// 通知 NavigationController 已经完成转场
// Notifies the system that the transition animation is done.
transitionContext.completeTransition(true)
})
}
} | a7752a6311a59f2da9141d66989433e3 | 36.895349 | 146 | 0.674954 | false | false | false | false |
sonsongithub/reddift | refs/heads/master | application/LinkContainable.swift | mit | 1 | //
// LinkContainable.swift
// reddift
//
// Created by sonson on 2016/09/29.
// Copyright © 2016年 sonson. All rights reserved.
//
import reddift
import Foundation
let LinkContainerDidLoadImageName = Notification.Name(rawValue: "LinkContainerDidLoadImageName")
private let regexForImageURL: NSRegularExpression! = {
do {
return try NSRegularExpression(pattern: "((jpg)|(jpeg)|(gif)|(png))$", options: .caseInsensitive)
} catch {
assert(false, "Fatal error: \(#file) \(#line) \(error)")
return nil
}
}()
class LinkContainable: ThingContainable, ImageDownloadable {
/// reddift raw data
internal var intrinsicLink: Link
var link: Link {
get {
return intrinsicLink
}
}
/// Attributed string for UITableViewCell's title
var attributedTitle: NSAttributedString
/// Size of view to render title as an attributed string in the cell, including margin size.
var titleSize: CGSize
///
var pageLoaded: Bool
var thumbnails: [Thumbnail] = []
var width = CGFloat(0)
/// Height of cell which contains the content
override var height: CGFloat {
if isHidden {
return 0
} else {
return LinkCell.estimateHeight(titleHeight: titleSize.height)
}
}
override var intrinsicThing: Thing {
didSet {
DispatchQueue.main.async(execute: { () -> Void in
if let link = self.thing as? Link {
self.intrinsicLink = link
NotificationCenter.default.post(name: ThingContainableDidUpdate, object: nil, userInfo: ["contents": self])
}
})
}
}
/// Method to download attional contents or images when the cell is updated.
func downloadImages() {
}
/// Download and parse html page, like imgur image list.
func prefetch(at: IndexPath) {
}
func layout(with width: CGFloat, fontSize: CGFloat) {
self.width = width
let font = UIFont(name: UIFont.systemFont(ofSize: fontSize).fontName, size: fontSize) ?? UIFont.systemFont(ofSize: fontSize)
attributedTitle = NSAttributedString(string: link.title).reconstruct(with: font, color: UIColor.black, linkColor: UIColor.blue)
titleSize = LinkCell.estimateTitleSize(attributedString: attributedTitle, withBountWidth: width, margin: .zero)
}
init(with link: Link, width: CGFloat, fontSize: CGFloat = 18) {
self.intrinsicLink = link
self.width = width
let font = UIFont(name: UIFont.systemFont(ofSize: fontSize).fontName, size: fontSize) ?? UIFont.systemFont(ofSize: fontSize)
attributedTitle = NSAttributedString(string: link.title).reconstruct(with: font, color: UIColor.black, linkColor: UIColor.blue)
titleSize = LinkCell.estimateTitleSize(attributedString: attributedTitle, withBountWidth: width, margin: .zero)
pageLoaded = true
super.init(with: link)
}
static func createContainer(with link: Link, width: CGFloat, fontSize: CGFloat = 14) -> LinkContainable {
guard let url = URL(string: link.url) else { return LinkContainer(with: link, width: width, fontSize: fontSize) }
// simple image URL
if let _ = regexForImageURL.firstMatch(in: link.url as String, options: [], range: NSRange(location: 0, length: (link.url as NSString).length)) {
if let imageURL = URL(string: link.url) {
let thumbnail = Thumbnail.Image(imageURL: imageURL, parentID: link.id)
return MediaLinkContainer(link: link, width: width, fontSize: fontSize, thumbnails: [thumbnail])
}
}
if url.isGfygatURL {
if let urlset = url.extractGfycatURL() {
let thumbnail = Thumbnail.Movie(movieURL: urlset.0, thumbnailURL: urlset.1, parentID: link.id)
return MediaLinkContainer(link: link, width: width, fontSize: fontSize, thumbnails: [thumbnail])
}
}
if url.isYouTubeURL {
if let urlset = url.extractYouTubeURL() {
let thumbnail = Thumbnail.Movie(movieURL: urlset.0, thumbnailURL: urlset.1, parentID: link.id)
return MediaLinkContainer(link: link, width: width, fontSize: fontSize, thumbnails: [thumbnail])
}
}
// image URL of imgur
if url.isImgurURL {
return ImgurLinkContainer(link: link, width: width, fontSize: fontSize, thumbnails: [])
}
// contents with thumbnail
if let thumbnailURL = URL(string: link.thumbnail), let _ = URL(string: link.url), let _ = thumbnailURL.scheme {
let thumbnail = Thumbnail.Image(imageURL: thumbnailURL, parentID: link.id)
return ThumbnailLinkContainer(link: link, width: width, fontSize: fontSize, thumbnail: thumbnail)
}
return LinkContainer(with: link, width: width, fontSize: fontSize)
}
}
| f566856be2632fef1ccbf2b52ac60311 | 38.445313 | 153 | 0.630818 | false | false | false | false |
loudnate/Loop | refs/heads/master | Loop/Managers/AnalyticsManager.swift | apache-2.0 | 1 | //
// AnalyticsManager.swift
// Naterade
//
// Created by Nathan Racklyeft on 4/28/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
import Amplitude
import LoopKit
import LoopCore
final class AnalyticsManager: IdentifiableClass {
var amplitudeService: AmplitudeService {
didSet {
try! KeychainManager().setAmplitudeAPIKey(amplitudeService.APIKey)
}
}
init() {
if let APIKey = KeychainManager().getAmplitudeAPIKey() {
amplitudeService = AmplitudeService(APIKey: APIKey)
} else {
amplitudeService = AmplitudeService(APIKey: nil)
}
logger = DiagnosticLogger.shared.forCategory(type(of: self).className)
}
static let shared = AnalyticsManager()
// MARK: - Helpers
private var logger: CategoryLogger?
private func logEvent(_ name: String, withProperties properties: [AnyHashable: Any]? = nil, outOfSession: Bool = false) {
logger?.debug("\(name) \(properties ?? [:])")
amplitudeService.client?.logEvent(name, withEventProperties: properties, outOfSession: outOfSession)
}
// MARK: - UIApplicationDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [AnyHashable: Any]?) {
logEvent("App Launch")
}
// MARK: - Screens
func didDisplayBolusScreen() {
logEvent("Bolus Screen")
}
func didDisplaySettingsScreen() {
logEvent("Settings Screen")
}
func didDisplayStatusScreen() {
logEvent("Status Screen")
}
// MARK: - Config Events
func transmitterTimeDidDrift(_ drift: TimeInterval) {
logEvent("Transmitter time change", withProperties: ["value" : drift], outOfSession: true)
}
func pumpTimeDidDrift(_ drift: TimeInterval) {
logEvent("Pump time change", withProperties: ["value": drift], outOfSession: true)
}
func punpTimeZoneDidChange() {
logEvent("Pump time zone change", outOfSession: true)
}
func pumpBatteryWasReplaced() {
logEvent("Pump battery replacement", outOfSession: true)
}
func reservoirWasRewound() {
logEvent("Pump reservoir rewind", outOfSession: true)
}
func didChangeBasalRateSchedule() {
logEvent("Basal rate change")
}
func didChangeCarbRatioSchedule() {
logEvent("Carb ratio change")
}
func didChangeInsulinModel() {
logEvent("Insulin model change")
}
func didChangeInsulinSensitivitySchedule() {
logEvent("Insulin sensitivity change")
}
func didChangeLoopSettings(from oldValue: LoopSettings, to newValue: LoopSettings) {
if newValue.maximumBasalRatePerHour != oldValue.maximumBasalRatePerHour {
logEvent("Maximum basal rate change")
}
if newValue.maximumBolus != oldValue.maximumBolus {
logEvent("Maximum bolus change")
}
if newValue.suspendThreshold != oldValue.suspendThreshold {
logEvent("Minimum BG Guard change")
}
if newValue.dosingEnabled != oldValue.dosingEnabled {
logEvent("Closed loop enabled change")
}
if newValue.retrospectiveCorrectionEnabled != oldValue.retrospectiveCorrectionEnabled {
logEvent("Retrospective correction enabled change")
}
if newValue.glucoseTargetRangeSchedule != oldValue.glucoseTargetRangeSchedule {
if newValue.glucoseTargetRangeSchedule?.timeZone != oldValue.glucoseTargetRangeSchedule?.timeZone {
self.punpTimeZoneDidChange()
} else if newValue.scheduleOverride != oldValue.scheduleOverride {
logEvent("Temporary schedule override change", outOfSession: true)
} else {
logEvent("Glucose target range change")
}
}
}
// MARK: - Loop Events
func didAddCarbsFromWatch() {
logEvent("Carb entry created", withProperties: ["source" : "Watch"], outOfSession: true)
}
func didRetryBolus() {
logEvent("Bolus Retry", outOfSession: true)
}
func didSetBolusFromWatch(_ units: Double) {
logEvent("Bolus set", withProperties: ["source" : "Watch"], outOfSession: true)
}
func didFetchNewCGMData() {
logEvent("CGM Fetch", outOfSession: true)
}
func loopDidSucceed(_ duration: TimeInterval) {
logEvent("Loop success", withProperties: ["duration": duration], outOfSession: true)
}
func loopDidError() {
logEvent("Loop error", outOfSession: true)
}
}
| 59faac8f48c40f73f86371d2ce8d2c56 | 27.9125 | 125 | 0.65067 | false | false | false | false |
ferusinfo/OctoAPI | refs/heads/master | Example/GetResponseBlog/GetResponseBlogExample.swift | mit | 1 | //
// GetResponseBlogExample.swift
// OctoAPI
//
// Copyright (c) 2016 Maciej Kołek
//
// 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.
//
class GetResponseBlogExample : BaseExample {
override func run() {
let request = OctoRequest(endpoint: "posts")
request.paging = GetResponseBlogPaging(offset: 1, limit: 10)
GetResponseBlogConnector.sharedInstance.run(octoRequest: request) { (error, data, paging) in
if error == nil {
if let jsonData = data, let blogPosts = try? DecodableParser.decode(data: jsonData, type: [GRBlogPost].self), let post = blogPosts.first {
self.delegate?.exampleDidEndRunning(result: post.clearTitle)
}
} else {
if let octoError = error {
print("Error code captured: ", octoError.errorCode)
}
self.delegate?.exampleDidEndRunning(result: error!.error.localizedDescription)
}
}
}
}
| 74162e6cbcc88e3c8cd156efbfd1de41 | 44.733333 | 154 | 0.676871 | false | false | false | false |
mitchtreece/Bulletin | refs/heads/master | Example/Bulletin/NotchView.swift | mit | 1 | //
// NotchView.swift
// Bulletin_Example
//
// Created by Mitch Treece on 9/25/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
class NotchView: UIView {
var titleLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
backgroundColor = UIColor.black
titleLabel = UILabel()
titleLabel.backgroundColor = UIColor.clear
titleLabel.textColor = UIColor.white
titleLabel.font = UIFont.boldSystemFont(ofSize: 15)
titleLabel.textAlignment = .center
addSubview(titleLabel)
titleLabel.snp.makeConstraints { (make) in
make.top.equalTo(UIScreen.main.topNotch!.size.height)
make.left.bottom.right.equalTo(0)
}
}
override func layoutSubviews() {
super.layoutSubviews()
let cornerRadii = CGSize(width: UIScreen.main.topNotch!.cornerRadius, height: UIScreen.main.topNotch!.cornerRadius)
let mask = CAShapeLayer()
mask.path = UIBezierPath(roundedRect: frame, byRoundingCorners: [.bottomLeft, .bottomRight], cornerRadii: cornerRadii).cgPath
layer.mask = mask
}
}
| 3dc8da3edaa9367239f33da8a5e82810 | 24.727273 | 133 | 0.60424 | false | false | false | false |
v-adhithyan/cricket-score-applet | refs/heads/master | Cricket Score Applet/ScoreViewController.swift | mit | 1 | //
// ScoreViewController.swift
// Cricket Score Applet
//
// Created by Adhithyan Vijayakumar on 19/03/16.
// Copyright © 2016 Adhithyan Vijayakumar. All rights reserved.
//
import Cocoa
class ScoreViewController: NSViewController, XMLParserDelegate {
@IBOutlet var scoreCard: NSTextField!
var parser = XMLParser()
var posts = NSMutableArray()
var content = NSMutableString()
var currentItem = ""
var itemCount = 0
var appendCount = 0
var currentScoreIndex: Int = 0{
didSet{
updateScore()
}
}
//let scores = Score.all
//viewdidload is available only on 10.10 and later
override func viewDidLoad() {
if #available(OSX 10.10, *) {
super.viewDidLoad()
} else {
// Fallback on earlier versions
}
self.beginParsing()
updateScore()
}
func beginParsing(){
posts = []
parser = XMLParser(contentsOf: URL(string:"http://live-feeds.cricbuzz.com/CricbuzzFeed?format=xml")!)!
parser.delegate = self
parser.parse()
}
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
if(elementName == "item"){
itemCount = itemCount + 1;
content = NSMutableString()
}
switch(elementName){
case "title":
currentItem = "title"
break
case "description":
currentItem = "description"
break
case "link":
currentItem = "link"
break
default:
break
}
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if(elementName == "item"){
itemCount = itemCount - 1;
currentItem = ""
appendCount = 0
posts.add(content)
}
}
@nonobjc func parser(parser: XMLParser, foundCharacters string: String) {
if(itemCount == 1){
if(currentItem == "title" || currentItem == "description"){
if(appendCount < 3){
content.append(string)
}
appendCount = appendCount + 1;
}
}
}
func updateScore(){
scoreCard.stringValue = String(describing: posts[currentScoreIndex])
}
func removeHtml(string: String){
}
}
extension ScoreViewController{
@IBAction func goLeft(sender: NSButton){
currentScoreIndex = (currentScoreIndex - 1 + posts.count) % (posts.count)
}
@IBAction func goRight(sender: NSButton){
currentScoreIndex = (currentScoreIndex + 1) % (posts.count)
}
@IBAction func refresh(sender: NSButton){
beginParsing()
updateScore()
}
}
| 4ea5871206906fcc2d0890432750d0f8 | 24.857143 | 173 | 0.546636 | false | false | false | false |
railsware/Sleipnir | refs/heads/master | Sleipnir/Sleipnir/Internals/Runner.swift | mit | 1 | //
// Runner.swift
// Sleipnir
//
// Created by Artur Termenji on 6/19/14.
// Copyright (c) 2014 railsware. All rights reserved.
//
import Foundation
public struct Runner {
public enum RunOrder {
case Normal
case Random
}
static var currentExample: Example?
static var shouldOnlyRunFocused = false
public static func run(runOrder: RunOrder = RunOrder.Random, seed: Int? = nil) {
let specSeed = setUpRandomSeed(seed)
if (runOrder == RunOrder.Random) {
shuffleExamples(&SpecTable.topLevelGroups)
}
for exampleGroup in SpecTable.topLevelGroups {
if exampleGroup.hasFocusedExamples() {
shouldOnlyRunFocused = true
break
}
}
let dispatcher = ReportDispatcher(with: getReporters())
dispatcher.runWillStart(randomSeed: specSeed)
for exampleGroup in SpecTable.topLevelGroups {
exampleGroup.runWithDispatcher(dispatcher)
}
dispatcher.runDidComplete()
let result = dispatcher.result()
exit(Int32(result))
}
private static func shuffleExamples(inout groups: [ExampleGroup]) {
groups.shuffle()
for group in groups {
group.examples.shuffle()
if (group.childGroups.count > 0) {
shuffleExamples(&group.childGroups)
}
}
}
// TODO provide a way to define and load custom reporters
private static func getReporters() -> [Reporter] {
var reporters = [Reporter]()
reporters.append(DefaultReporter())
return reporters
}
private static func setUpRandomSeed(seed: Int? = nil) -> Int {
var specSeed: Int
if seed != nil {
specSeed = seed!
} else {
specSeed = Int(arc4random_uniform(9999))
}
srandom(UInt32(specSeed))
return specSeed
}
} | d366332d3def14349dcbb8a0160ea402 | 25.217949 | 84 | 0.568004 | false | false | false | false |
prolificinteractive/simcoe | refs/heads/master | Simcoe/Tracker.swift | mit | 1 | //
// SimcoeRecorder.swift
// Simcoe
//
// Created by Christopher Jones on 2/15/16.
// Copyright © 2016 Prolific Interactive. All rights reserved.
//
/// A recorder for SimcoeEvents.
public final class Tracker {
/// The output option for the recorder. Defaults to .Verbose.
public var outputOption: OutputOptions = .verbose
/// The error option for the recorder. Defaults to .Default.
public var errorOption: ErrorHandlingOption = .default
fileprivate let outputSources: [Output]
/// Initializes a new instance using the specified source as its output. By default, this is the
/// standard output console.
///
/// - Parameter outputSources: The source to use for general output.
init(outputSources: [Output] = [ConsoleOutput(), RemoteOutput(token: Simcoe.session)]) {
self.outputSources = outputSources
}
/// Records the event.
///
/// - Parameter event: The event to record.
func track(event: Event) {
let successfulProviders = event.writeEvents.map { writeEvent -> AnalyticsTracking? in
switch writeEvent.trackingResult {
case .success:
return writeEvent.provider
case .error(let message):
handleError(usingMessage: message, inProvider: writeEvent.provider)
return nil
}
}
write(event.description, forProviders: successfulProviders.compactMap { $0 })
}
fileprivate func handleError(usingMessage message: String, inProvider provider: AnalyticsTracking) {
switch errorOption {
case .default:
writeOut(withName: "** ANALYTICS ERROR **", message: message)
break
case .strict:
fatalError(message)
case .suppress:
break
}
}
fileprivate func write(_ description: String, forProviders providers: [AnalyticsTracking]) {
guard outputOption != .none else {
return
}
if outputOption == .verbose {
for provider in providers {
writeOut(withName: provider.name, message: description)
}
} else {
writeOut(withName: "Analytics", message: description)
}
}
fileprivate func writeOut(withName name: String, message: String) {
outputSources.forEach { $0.print("[\(name)] \(message)") }
}
}
| 73635fe5cb77878be5cd7606df0dcbbe | 31.459459 | 104 | 0.622814 | false | false | false | false |
huonw/swift | refs/heads/master | test/decl/protocol/conforms/near_miss_objc.swift | apache-2.0 | 1 | // RUN: %target-typecheck-verify-swift -enable-objc-interop
// Test "near misses" where a member of a class or extension thereof
// nearly matches an optional requirement, but does not exactly match.
@objc protocol P1 {
@objc optional func doSomething(a: Int, b: Double) // expected-note 2{{requirement 'doSomething(a:b:)' declared here}}
}
class C1a : P1 {
@objc func doSomething(a: Int, c: Double) { }
// expected-warning@-1{{instance method 'doSomething(a:c:)' nearly matches optional requirement 'doSomething(a:b:)' of protocol 'P1'}}
// expected-note@-2{{rename to 'doSomething(a:b:)' to satisfy this requirement}}{{34-34=b }}{{none}}
// expected-note@-3{{move 'doSomething(a:c:)' to an extension to silence this warning}}
// expected-note@-4{{make 'doSomething(a:c:)' private to silence this warning}}{{9-9=private }}
}
class C1b : P1 {
}
extension C1b {
@objc func doSomething(a: Int, c: Double) { } // don't warn
}
class C1c {
}
extension C1c : P1 {
func doSomething(a: Int, c: Double) { }
// expected-warning@-1{{instance method 'doSomething(a:c:)' nearly matches optional requirement 'doSomething(a:b:)' of protocol 'P1'}}
// expected-note@-2{{rename to 'doSomething(a:b:)' to satisfy this requirement}}{{28-28=b }}{{none}}
// expected-note@-3{{move 'doSomething(a:c:)' to another extension to silence this warning}}
// expected-note@-4{{make 'doSomething(a:c:)' private to silence this warning}}{{3-3=private }}
}
class C1d : P1 {
@objc private func doSomething(a: Int, c: Double) { } // don't warn
}
class C1e : P1 {
@nonobjc func doSomething(a: Int, c: Double) { } // don't warn
}
// Don't try to match an optional requirement against a declaration
// that already satisfies one witness.
@objc protocol P2 {
@objc optional func doSomething(a: Int, b: Double)
@objc optional func doSomething(a: Int, d: Double)
}
class C2a : P2 {
@objc func doSomething(a: Int, b: Double) { } // don't warn: this matches something
}
// Cope with base names that change.
@objc protocol P3 {
@objc optional func doSomethingWithPriority(_ a: Int, d: Double) // expected-note{{requirement 'doSomethingWithPriority(_:d:)' declared here}}
}
class C3a : P3 {
func doSomething(priority: Int, d: Double) { }
// expected-warning@-1{{instance method 'doSomething(priority:d:)' nearly matches optional requirement 'doSomethingWithPriority(_:d:)' of protocol 'P3'}}
// expected-note@-2{{rename to 'doSomethingWithPriority(_:d:)' to satisfy this requirement}}{{20-20=_ }}
// expected-note@-3{{move 'doSomething(priority:d:)' to an extension to silence this warning}}
// expected-note@-4{{make 'doSomething(priority:d:)' private to silence this warning}}{{3-3=private }}
}
@objc protocol P4 {
@objc optional func doSomething(priority: Int, d: Double) // expected-note{{requirement 'doSomething(priority:d:)' declared here}}
}
class C4a : P4 {
func doSomethingWithPriority(_ a: Int, d: Double) { }
// expected-warning@-1{{instance method 'doSomethingWithPriority(_:d:)' nearly matches optional requirement 'doSomething(priority:d:)' of protocol 'P4'}}
// expected-note@-2{{rename to 'doSomething(priority:d:)' to satisfy this requirement}}{{32-33=priority}}
// expected-note@-3{{move 'doSomethingWithPriority(_:d:)' to an extension to silence this warning}}
// expected-note@-4{{make 'doSomethingWithPriority(_:d:)' private to silence this warning}}{{3-3=private }}
}
@objc class SomeClass { }
@objc protocol P5 {
@objc optional func methodWithInt(_: Int, forSomeClass: SomeClass, dividingDouble: Double)
// expected-note@-1{{requirement 'methodWithInt(_:forSomeClass:dividingDouble:)' declared here}}
}
class C5a : P5 {
func method(_: Int, for someClass: SomeClass, dividing double: Double) { }
// expected-warning@-1{{instance method 'method(_:for:dividing:)' nearly matches optional requirement 'methodWithInt(_:forSomeClass:dividingDouble:)' of protocol 'P5'}}
// expected-note@-2{{rename to 'methodWithInt(_:forSomeClass:dividingDouble:)' to satisfy this requirement}}{{8-14=methodWithInt}}{{23-26=forSomeClass}}{{49-57=dividingDouble}}{{none}}
// expected-note@-3{{move 'method(_:for:dividing:)' to an extension to silence this warning}}
// expected-note@-4{{make 'method(_:for:dividing:)' private to silence this warning}}{{3-3=private }}
}
@objc protocol P6 {
@objc optional func method(_: Int, for someClass: SomeClass, dividing double: Double)
// expected-note@-1{{requirement 'method(_:for:dividing:)' declared here}}
}
class C6a : P6 {
func methodWithInt(_: Int, forSomeClass: SomeClass, dividingDouble: Double) { }
// expected-warning@-1{{instance method 'methodWithInt(_:forSomeClass:dividingDouble:)' nearly matches optional requirement 'method(_:for:dividing:)' of protocol 'P6'}}
// expected-note@-2{{rename to 'method(_:for:dividing:)' to satisfy this requirement}}{{8-21=method}}{{30-30=for }}{{55-55=dividing }}{{none}}
// expected-note@-3{{move 'methodWithInt(_:forSomeClass:dividingDouble:)' to an extension to silence this warning}}
// expected-note@-4{{make 'methodWithInt(_:forSomeClass:dividingDouble:)' private to silence this warning}}{{3-3=private }}
}
// Use the first note to always describe why it didn't match.
@objc protocol P7 {
@objc optional func method(foo: Float)
// expected-note@-1{{requirement 'method(foo:)' declared here}}
}
class C7a : P7 {
@objc func method(foo: Double) { }
// expected-warning@-1{{instance method 'method(foo:)' nearly matches optional requirement 'method(foo:)' of protocol 'P7'}}
// expected-note@-2{{candidate has non-matching type '(Double) -> ()'}}
// expected-note@-3{{move 'method(foo:)' to an extension to silence this warning}}
// expected-note@-4{{make 'method(foo:)' private to silence this warning}}
}
// Don't complain about near misses that satisfy other protocol
// requirements.
@objc protocol P8 {
@objc optional func foo(exactMatch: Int)
}
@objc protocol P9 : P8 {
@objc optional func foo(nearMatch: Int)
}
class C8Super : P8 { }
class C9Sub : C8Super, P9 {
func foo(exactMatch: Int) { }
}
// Don't complain about overriding methods that are near misses;
// the user cannot make it satisfy the protocol requirement.
class C10Super {
func foo(nearMatch: Int) { }
}
class C10Sub : C10Super, P8 {
override func foo(nearMatch: Int) { }
}
// Be more strict about near misses than we had previously.
@objc protocol P11 {
@objc optional func foo(wibble: Int)
}
class C11 : P11 {
func f(waggle: Int) { } // no warning
}
| b89b3a02fe0b7afa9727b3ae523e3c1e | 41.045161 | 186 | 0.701243 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | test/SILGen/class_resilience.swift | apache-2.0 | 3 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class -I %t %S/../Inputs/resilient_class.swift
// RUN: %target-swift-frontend -I %t -emit-silgen -enable-sil-ownership -enable-resilience %s | %FileCheck %s
import resilient_class
// Accessing final property of resilient class from different resilience domain
// through accessor
// CHECK-LABEL: sil @_T016class_resilience20finalPropertyOfOthery010resilient_A022ResilientOutsideParentCF
// CHECK: function_ref @_T015resilient_class22ResilientOutsideParentC13finalPropertySSvg
public func finalPropertyOfOther(_ other: ResilientOutsideParent) {
_ = other.finalProperty
}
public class MyResilientClass {
public final var finalProperty: String = "MyResilientClass.finalProperty"
}
// Accessing final property of resilient class from my resilience domain
// directly
// CHECK-LABEL: sil @_T016class_resilience19finalPropertyOfMineyAA16MyResilientClassCF
// CHECK: bb0([[ARG:%.*]] : @owned $MyResilientClass):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: ref_element_addr [[BORROWED_ARG]] : $MyResilientClass, #MyResilientClass.finalProperty
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
public func finalPropertyOfMine(_ other: MyResilientClass) {
_ = other.finalProperty
}
class SubclassOfOutsideChild : ResilientOutsideChild {
override func method() {}
func newMethod() {}
}
// Note: no entries for [inherited] methods
// CHECK-LABEL: sil_vtable SubclassOfOutsideChild {
// CHECK-NEXT: #ResilientOutsideParent.init!initializer.1: (ResilientOutsideParent.Type) -> () -> ResilientOutsideParent : _T016class_resilience22SubclassOfOutsideChildCACycfc [override]
// CHECK-NEXT: #ResilientOutsideParent.method!1: (ResilientOutsideParent) -> () -> () : _T016class_resilience22SubclassOfOutsideChildC6methodyyF [override]
// CHECK-NEXT: #SubclassOfOutsideChild.newMethod!1: (SubclassOfOutsideChild) -> () -> () : _T016class_resilience22SubclassOfOutsideChildC9newMethodyyF
// CHECK-NEXT: #SubclassOfOutsideChild.deinit!deallocator: _T016class_resilience22SubclassOfOutsideChildCfD
// CHECK-NEXT: }
| 8d267f6a98a91c082a32daded2d58925 | 48.729167 | 187 | 0.774194 | false | false | false | false |
albertochiwas/Rollo1000 | refs/heads/master | Rollo1000/Rollo1000/ViewController.swift | gpl-2.0 | 1 | //
// ViewController.swift
// Rollo1000
//
// Created by Alberto Pacheco on 27/10/15.
// Copyright © 2015 Alberto Pacheco. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var display: UILabel!
@IBOutlet weak var picker: UIPickerView!
@IBAction func aceptar(sender: UIButton) {
let num:Int = Int(display.text!)!
if num == oculto {
display.text = "Ganaste!"
oculto = generaNum(0,9)
} else if num < oculto {
display.text = "+Grande"
} else {
display.text = "+chico"
}
}
let digits = ["0","1","2","3","4","5","6","7","8","9"]
var oculto: Int = 0
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return digits.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return digits[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
display.text = digits[row]
}
override func viewDidLoad() {
super.viewDidLoad()
display.text = "Selecciona num 1-1000"
picker.dataSource = self
picker.delegate = self
oculto = generaNum(0,9)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| cfa8a00e66ddb2524f51e7fbdd2d8a1d | 25.444444 | 109 | 0.609844 | false | false | false | false |
dashboardearth/rewardsplatform | refs/heads/master | src/Halo-iOS-App/Halo/User Interface/HaloCardView.swift | apache-2.0 | 1 | //
// HaloCardView.swift
// Halo
//
// Created by Sattawat Suppalertporn on 24/7/17.
// Copyright © 2017 dashboardearth. All rights reserved.
//
import UIKit
class HaloCardView: UIView {
private static let haloSize:Double = 325
private var containerView:UIView?
private var topView:UIView?
private var middleView:UIView?
private var bottomView:UIView?
public var haloView:HaloView?
private var dailyProgressLabel:UILabel?
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0)
let containerView = UIView()
containerView.translatesAutoresizingMaskIntoConstraints = false
// add round corner and shadow
containerView.backgroundColor = UIColor.white
containerView.layer.cornerRadius = 12
containerView.layer.masksToBounds = true
self.addSubview(containerView)
self.containerView = containerView
let topView = UIView()
topView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(topView)
self.topView = topView
let middleView = UIView()
middleView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(middleView)
self.middleView = middleView
let bottomView = UIView()
bottomView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(bottomView)
self.bottomView = bottomView
// top view
// middle view
let viewModel = HaloTimeSlice()
let frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
let haloView = HaloView(frame: frame, viewModel: viewModel)
haloView.translatesAutoresizingMaskIntoConstraints = false
middleView.addSubview(haloView)
self.haloView = haloView
// bottom view
let dailyProgressLabel = UILabel()
dailyProgressLabel.translatesAutoresizingMaskIntoConstraints = false
dailyProgressLabel.text = "Daily progress"
dailyProgressLabel.font = UIFont.preferredFont(forTextStyle: .title3)
bottomView.addSubview(dailyProgressLabel)
self.dailyProgressLabel = dailyProgressLabel
self.setupConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupConstraints() {
let views = ["containerView": self.containerView!,
"topView": self.topView!,
"middleView": self.middleView!,
"bottomView": self.bottomView!,
"haloView": self.haloView!,
"dailyProgressLabel": self.dailyProgressLabel!] as [String : Any]
var allConstraints = [NSLayoutConstraint]()
allConstraints.append(contentsOf: NSLayoutConstraint.constraints(
withVisualFormat: "V:|-8-[containerView]-8-|",
options: [],
metrics: nil,
views: views))
allConstraints.append(contentsOf: NSLayoutConstraint.constraints(
withVisualFormat: "H:|-8-[containerView]-8-|",
options: [],
metrics: nil,
views: views))
// overall layout
allConstraints.append(contentsOf: NSLayoutConstraint.constraints(
withVisualFormat: "V:|[topView][middleView][bottomView]|",
options: [],
metrics: nil,
views: views))
allConstraints.append(contentsOf: NSLayoutConstraint.constraints(
withVisualFormat: "H:|[topView]|",
options: [],
metrics: nil,
views: views))
allConstraints.append(contentsOf: NSLayoutConstraint.constraints(
withVisualFormat: "H:|[middleView]|",
options: [],
metrics: nil,
views: views))
allConstraints.append(contentsOf: NSLayoutConstraint.constraints(
withVisualFormat: "H:|[bottomView]|",
options: [],
metrics: nil,
views: views))
// top view
// middle view
let haloView = self.haloView!
let middleView = self.middleView!
allConstraints.append(NSLayoutConstraint(item: haloView, attribute: .centerX, relatedBy: .equal, toItem: middleView, attribute: .centerX, multiplier: 1.0, constant: 0.0))
allConstraints.append(NSLayoutConstraint(item: haloView, attribute: .centerY, relatedBy: .equal, toItem: middleView, attribute: .centerY, multiplier: 1.0, constant: 0.0))
allConstraints.append(NSLayoutConstraint(item: haloView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: CGFloat(HaloCardView.haloSize)))
allConstraints.append(NSLayoutConstraint(item: haloView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: CGFloat(HaloCardView.haloSize)))
// bottom view
allConstraints.append(contentsOf: NSLayoutConstraint.constraints(
withVisualFormat: "V:|[dailyProgressLabel]-4-|",
options: [],
metrics: nil,
views: views))
allConstraints.append(contentsOf: NSLayoutConstraint.constraints(
withVisualFormat: "H:|-8-[dailyProgressLabel]-8-|",
options: [.alignAllCenterY],
metrics: nil,
views: views))
NSLayoutConstraint.activate(allConstraints)
}
}
| 7381ee6ec6586ccf6ae7fa0bc41ba96c | 35.859873 | 204 | 0.620356 | false | false | false | false |
eggswift/ESTabBarController | refs/heads/master | ESTabBarControllerExample/ESTabBarControllerExample/Content/Irregularity/ExampleIrregularityContentView.swift | mit | 1 | //
// ExampleIrregularityContentView.swift
// ESTabBarControllerExample
//
// Created by lihao on 2017/2/9.
// Copyright © 2018年 Egg Swift. All rights reserved.
//
import UIKit
import pop
import ESTabBarController
class ExampleIrregularityBasicContentView: ExampleBouncesContentView {
override init(frame: CGRect) {
super.init(frame: frame)
textColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0)
highlightTextColor = UIColor.init(red: 23/255.0, green: 149/255.0, blue: 158/255.0, alpha: 1.0)
iconColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0)
highlightIconColor = UIColor.init(red: 23/255.0, green: 149/255.0, blue: 158/255.0, alpha: 1.0)
backdropColor = UIColor.init(red: 10/255.0, green: 66/255.0, blue: 91/255.0, alpha: 1.0)
highlightBackdropColor = UIColor.init(red: 10/255.0, green: 66/255.0, blue: 91/255.0, alpha: 1.0)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ExampleIrregularityContentView: ESTabBarItemContentView {
override init(frame: CGRect) {
super.init(frame: frame)
self.imageView.backgroundColor = UIColor.init(red: 23/255.0, green: 149/255.0, blue: 158/255.0, alpha: 1.0)
self.imageView.layer.borderWidth = 3.0
self.imageView.layer.borderColor = UIColor.init(white: 235 / 255.0, alpha: 1.0).cgColor
self.imageView.layer.cornerRadius = 35
self.insets = UIEdgeInsets.init(top: -32, left: 0, bottom: 0, right: 0)
let transform = CGAffineTransform.identity
self.imageView.transform = transform
self.superview?.bringSubviewToFront(self)
textColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0)
highlightTextColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0)
iconColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0)
highlightIconColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0)
backdropColor = .clear
highlightBackdropColor = .clear
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let p = CGPoint.init(x: point.x - imageView.frame.origin.x, y: point.y - imageView.frame.origin.y)
return sqrt(pow(imageView.bounds.size.width / 2.0 - p.x, 2) + pow(imageView.bounds.size.height / 2.0 - p.y, 2)) < imageView.bounds.size.width / 2.0
}
override func updateLayout() {
super.updateLayout()
self.imageView.sizeToFit()
self.imageView.center = CGPoint.init(x: self.bounds.size.width / 2.0, y: self.bounds.size.height / 2.0)
}
public override func selectAnimation(animated: Bool, completion: (() -> ())?) {
let view = UIView.init(frame: CGRect.init(origin: CGPoint.zero, size: CGSize(width: 2.0, height: 2.0)))
view.layer.cornerRadius = 1.0
view.layer.opacity = 0.5
view.backgroundColor = UIColor.init(red: 10/255.0, green: 66/255.0, blue: 91/255.0, alpha: 1.0)
self.addSubview(view)
playMaskAnimation(animateView: view, target: self.imageView, completion: {
[weak view] in
view?.removeFromSuperview()
completion?()
})
}
public override func reselectAnimation(animated: Bool, completion: (() -> ())?) {
completion?()
}
public override func deselectAnimation(animated: Bool, completion: (() -> ())?) {
completion?()
}
public override func highlightAnimation(animated: Bool, completion: (() -> ())?) {
UIView.beginAnimations("small", context: nil)
UIView.setAnimationDuration(0.2)
let transform = self.imageView.transform.scaledBy(x: 0.8, y: 0.8)
self.imageView.transform = transform
UIView.commitAnimations()
completion?()
}
public override func dehighlightAnimation(animated: Bool, completion: (() -> ())?) {
UIView.beginAnimations("big", context: nil)
UIView.setAnimationDuration(0.2)
let transform = CGAffineTransform.identity
self.imageView.transform = transform
UIView.commitAnimations()
completion?()
}
private func playMaskAnimation(animateView view: UIView, target: UIView, completion: (() -> ())?) {
view.center = CGPoint.init(x: target.frame.origin.x + target.frame.size.width / 2.0, y: target.frame.origin.y + target.frame.size.height / 2.0)
let scale = POPBasicAnimation.init(propertyNamed: kPOPLayerScaleXY)
scale?.fromValue = NSValue.init(cgSize: CGSize.init(width: 1.0, height: 1.0))
scale?.toValue = NSValue.init(cgSize: CGSize.init(width: 36.0, height: 36.0))
scale?.beginTime = CACurrentMediaTime()
scale?.duration = 0.3
scale?.timingFunction = CAMediaTimingFunction.init(name: CAMediaTimingFunctionName.easeOut)
scale?.removedOnCompletion = true
let alpha = POPBasicAnimation.init(propertyNamed: kPOPLayerOpacity)
alpha?.fromValue = 0.6
alpha?.toValue = 0.6
alpha?.beginTime = CACurrentMediaTime()
alpha?.duration = 0.25
alpha?.timingFunction = CAMediaTimingFunction.init(name: CAMediaTimingFunctionName.easeOut)
alpha?.removedOnCompletion = true
view.layer.pop_add(scale, forKey: "scale")
view.layer.pop_add(alpha, forKey: "alpha")
scale?.completionBlock = ({ animation, finished in
completion?()
})
}
}
| e921242bde83ac8ede45a90536eba8a0 | 41.291045 | 155 | 0.639845 | false | false | false | false |
csnu17/My-Swift-learning | refs/heads/master | ComposingComplexInterfaces/Landmarks/Landmarks/Models/Data.swift | mit | 1 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
Helpers for loading images and data.
*/
import Foundation
import CoreLocation
import UIKit
import SwiftUI
let landmarkData: [Landmark] = load("landmarkData.json")
let hikeData: [Hike] = load("hikeData.json")
func load<T: Decodable>(_ filename: String, as type: T.Type = T.self) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}
final class ImageStore {
fileprivate typealias _ImageDictionary = [String: [Int: CGImage]]
fileprivate var images: _ImageDictionary = [:]
fileprivate static var originalSize = 250
fileprivate static var scale = 2
static var shared = ImageStore()
func image(name: String, size: Int) -> Image {
let index = _guaranteeInitialImage(name: name)
let sizedImage = images.values[index][size]
?? _sizeImage(images.values[index][ImageStore.originalSize]!, to: size * ImageStore.scale)
images.values[index][size] = sizedImage
return Image(sizedImage, scale: Length(ImageStore.scale), label: Text(verbatim: name))
}
fileprivate func _guaranteeInitialImage(name: String) -> _ImageDictionary.Index {
if let index = images.index(forKey: name) { return index }
guard
let url = Bundle.main.url(forResource: name, withExtension: "jpg"),
let imageSource = CGImageSourceCreateWithURL(url as NSURL, nil),
let image = CGImageSourceCreateImageAtIndex(imageSource, 0, nil)
else {
fatalError("Couldn't load image \(name).jpg from main bundle.")
}
images[name] = [ImageStore.originalSize: image]
return images.index(forKey: name)!
}
fileprivate func _sizeImage(_ image: CGImage, to size: Int) -> CGImage {
guard
let colorSpace = image.colorSpace,
let context = CGContext(
data: nil,
width: size, height: size,
bitsPerComponent: image.bitsPerComponent,
bytesPerRow: image.bytesPerRow,
space: colorSpace,
bitmapInfo: image.bitmapInfo.rawValue)
else {
fatalError("Couldn't create graphics context.")
}
context.interpolationQuality = .high
context.draw(image, in: CGRect(x: 0, y: 0, width: size, height: size))
if let sizedImage = context.makeImage() {
return sizedImage
} else {
fatalError("Couldn't resize image.")
}
}
}
| 3ff64a62cb7c2337a5fc90b81eec1bb5 | 31.284211 | 102 | 0.606456 | false | false | false | false |
hgl888/firefox-ios | refs/heads/master | Client/Frontend/Settings/SettingsTableViewController.swift | mpl-2.0 | 2 | /* 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 Account
import Base32
import Shared
import UIKit
import XCGLogger
private var ShowDebugSettings: Bool = false
private var DebugSettingsClickCount: Int = 0
// The following are only here because we use master for L10N and otherwise these strings would disappear from the v1.0 release
private let Bug1204635_S1 = NSLocalizedString("Clear Everything", tableName: "ClearPrivateData", comment: "Title of the Clear private data dialog.")
private let Bug1204635_S2 = NSLocalizedString("Are you sure you want to clear all of your data? This will also close all open tabs.", tableName: "ClearPrivateData", comment: "Message shown in the dialog prompting users if they want to clear everything")
private let Bug1204635_S3 = NSLocalizedString("Clear", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to Clear private data dialog")
private let Bug1204635_S4 = NSLocalizedString("Cancel", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to cancel clear private data dialog")
// A base TableViewCell, to help minimize initialization and allow recycling.
class SettingsTableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
indentationWidth = 0
layoutMargins = UIEdgeInsetsZero
// So that the seperator line goes all the way to the left edge.
separatorInset = UIEdgeInsetsZero
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// A base setting class that shows a title. You probably want to subclass this, not use it directly.
class Setting {
private var _title: NSAttributedString?
// The url the SettingsContentViewController will show, e.g. Licenses and Privacy Policy.
var url: NSURL? { return nil }
// The title shown on the pref.
var title: NSAttributedString? { return _title }
// An optional second line of text shown on the pref.
var status: NSAttributedString? { return nil }
// Whether or not to show this pref.
var hidden: Bool { return false }
var style: UITableViewCellStyle { return .Subtitle }
var accessoryType: UITableViewCellAccessoryType { return .None }
// Called when the cell is setup. Call if you need the default behaviour.
func onConfigureCell(cell: UITableViewCell) {
cell.detailTextLabel?.attributedText = status
cell.textLabel?.attributedText = title
cell.accessoryType = accessoryType
cell.accessoryView = nil
}
// Called when the pref is tapped.
func onClick(navigationController: UINavigationController?) { return }
// Helper method to set up and push a SettingsContentViewController
func setUpAndPushSettingsContentViewController(navigationController: UINavigationController?) {
if let url = self.url {
let viewController = SettingsContentViewController()
viewController.settingsTitle = self.title
viewController.url = url
navigationController?.pushViewController(viewController, animated: true)
}
}
init(title: NSAttributedString? = nil) {
self._title = title
}
}
// A setting in the sections panel. Contains a sublist of Settings
class SettingSection : Setting {
private let children: [Setting]
init(title: NSAttributedString? = nil, children: [Setting]) {
self.children = children
super.init(title: title)
}
var count: Int {
var count = 0
for setting in children {
if !setting.hidden {
count++
}
}
return count
}
subscript(val: Int) -> Setting? {
var i = 0
for setting in children {
if !setting.hidden {
if i == val {
return setting
}
i++
}
}
return nil
}
}
// A helper class for settings with a UISwitch.
// Takes and optional settingsDidChange callback and status text.
class BoolSetting: Setting {
private let prefKey: String
private let prefs: Prefs
private let defaultValue: Bool
private let settingDidChange: ((Bool) -> Void)?
private let statusText: String?
init(prefs: Prefs, prefKey: String, defaultValue: Bool, titleText: String, statusText: String? = nil, settingDidChange: ((Bool) -> Void)? = nil) {
self.prefs = prefs
self.prefKey = prefKey
self.defaultValue = defaultValue
self.settingDidChange = settingDidChange
self.statusText = statusText
super.init(title: NSAttributedString(string: titleText, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override var status: NSAttributedString? {
if let text = statusText {
return NSAttributedString(string: text, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewHeaderTextColor])
} else {
return nil
}
}
override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
control.on = prefs.boolForKey(prefKey) ?? defaultValue
cell.accessoryView = control
}
@objc func switchValueChanged(control: UISwitch) {
prefs.setBool(control.on, forKey: prefKey)
settingDidChange?(control.on)
}
}
// A helper class for prefs that deal with sync. Handles reloading the tableView data if changes to
// the fxAccount happen.
private class AccountSetting: Setting, FxAContentViewControllerDelegate {
unowned var settings: SettingsTableViewController
var profile: Profile {
return settings.profile
}
override var title: NSAttributedString? { return nil }
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
private override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
if settings.profile.getAccount() != nil {
cell.selectionStyle = .None
}
}
override var accessoryType: UITableViewCellAccessoryType { return .None }
func contentViewControllerDidSignIn(viewController: FxAContentViewController, data: JSON) -> Void {
if data["keyFetchToken"].asString == nil || data["unwrapBKey"].asString == nil {
// The /settings endpoint sends a partial "login"; ignore it entirely.
NSLog("Ignoring didSignIn with keyFetchToken or unwrapBKey missing.")
return
}
// TODO: Error handling.
let account = FirefoxAccount.fromConfigurationAndJSON(profile.accountConfiguration, data: data)!
settings.profile.setAccount(account)
// Reload the data to reflect the new Account immediately.
settings.tableView.reloadData()
// And start advancing the Account state in the background as well.
settings.SELrefresh()
settings.navigationController?.popToRootViewControllerAnimated(true)
}
func contentViewControllerDidCancel(viewController: FxAContentViewController) {
NSLog("didCancel")
settings.navigationController?.popToRootViewControllerAnimated(true)
}
}
private class WithAccountSetting: AccountSetting {
override var hidden: Bool { return !profile.hasAccount() }
}
private class WithoutAccountSetting: AccountSetting {
override var hidden: Bool { return profile.hasAccount() }
}
// Sync setting for connecting a Firefox Account. Shown when we don't have an account.
private class ConnectSetting: WithoutAccountSetting {
override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator }
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Sign In", comment: "Text message / button in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
let viewController = FxAContentViewController()
viewController.delegate = self
viewController.url = settings.profile.accountConfiguration.signInURL
navigationController?.pushViewController(viewController, animated: true)
}
}
// Sync setting for disconnecting a Firefox Account. Shown when we have an account.
private class DisconnectSetting: WithAccountSetting {
override var accessoryType: UITableViewCellAccessoryType { return .None }
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Log Out", comment: "Button in settings screen to disconnect from your account"), attributes: [NSForegroundColorAttributeName: UIConstants.DestructiveRed])
}
override func onClick(navigationController: UINavigationController?) {
let alertController = UIAlertController(
title: NSLocalizedString("Log Out?", comment: "Title of the 'log out firefox account' alert"),
message: NSLocalizedString("Firefox will stop syncing with your account, but won’t delete any of your browsing data on this device.", comment: "Text of the 'log out firefox account' alert"),
preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(
UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel button in the 'log out firefox account' alert"), style: .Cancel) { (action) in
// Do nothing.
})
alertController.addAction(
UIAlertAction(title: NSLocalizedString("Log Out", comment: "Disconnect button in the 'log out firefox account' alert"), style: .Destructive) { (action) in
self.settings.profile.removeAccount()
// Refresh, to show that we no longer have an Account immediately.
self.settings.SELrefresh()
})
navigationController?.presentViewController(alertController, animated: true, completion: nil)
}
}
private class SyncNowSetting: WithAccountSetting {
private let syncNowTitle = NSAttributedString(string: NSLocalizedString("Sync Now", comment: "Sync Firefox Account"), attributes: [NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: UIConstants.DefaultStandardFont])
private let syncingTitle = NSAttributedString(string: NSLocalizedString("Syncing…", comment: "Syncing Firefox Account"), attributes: [NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont.systemFontOfSize(UIConstants.DefaultStandardFontSize, weight: UIFontWeightRegular)])
override var accessoryType: UITableViewCellAccessoryType { return .None }
override var style: UITableViewCellStyle { return .Value1 }
override var title: NSAttributedString? {
return profile.syncManager.isSyncing ? syncingTitle : syncNowTitle
}
override var status: NSAttributedString? {
if let timestamp = profile.prefs.timestampForKey(PrefsKeys.KeyLastSyncFinishTime) {
let label = NSLocalizedString("Last synced: %@", comment: "Last synced time label beside Sync Now setting option. Argument is the relative date string.")
let formattedLabel = String(format: label, NSDate.fromTimestamp(timestamp).toRelativeTimeString())
let attributedString = NSMutableAttributedString(string: formattedLabel)
let attributes = [NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont.systemFontOfSize(12, weight: UIFontWeightRegular)]
let range = NSMakeRange(0, attributedString.length)
attributedString.setAttributes(attributes, range: range)
return attributedString
}
return nil
}
override func onConfigureCell(cell: UITableViewCell) {
cell.textLabel?.attributedText = title
cell.detailTextLabel?.attributedText = status
cell.accessoryType = accessoryType
cell.accessoryView = nil
cell.userInteractionEnabled = !profile.syncManager.isSyncing
}
override func onClick(navigationController: UINavigationController?) {
profile.syncManager.syncEverything()
}
}
// Sync setting that shows the current Firefox Account status.
private class AccountStatusSetting: WithAccountSetting {
override var accessoryType: UITableViewCellAccessoryType {
if let account = profile.getAccount() {
switch account.actionNeeded {
case .NeedsVerification:
// We link to the resend verification email page.
return .DisclosureIndicator
case .NeedsPassword:
// We link to the re-enter password page.
return .DisclosureIndicator
case .None, .NeedsUpgrade:
// In future, we'll want to link to /settings and an upgrade page, respectively.
return .None
}
}
return .DisclosureIndicator
}
override var title: NSAttributedString? {
if let account = profile.getAccount() {
return NSAttributedString(string: account.email, attributes: [NSFontAttributeName: UIConstants.DefaultStandardFontBold, NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
return nil
}
override var status: NSAttributedString? {
if let account = profile.getAccount() {
switch account.actionNeeded {
case .None:
return nil
case .NeedsVerification:
return NSAttributedString(string: NSLocalizedString("Verify your email address.", comment: "Text message in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
case .NeedsPassword:
let string = NSLocalizedString("Enter your password to connect.", comment: "Text message in the settings table view")
let range = NSRange(location: 0, length: string.characters.count)
let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1)
let attrs = [NSForegroundColorAttributeName : orange]
let res = NSMutableAttributedString(string: string)
res.setAttributes(attrs, range: range)
return res
case .NeedsUpgrade:
let string = NSLocalizedString("Upgrade Firefox to connect.", comment: "Text message in the settings table view")
let range = NSRange(location: 0, length: string.characters.count)
let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1)
let attrs = [NSForegroundColorAttributeName : orange]
let res = NSMutableAttributedString(string: string)
res.setAttributes(attrs, range: range)
return res
}
}
return nil
}
override func onClick(navigationController: UINavigationController?) {
let viewController = FxAContentViewController()
viewController.delegate = self
if let account = profile.getAccount() {
switch account.actionNeeded {
case .NeedsVerification:
let cs = NSURLComponents(URL: account.configuration.settingsURL, resolvingAgainstBaseURL: false)
cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email))
viewController.url = cs?.URL
case .NeedsPassword:
let cs = NSURLComponents(URL: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false)
cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email))
viewController.url = cs?.URL
case .None, .NeedsUpgrade:
// In future, we'll want to link to /settings and an upgrade page, respectively.
return
}
}
navigationController?.pushViewController(viewController, animated: true)
}
}
// For great debugging!
private class RequirePasswordDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsPassword {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: require password", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
profile.getAccount()?.makeSeparated()
settings.tableView.reloadData()
}
}
// For great debugging!
private class RequireUpgradeDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsUpgrade {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: require upgrade", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
profile.getAccount()?.makeDoghouse()
settings.tableView.reloadData()
}
}
// For great debugging!
private class ForgetSyncAuthStateDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let _ = profile.getAccount() {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: forget Sync auth state", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
profile.getAccount()?.syncAuthState.invalidate()
settings.tableView.reloadData()
}
}
// For great debugging!
private class HiddenSetting: Setting {
let settings: SettingsTableViewController
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override var hidden: Bool {
return !ShowDebugSettings
}
}
extension NSFileManager {
public func removeItemInDirectory(directory: String, named: String) throws {
if let file = NSURL.fileURLWithPath(directory).URLByAppendingPathComponent(named).path {
try self.removeItemAtPath(file)
}
}
}
private class DeleteExportedDataSetting: HiddenSetting {
override var title: NSAttributedString? {
// Not localized for now.
return NSAttributedString(string: "Debug: delete exported databases", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
do {
try NSFileManager.defaultManager().removeItemInDirectory(documentsPath, named: "browser.db")
} catch {
print("Couldn't delete exported data: \(error).")
}
}
}
private class ExportBrowserDataSetting: HiddenSetting {
override var title: NSAttributedString? {
// Not localized for now.
return NSAttributedString(string: "Debug: copy databases to app container", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
if let browserDB = NSURL.fileURLWithPath(documentsPath).URLByAppendingPathComponent("browser.db").path {
do {
try self.settings.profile.files.copy("browser.db", toAbsolutePath: browserDB)
} catch {
print("Couldn't export browser data: \(error).")
}
}
}
}
// Show the current version of Firefox
private class VersionSetting : Setting {
let settings: SettingsTableViewController
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override var title: NSAttributedString? {
let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
let buildNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion") as! String
return NSAttributedString(string: String(format: NSLocalizedString("Version %@ (%@)", comment: "Version number of Firefox shown in settings"), appVersion, buildNumber), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
private override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
cell.selectionStyle = .None
}
override func onClick(navigationController: UINavigationController?) {
if AppConstants.BuildChannel != .Aurora {
DebugSettingsClickCount += 1
if DebugSettingsClickCount >= 5 {
DebugSettingsClickCount = 0
ShowDebugSettings = !ShowDebugSettings
settings.tableView.reloadData()
}
}
}
}
// Opens the the license page in a new tab
private class LicenseAndAcknowledgementsSetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Licenses", comment: "Settings item that opens a tab containing the licenses. See http://mzl.la/1NSAWCG"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override var url: NSURL? {
return NSURL(string: WebServer.sharedInstance.URLForResource("license", module: "about"))
}
override func onClick(navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// Opens about:rights page in the content view controller
private class YourRightsSetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Your Rights", comment: "Your Rights settings section title"), attributes:
[NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override var url: NSURL? {
return NSURL(string: "https://www.mozilla.org/about/legal/terms/firefox/")
}
private override func onClick(navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// Opens the on-boarding screen again
private class ShowIntroductionSetting: Setting {
let profile: Profile
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Show Tour", comment: "Show the on-boarding screen again from the settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
navigationController?.dismissViewControllerAnimated(true, completion: {
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
appDelegate.browserViewController.presentIntroViewController(true)
}
})
}
}
private class SendFeedbackSetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Send Feedback", comment: "Show an input.mozilla.org page where people can submit feedback"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override var url: NSURL? {
let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
return NSURL(string: "https://input.mozilla.org/feedback/fxios/\(appVersion)")
}
override func onClick(navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// Opens the the SUMO page in a new tab
private class OpenSupportPageSetting: Setting {
init() {
super.init(title: NSAttributedString(string: NSLocalizedString("Help", comment: "Show the SUMO support page from the Support section in the settings. see http://mzl.la/1dmM8tZ"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
navigationController?.dismissViewControllerAnimated(true, completion: {
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
let rootNavigationController = appDelegate.rootViewController
rootNavigationController.popViewControllerAnimated(true)
if let url = NSURL(string: "https://support.mozilla.org/products/ios") {
appDelegate.browserViewController.openURLInNewTab(url)
}
}
})
}
}
// Opens the search settings pane
private class SearchSetting: Setting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator }
override var style: UITableViewCellStyle { return .Value1 }
override var status: NSAttributedString { return NSAttributedString(string: profile.searchEngines.defaultEngine.shortName) }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Search", comment: "Open search section of settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
let viewController = SearchSettingsTableViewController()
viewController.model = profile.searchEngines
navigationController?.pushViewController(viewController, animated: true)
}
}
private class ClearPrivateDataSetting: Setting {
let profile: Profile
var tabManager: TabManager!
override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
self.tabManager = settings.tabManager
let clearTitle = NSLocalizedString("Clear Private Data", comment: "Label used as an item in Settings. When touched it will open a dialog prompting the user to make sure they want to clear all of their private data.")
super.init(title: NSAttributedString(string: clearTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
let viewController = ClearPrivateDataTableViewController()
viewController.profile = profile
viewController.tabManager = tabManager
navigationController?.pushViewController(viewController, animated: true)
}
}
private class PrivacyPolicySetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Privacy Policy", comment: "Show Firefox Browser Privacy Policy page from the Privacy section in the settings. See https://www.mozilla.org/privacy/firefox/"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override var url: NSURL? {
return NSURL(string: "https://www.mozilla.org/privacy/firefox/")
}
override func onClick(navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// The base settings view controller.
class SettingsTableViewController: UITableViewController {
private let Identifier = "CellIdentifier"
private let SectionHeaderIdentifier = "SectionHeaderIdentifier"
private var settings = [SettingSection]()
var profile: Profile!
var tabManager: TabManager!
override func viewDidLoad() {
super.viewDidLoad()
let privacyTitle = NSLocalizedString("Privacy", comment: "Privacy section title")
let accountDebugSettings: [Setting]
if AppConstants.BuildChannel != .Aurora {
accountDebugSettings = [
// Debug settings:
RequirePasswordDebugSetting(settings: self),
RequireUpgradeDebugSetting(settings: self),
ForgetSyncAuthStateDebugSetting(settings: self),
]
} else {
accountDebugSettings = []
}
let prefs = profile.prefs
var generalSettings = [
SearchSetting(settings: self),
BoolSetting(prefs: prefs, prefKey: "blockPopups", defaultValue: true,
titleText: NSLocalizedString("Block Pop-up Windows", comment: "Block pop-up windows setting")),
BoolSetting(prefs: prefs, prefKey: "saveLogins", defaultValue: true,
titleText: NSLocalizedString("Save Logins", comment: "Setting to enable the built-in password manager")),
]
// There is nothing to show in the Customize section if we don't include the compact tab layout
// setting on iPad. When more options are added that work on both device types, this logic can
// be changed.
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
generalSettings += [
BoolSetting(prefs: prefs, prefKey: "CompactTabLayout", defaultValue: true,
titleText: NSLocalizedString("Use Compact Tabs", comment: "Setting to enable compact tabs in the tab overview"))
]
}
settings += [
SettingSection(title: nil, children: [
// Without a Firefox Account:
ConnectSetting(settings: self),
// With a Firefox Account:
AccountStatusSetting(settings: self),
SyncNowSetting(settings: self)
] + accountDebugSettings),
SettingSection(title: NSAttributedString(string: NSLocalizedString("General", comment: "General settings section title")), children: generalSettings)
]
var privacySettings: [Setting] = [ClearPrivateDataSetting(settings: self)]
if #available(iOS 9, *) {
privacySettings += [
BoolSetting(prefs: prefs,
prefKey: "settings.closePrivateTabs",
defaultValue: false,
titleText: NSLocalizedString("Close Private Tabs", tableName: "PrivateBrowsing", comment: "Setting for closing private tabs"),
statusText: NSLocalizedString("When Leaving Private Browsing", tableName: "PrivateBrowsing", comment: "Will be displayed in Settings under 'Close Private Tabs'"))
]
}
privacySettings += [
BoolSetting(prefs: prefs, prefKey: "crashreports.send.always", defaultValue: false,
titleText: NSLocalizedString("Send Crash Reports", comment: "Setting to enable the sending of crash reports"),
settingDidChange: { configureActiveCrashReporter($0) }),
PrivacyPolicySetting()
]
settings += [
SettingSection(title: NSAttributedString(string: privacyTitle), children: privacySettings),
SettingSection(title: NSAttributedString(string: NSLocalizedString("Support", comment: "Support section title")), children: [
ShowIntroductionSetting(settings: self),
SendFeedbackSetting(),
OpenSupportPageSetting()
]),
SettingSection(title: NSAttributedString(string: NSLocalizedString("About", comment: "About settings section title")), children: [
VersionSetting(settings: self),
LicenseAndAcknowledgementsSetting(),
YourRightsSetting(),
DisconnectSetting(settings: self),
ExportBrowserDataSetting(settings: self),
DeleteExportedDataSetting(settings: self),
])
]
navigationItem.title = NSLocalizedString("Settings", comment: "Settings")
navigationItem.leftBarButtonItem = UIBarButtonItem(
title: NSLocalizedString("Done", comment: "Done button on left side of the Settings view controller title bar"),
style: UIBarButtonItemStyle.Done,
target: navigationController, action: "SELdone")
tableView.registerClass(SettingsTableViewCell.self, forCellReuseIdentifier: Identifier)
tableView.registerClass(SettingsTableSectionHeaderView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier)
tableView.tableFooterView = SettingsTableFooterView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 128))
tableView.separatorColor = UIConstants.TableViewSeparatorColor
tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELsyncDidChangeState", name: ProfileDidStartSyncingNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELsyncDidChangeState", name: ProfileDidFinishSyncingNotification, object: nil)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
SELrefresh()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: ProfileDidStartSyncingNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: ProfileDidFinishSyncingNotification, object: nil)
}
@objc private func SELsyncDidChangeState() {
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
@objc private func SELrefresh() {
// Through-out, be aware that modifying the control while a refresh is in progress is /not/ supported and will likely crash the app.
if let account = self.profile.getAccount() {
account.advance().upon { _ in
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.tableView.reloadData()
}
}
} else {
self.tableView.reloadData()
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let section = settings[indexPath.section]
if let setting = section[indexPath.row] {
var cell: UITableViewCell!
if let _ = setting.status {
// Work around http://stackoverflow.com/a/9999821 and http://stackoverflow.com/a/25901083 by using a new cell.
// I could not make any setNeedsLayout solution work in the case where we disconnect and then connect a new account.
// Be aware that dequeing and then ignoring a cell appears to cause issues; only deque a cell if you're going to return it.
cell = SettingsTableViewCell(style: setting.style, reuseIdentifier: nil)
} else {
cell = tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath)
}
setting.onConfigureCell(cell)
return cell
}
return tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return settings.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let section = settings[section]
return section.count
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionHeaderIdentifier) as! SettingsTableSectionHeaderView
let sectionSetting = settings[section]
if let sectionTitle = sectionSetting.title?.string {
headerView.titleLabel.text = sectionTitle
}
// Hide the top border for the top section to avoid having a double line at the top
if section == 0 {
headerView.showTopBorder = false
} else {
headerView.showTopBorder = true
}
return headerView
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// empty headers should be 13px high, but headers with text should be 44
var height: CGFloat = 13
let section = settings[section]
if let sectionTitle = section.title {
if sectionTitle.length > 0 {
height = 44
}
}
return height
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
let section = settings[indexPath.section]
if let setting = section[indexPath.row] {
setting.onClick(navigationController)
}
return nil
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
//make account/sign-in and close private tabs rows taller, as per design specs
if indexPath.section == 0 && indexPath.row == 0 {
return 64
}
if #available(iOS 9, *) {
if indexPath.section == 2 && indexPath.row == 1 {
return 64
}
}
return 44
}
}
class SettingsTableFooterView: UIView {
var logo: UIImageView = {
var image = UIImageView(image: UIImage(named: "settingsFlatfox"))
image.contentMode = UIViewContentMode.Center
return image
}()
private lazy var topBorder: CALayer = {
let topBorder = CALayer()
topBorder.backgroundColor = UIConstants.SeparatorColor.CGColor
return topBorder
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIConstants.TableViewHeaderBackgroundColor
layer.addSublayer(topBorder)
addSubview(logo)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
topBorder.frame = CGRectMake(0.0, 0.0, frame.size.width, 0.5)
logo.center = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
}
}
class SettingsTableSectionHeaderView: UITableViewHeaderFooterView {
var showTopBorder: Bool = true {
didSet {
topBorder.hidden = !showTopBorder
}
}
var showBottomBorder: Bool = true {
didSet {
bottomBorder.hidden = !showBottomBorder
}
}
var titleLabel: UILabel = {
var headerLabel = UILabel()
var frame = headerLabel.frame
frame.origin.x = 15
frame.origin.y = 25
headerLabel.frame = frame
headerLabel.textColor = UIConstants.TableViewHeaderTextColor
headerLabel.font = UIFont.systemFontOfSize(12.0, weight: UIFontWeightRegular)
return headerLabel
}()
private lazy var topBorder: CALayer = {
let topBorder = CALayer()
topBorder.backgroundColor = UIConstants.SeparatorColor.CGColor
return topBorder
}()
private lazy var bottomBorder: CALayer = {
let bottomBorder = CALayer()
bottomBorder.backgroundColor = UIConstants.SeparatorColor.CGColor
return bottomBorder
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
addSubview(titleLabel)
clipsToBounds = true
layer.addSublayer(topBorder)
layer.addSublayer(bottomBorder)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
bottomBorder.frame = CGRectMake(0.0, frame.size.height - 0.5, frame.size.width, 0.5)
topBorder.frame = CGRectMake(0.0, 0.0, frame.size.width, 0.5)
titleLabel.sizeToFit()
}
}
| 27236106ada923a70e9d8a07b0c2f61a | 41.765128 | 303 | 0.685006 | false | false | false | false |
leasual/PDChart | refs/heads/master | PDChartDemo/PDChartDemo/PDChartDemo/PDChart/PDChartComponent/PDChartAxesComponent.swift | mit | 2 | //
// PDChartAxesComponent.swift
// PDChart
//
// Created by Pandara on 14-7-11.
// Copyright (c) 2014年 Pandara. All rights reserved.
//
import UIKit
class PDChartAxesComponentDataItem: NSObject {
//required
var targetView: UIView!
var featureH: CGFloat!
var featureW: CGFloat!
var xMax: CGFloat!
var xInterval: CGFloat!
var yMax: CGFloat!
var yInterval: CGFloat!
var xAxesDegreeTexts: [String]?
var yAxesDegreeTexts: [String]?
//optional default
var showAxes: Bool = true
var showXDegree: Bool = true
var showYDegree: Bool = true
var axesColor: UIColor = UIColor(red: 80.0 / 255, green: 80.0 / 255, blue: 80.0 / 255, alpha: 1.0)//坐标轴颜色
var axesTipColor: UIColor = UIColor(red: 80.0 / 255, green: 80.0 / 255, blue: 80.0 / 255, alpha: 1.0)//坐标轴刻度值颜色
var xAxesLeftMargin: CGFloat = 40 //坐标系左边margin
var xAxesRightMargin: CGFloat = 40 //坐标系右边margin
var yAxesBottomMargin: CGFloat = 40 //坐标系下面margin
var yAxesTopMargin: CGFloat = 40 //坐标系上方marign
var axesWidth: CGFloat = 1.0 //坐标轴的粗细
var arrowHeight: CGFloat = 5.0
var arrowWidth: CGFloat = 5.0
var arrowBodyLength: CGFloat = 10.0
var degreeLength: CGFloat = 5.0 //坐标轴刻度直线的长度
var degreeTipFontSize: CGFloat = 10.0
var degreeTipMarginHorizon: CGFloat = 5.0
var degreeTipMarginVertical: CGFloat = 5.0
override init() {
}
}
class PDChartAxesComponent: NSObject {
var dataItem: PDChartAxesComponentDataItem!
init(dataItem: PDChartAxesComponentDataItem) {
self.dataItem = dataItem
}
func getYAxesHeight() -> CGFloat {//heigth between 0~yMax
var basePoint: CGPoint = self.getBasePoint()
var yAxesHeight = basePoint.y - dataItem.arrowHeight - dataItem.yAxesTopMargin - dataItem.arrowBodyLength
return yAxesHeight
}
func getXAxesWidth() -> CGFloat {//width between 0~xMax
var basePoint: CGPoint = self.getBasePoint()
var xAxesWidth = dataItem.featureW - basePoint.x - dataItem.arrowHeight - dataItem.xAxesRightMargin - dataItem.arrowBodyLength
return xAxesWidth
}
func getBasePoint() -> CGPoint {
var neededAxesWidth: CGFloat!
if dataItem.showAxes {
neededAxesWidth = CGFloat(dataItem.axesWidth)
} else {
neededAxesWidth = 0
}
var basePoint: CGPoint = CGPoint(x: dataItem.xAxesLeftMargin + neededAxesWidth / 2.0, y: dataItem.featureH - (dataItem.yAxesBottomMargin + neededAxesWidth / 2.0))
return basePoint
}
func getXDegreeInterval() -> CGFloat {
var xAxesWidth: CGFloat = self.getXAxesWidth()
var xDegreeInterval: CGFloat = dataItem.xInterval / dataItem.xMax * xAxesWidth
return xDegreeInterval
}
func getYDegreeInterval() -> CGFloat {
var yAxesHeight: CGFloat = self.getYAxesHeight()
var yDegreeInterval: CGFloat = dataItem.yInterval / dataItem.yMax * yAxesHeight
return yDegreeInterval
}
func getAxesDegreeTipLabel(tipText: String, center: CGPoint, size: CGSize, fontSize: CGFloat, textAlignment: NSTextAlignment, textColor: UIColor) -> UILabel {
var label: UILabel = UILabel(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: size))
label.text = tipText
label.center = center
label.textAlignment = textAlignment
label.textColor = textColor
label.backgroundColor = UIColor.clearColor()
label.adjustsFontSizeToFitWidth = true
label.font = UIFont.systemFontOfSize(fontSize)
return label
}
func getXAxesDegreeTipLabel(tipText: String, center: CGPoint, size: CGSize, fontSize: CGFloat) -> UILabel {
return self.getAxesDegreeTipLabel(tipText, center: center, size: size, fontSize: fontSize, textAlignment: NSTextAlignment.Center, textColor: dataItem.axesTipColor)
}
func getYAxesDegreeTipLabel(tipText: String, center: CGPoint, size: CGSize, fontSize: CGFloat) -> UILabel {
return self.getAxesDegreeTipLabel(tipText, center: center, size: size, fontSize: fontSize, textAlignment: NSTextAlignment.Right, textColor: dataItem.axesTipColor)
}
func strokeAxes(context: CGContextRef?) {
var xAxesWidth: CGFloat = self.getXAxesWidth()
var yAxesHeight: CGFloat = self.getYAxesHeight()
var basePoint: CGPoint = self.getBasePoint()
if dataItem.showAxes {
CGContextSetStrokeColorWithColor(context, dataItem.axesColor.CGColor)
CGContextSetFillColorWithColor(context, dataItem.axesColor.CGColor)
var axesPath: UIBezierPath = UIBezierPath()
axesPath.lineWidth = dataItem.axesWidth
axesPath.lineCapStyle = kCGLineCapRound
axesPath.lineJoinStyle = kCGLineJoinRound
//x axes--------------------------------------
axesPath.moveToPoint(CGPoint(x: basePoint.x, y: basePoint.y))
axesPath.addLineToPoint(CGPoint(x: basePoint.x + xAxesWidth, y: basePoint.y))
//degrees in x axes
var xDegreeNum: Int = Int((dataItem.xMax - (dataItem.xMax % dataItem.xInterval)) / dataItem.xInterval)
var xDegreeInterval: CGFloat = self.getXDegreeInterval()
if dataItem.showXDegree {
for var i = 0; i < xDegreeNum; i++ {
var degreeX: CGFloat = basePoint.x + xDegreeInterval * CGFloat(i + 1)
axesPath.moveToPoint(CGPoint(x: degreeX, y: basePoint.y))
axesPath.addLineToPoint(CGPoint(x: degreeX, y: basePoint.y - dataItem.degreeLength))
}
}
//x axes arrow
//arrow body
axesPath.moveToPoint(CGPoint(x: basePoint.x + xAxesWidth, y: basePoint.y))
axesPath.addLineToPoint(CGPoint(x: basePoint.x + xAxesWidth + dataItem.arrowBodyLength, y: basePoint.y))
//arrow head
var arrowPath: UIBezierPath = UIBezierPath()
arrowPath.lineWidth = dataItem.axesWidth
arrowPath.lineCapStyle = kCGLineCapRound
arrowPath.lineJoinStyle = kCGLineJoinRound
var xArrowTopPoint: CGPoint = CGPoint(x: basePoint.x + xAxesWidth + dataItem.arrowBodyLength + dataItem.arrowHeight, y: basePoint.y)
arrowPath.moveToPoint(xArrowTopPoint)
arrowPath.addLineToPoint(CGPoint(x: basePoint.x + xAxesWidth + dataItem.arrowBodyLength, y: basePoint.y - dataItem.arrowWidth / 2))
arrowPath.addLineToPoint(CGPoint(x: basePoint.x + xAxesWidth + dataItem.arrowBodyLength, y: basePoint.y + dataItem.arrowWidth / 2))
arrowPath.addLineToPoint(xArrowTopPoint)
//y axes--------------------------------------
axesPath.moveToPoint(CGPoint(x: basePoint.x, y: basePoint.y))
axesPath.addLineToPoint(CGPoint(x: basePoint.x, y: basePoint.y - yAxesHeight))
//degrees in y axes
var yDegreesNum: Int = Int((dataItem.yMax - (dataItem.yMax % dataItem.yInterval)) / dataItem.yInterval)
var yDegreeInterval: CGFloat = self.getYDegreeInterval()
if dataItem.showYDegree {
for var i = 0; i < yDegreesNum; i++ {
var degreeY: CGFloat = basePoint.y - yDegreeInterval * CGFloat(i + 1)
axesPath.moveToPoint(CGPoint(x: basePoint.x, y: degreeY))
axesPath.addLineToPoint(CGPoint(x: basePoint.x + dataItem.degreeLength, y: degreeY))
}
}
//y axes arrow
//arrow body
axesPath.moveToPoint(CGPoint(x: basePoint.x, y: basePoint.y - yAxesHeight))
axesPath.addLineToPoint(CGPoint(x: basePoint.x, y: basePoint.y - yAxesHeight - dataItem.arrowBodyLength))
//arrow head
var yArrowTopPoint: CGPoint = CGPoint(x: basePoint.x, y: basePoint.y - yAxesHeight - dataItem.arrowBodyLength - dataItem.arrowHeight)
arrowPath.moveToPoint(yArrowTopPoint)
arrowPath.addLineToPoint(CGPoint(x: basePoint.x - dataItem.arrowWidth / 2, y: basePoint.y - yAxesHeight - dataItem.arrowBodyLength))
arrowPath.addLineToPoint(CGPoint(x: basePoint.x + dataItem.arrowWidth / 2, y: basePoint.y - yAxesHeight - dataItem.arrowBodyLength))
arrowPath.addLineToPoint(yArrowTopPoint)
axesPath.stroke()
arrowPath.stroke()
//axes tips------------------------------------
//func getXAxesDegreeTipLabel(tipText: String, frame: CGRect, fontSize: CGFloat) -> UILabel {
if (dataItem.xAxesDegreeTexts != nil) {
for var i = 0; i < dataItem.xAxesDegreeTexts!.count; i++ {
var size: CGSize = CGSize(width: xDegreeInterval - dataItem.degreeTipMarginHorizon * 2, height: dataItem.degreeTipFontSize)
var center: CGPoint = CGPoint(x: basePoint.x + xDegreeInterval * CGFloat(i + 1), y: basePoint.y + dataItem.degreeTipMarginVertical + size.height / 2)
var label: UILabel = self.getXAxesDegreeTipLabel(dataItem.xAxesDegreeTexts![i], center: center, size: size, fontSize: dataItem.degreeTipFontSize)
dataItem.targetView.addSubview(label)
}
} else {
for var i = 0; i < xDegreeNum; i++ {
var size: CGSize = CGSize(width: xDegreeInterval - dataItem.degreeTipMarginHorizon * 2, height: dataItem.degreeTipFontSize)
var center: CGPoint = CGPoint(x: basePoint.x + xDegreeInterval * CGFloat(i + 1), y: basePoint.y + dataItem.degreeTipMarginVertical + size.height / 2)
var label: UILabel = self.getXAxesDegreeTipLabel("\(CGFloat(i + 1) * dataItem.xInterval)", center: center, size: size, fontSize: dataItem.degreeTipFontSize)
dataItem.targetView.addSubview(label)
}
}
if (dataItem.yAxesDegreeTexts != nil) {
for var i = 0; i < dataItem.yAxesDegreeTexts!.count; i++ {
var size: CGSize = CGSize(width: dataItem.xAxesLeftMargin - dataItem.degreeTipMarginHorizon * 2, height: dataItem.degreeTipFontSize)
var center: CGPoint = CGPoint(x: dataItem.xAxesLeftMargin / 2, y: basePoint.y - yDegreeInterval * CGFloat(i + 1))
var label: UILabel = self.getYAxesDegreeTipLabel(dataItem.yAxesDegreeTexts![i], center: center, size: size, fontSize: dataItem.degreeTipFontSize)
dataItem.targetView.addSubview(label)
}
} else {
for var i = 0; i < yDegreesNum; i++ {
var size: CGSize = CGSize(width: dataItem.xAxesLeftMargin - dataItem.degreeTipMarginHorizon * 2, height: dataItem.degreeTipFontSize)
var center: CGPoint = CGPoint(x: dataItem.xAxesLeftMargin / 2, y: basePoint.y - yDegreeInterval * CGFloat(i + 1))
var label: UILabel = self.getYAxesDegreeTipLabel("\(CGFloat(i + 1) * dataItem.yInterval)", center: center, size: size, fontSize: dataItem.degreeTipFontSize)
dataItem.targetView.addSubview(label)
}
}
}
}
}
| ed8d833df7488c6054f02985a29d5d94 | 44.535433 | 176 | 0.620353 | false | false | false | false |
ReduxKit/ReduxKit | refs/heads/master | ReduxKitTests/CreateStoreSpec.swift | mit | 1 | //
// CreateStoreSpec.swift
// ReduxKit
//
// Created by Aleksander Herforth Rendtslev on 06/11/15.
// Copyright © 2015 Kare Media. All rights reserved.
//
import Quick
import Nimble
@testable import ReduxKit
class CreateStoreSpec: QuickSpec {
// swiftlint:disable function_body_length
override func spec() {
describe("Create Store") {
var defaultState: AppState!
var store: Store<AppState>!
beforeEach {
store = createStore(applicationReducer, state: nil)
defaultState = store.state
}
it("should be subscribable and succesfully propagate one action dispatch") {
// Arrange
var state: AppState!
// Act
store.subscribe { state = $0 }
store.dispatch(IncrementAction())
// Assert
expect(state.counter).toNot(equal(defaultState.counter))
expect(state.counter).to(equal(defaultState.counter + 1))
}
it("should not propagate state on subscription") {
// Arrange
var state: AppState!
// Act: Run dispatch multiple times
store.subscribe { state = $0 }
let emptyState = state
store.dispatch(IncrementAction())
// Assert
expect(emptyState).to(beNil())
expect(state.counter).to(equal(1))
}
it("should effectively run multiple dispatches") {
// Arrange
var state: AppState!
let iterations = 3
store.subscribe { state = $0 }
// Act: Run dispatch multiple times
for var i = 0; i < iterations; i++ {
store.dispatch(IncrementAction())
}
// Assert
expect(state.counter).toNot(equal(defaultState.counter))
expect(state.counter).to(equal(defaultState.counter + iterations))
}
it("should forbid dispatching actions from within reducers") {
/*
Reducers should be free of side effects, therefore dispatching actions from
within reducers is illegal.
*/
// Arrange
var storeWithDispatchingReducer: Store<AppState>!
func dispatchingReducer(state: AppState? = nil, action: Action) -> AppState {
// Set up the initial state when reducing `DefaultAction`
if action is DefaultAction {
return AppState()
} else if action is IncrementAction {
// Attempt to dispatch a new action when reducing `IncrementAction`
// Act: Dispatch from within Reducer & Assert
expect(
storeWithDispatchingReducer.dispatch(
PushAction(payload: PushAction.Payload(text: "Test")))
)
.to(raiseException(named:"ReduxKit:IllegalDispatchFromReducer"))
}
return AppState()
}
storeWithDispatchingReducer = createStore(dispatchingReducer, state: nil)
// Act: Dispatch Initial Action
storeWithDispatchingReducer.dispatch(IncrementAction())
}
it("should fetch the latest state") {
// Arrange
var state: AppState!
// Act: Run dispatch multiple times
store.dispatch(IncrementAction())
state = store.state
// Assert
expect(state.counter).toNot(equal(defaultState.counter))
}
it("should work with multiple reducers") {
// Arrange
var state: AppState!
let textMessage = "test"
let iterations = 3
store.subscribe { state = $0 }
// Act
for var i = 0; i < iterations; i++ {
store.dispatch(IncrementAction())
store.dispatch(PushAction(payload: PushAction.Payload(text: textMessage)))
store.dispatch(UpdateTextFieldAction(
payload: UpdateTextFieldAction.Payload(text: textMessage)))
}
// Assert
expect(state.counter).to(equal(defaultState.counter + iterations))
expect(state.countries).to(contain(textMessage))
expect(state.countries.count).to(equal(iterations))
expect(state.textField.value).to(equal(textMessage))
}
it("should unsubscribe when dispose is called") {
// Arrange
var state: AppState!
let disposable = store.subscribe { state = $0 }
// Act
store.dispatch(IncrementAction())
disposable.dispose()
store.dispatch(IncrementAction())
// Assert
expect(state.counter).to(equal(1))
expect(store.state.counter).to(equal(2))
}
it("should maintain disposed status") {
// Arrange
let disposable = store.subscribe {_ in}
// Act
let disposedBefore = disposable.disposed
disposable.dispose()
let disposedAfter = disposable.disposed
// Assert
expect(disposedBefore).to(beFalse())
expect(disposedAfter).to(beTrue())
}
}
}
}
| 740ce2c34049b5fb280ba4e7b7c9c2fc | 33.720238 | 94 | 0.5042 | false | false | false | false |
apple/swift-nio | refs/heads/main | Tests/NIOPosixTests/EchoServerClientTest+XCTest.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//
// EchoServerClientTest+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension EchoServerClientTest {
@available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings")
static var allTests : [(String, (EchoServerClientTest) -> () throws -> Void)] {
return [
("testEcho", testEcho),
("testLotsOfUnflushedWrites", testLotsOfUnflushedWrites),
("testEchoUnixDomainSocket", testEchoUnixDomainSocket),
("testConnectUnixDomainSocket", testConnectUnixDomainSocket),
("testCleanupUnixDomainSocket", testCleanupUnixDomainSocket),
("testBootstrapUnixDomainSocketNameClash", testBootstrapUnixDomainSocketNameClash),
("testChannelActiveOnConnect", testChannelActiveOnConnect),
("testWriteThenRead", testWriteThenRead),
("testCloseInInactive", testCloseInInactive),
("testFlushOnEmpty", testFlushOnEmpty),
("testWriteOnConnect", testWriteOnConnect),
("testWriteOnAccept", testWriteOnAccept),
("testWriteAfterChannelIsDead", testWriteAfterChannelIsDead),
("testPendingReadProcessedAfterWriteError", testPendingReadProcessedAfterWriteError),
("testChannelErrorEOFNotFiredThroughPipeline", testChannelErrorEOFNotFiredThroughPipeline),
("testPortNumbers", testPortNumbers),
("testConnectingToIPv4And6ButServerOnlyWaitsOnIPv4", testConnectingToIPv4And6ButServerOnlyWaitsOnIPv4),
]
}
}
| bfecaeaa7d65541898b8b825a66940af | 45.14 | 162 | 0.64586 | false | true | false | false |
Jnosh/swift | refs/heads/master | test/Constraints/bridging.swift | apache-2.0 | 11 | // RUN: %target-swift-frontend -typecheck -verify %s
// REQUIRES: objc_interop
import Foundation
public class BridgedClass : NSObject, NSCopying {
@objc(copyWithZone:)
public func copy(with zone: NSZone?) -> Any {
return self
}
}
public class BridgedClassSub : BridgedClass { }
// Attempt to bridge to a non-whitelisted type from another module.
extension LazyFilterIterator : _ObjectiveCBridgeable { // expected-error{{conformance of 'LazyFilterIterator' to '_ObjectiveCBridgeable' can only be written in module 'Swift'}}
public typealias _ObjectiveCType = BridgedClassSub
public func _bridgeToObjectiveC() -> _ObjectiveCType {
return BridgedClassSub()
}
public static func _forceBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout LazyFilterIterator?
) { }
public static func _conditionallyBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout LazyFilterIterator?
) -> Bool {
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-> LazyFilterIterator {
let result: LazyFilterIterator?
return result!
}
}
struct BridgedStruct : Hashable, _ObjectiveCBridgeable {
var hashValue: Int { return 0 }
func _bridgeToObjectiveC() -> BridgedClass {
return BridgedClass()
}
static func _forceBridgeFromObjectiveC(
_ x: BridgedClass,
result: inout BridgedStruct?) {
}
static func _conditionallyBridgeFromObjectiveC(
_ x: BridgedClass,
result: inout BridgedStruct?
) -> Bool {
return true
}
static func _unconditionallyBridgeFromObjectiveC(_ source: BridgedClass?)
-> BridgedStruct {
var result: BridgedStruct?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
func ==(x: BridgedStruct, y: BridgedStruct) -> Bool { return true }
struct NotBridgedStruct : Hashable {
var hashValue: Int { return 0 }
}
func ==(x: NotBridgedStruct, y: NotBridgedStruct) -> Bool { return true }
class OtherClass : Hashable {
var hashValue: Int { return 0 }
}
func ==(x: OtherClass, y: OtherClass) -> Bool { return true }
// Basic bridging
func bridgeToObjC(_ s: BridgedStruct) -> BridgedClass {
return s // expected-error{{cannot convert return expression of type 'BridgedStruct' to return type 'BridgedClass'}}
return s as BridgedClass
}
func bridgeToAnyObject(_ s: BridgedStruct) -> AnyObject {
return s // expected-error{{return expression of type 'BridgedStruct' does not conform to 'AnyObject'}}
return s as AnyObject
}
func bridgeFromObjC(_ c: BridgedClass) -> BridgedStruct {
return c // expected-error{{'BridgedClass' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}}
return c as BridgedStruct
}
func bridgeFromObjCDerived(_ s: BridgedClassSub) -> BridgedStruct {
return s // expected-error{{'BridgedClassSub' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}}
return s as BridgedStruct
}
// Array -> NSArray
func arrayToNSArray() {
var nsa: NSArray
nsa = [AnyObject]() // expected-error {{cannot assign value of type '[AnyObject]' to type 'NSArray'}}
nsa = [BridgedClass]() // expected-error {{cannot assign value of type '[BridgedClass]' to type 'NSArray'}}
nsa = [OtherClass]() // expected-error {{cannot assign value of type '[OtherClass]' to type 'NSArray'}}
nsa = [BridgedStruct]() // expected-error {{cannot assign value of type '[BridgedStruct]' to type 'NSArray'}}
nsa = [NotBridgedStruct]() // expected-error{{cannot assign value of type '[NotBridgedStruct]' to type 'NSArray'}}
nsa = [AnyObject]() as NSArray
nsa = [BridgedClass]() as NSArray
nsa = [OtherClass]() as NSArray
nsa = [BridgedStruct]() as NSArray
nsa = [NotBridgedStruct]() as NSArray
_ = nsa
}
// NSArray -> Array
func nsArrayToArray(_ nsa: NSArray) {
var arr1: [AnyObject] = nsa // expected-error{{'NSArray' is not implicitly convertible to '[AnyObject]'; did you mean to use 'as' to explicitly convert?}} {{30-30= as [AnyObject]}}
var _: [BridgedClass] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedClass]'}} {{30-30= as! [BridgedClass]}}
var _: [OtherClass] = nsa // expected-error{{'NSArray' is not convertible to '[OtherClass]'}} {{28-28= as! [OtherClass]}}
var _: [BridgedStruct] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'}} {{31-31= as! [BridgedStruct]}}
var _: [NotBridgedStruct] = nsa // expected-error{{use 'as!' to force downcast}}
var _: [AnyObject] = nsa as [AnyObject]
var _: [BridgedClass] = nsa as [BridgedClass] // expected-error{{'NSArray' is not convertible to '[BridgedClass]'; did you mean to use 'as!' to force downcast?}} {{31-33=as!}}
var _: [OtherClass] = nsa as [OtherClass] // expected-error{{'NSArray' is not convertible to '[OtherClass]'; did you mean to use 'as!' to force downcast?}} {{29-31=as!}}
var _: [BridgedStruct] = nsa as [BridgedStruct] // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'; did you mean to use 'as!' to force downcast?}} {{32-34=as!}}
var _: [NotBridgedStruct] = nsa as [NotBridgedStruct] // expected-error{{use 'as!' to force downcast}}
var arr6: Array = nsa as Array
arr6 = arr1
arr1 = arr6
}
func dictionaryToNSDictionary() {
// FIXME: These diagnostics are awful.
var nsd: NSDictionary
nsd = [NSObject : AnyObject]() // expected-error {{cannot assign value of type '[NSObject : AnyObject]' to type 'NSDictionary'}}
nsd = [NSObject : AnyObject]() as NSDictionary
nsd = [NSObject : BridgedClass]() // expected-error {{cannot assign value of type '[NSObject : BridgedClass]' to type 'NSDictionary'}}
nsd = [NSObject : BridgedClass]() as NSDictionary
nsd = [NSObject : OtherClass]() // expected-error {{cannot assign value of type '[NSObject : OtherClass]' to type 'NSDictionary'}}
nsd = [NSObject : OtherClass]() as NSDictionary
nsd = [NSObject : BridgedStruct]() // expected-error {{cannot assign value of type '[NSObject : BridgedStruct]' to type 'NSDictionary'}}
nsd = [NSObject : BridgedStruct]() as NSDictionary
nsd = [NSObject : NotBridgedStruct]() // expected-error{{cannot assign value of type '[NSObject : NotBridgedStruct]' to type 'NSDictionary'}}
nsd = [NSObject : NotBridgedStruct]() as NSDictionary
nsd = [NSObject : BridgedClass?]() // expected-error{{cannot assign value of type '[NSObject : BridgedClass?]' to type 'NSDictionary'}}
nsd = [NSObject : BridgedClass?]() as NSDictionary
nsd = [NSObject : BridgedStruct?]() // expected-error{{cannot assign value of type '[NSObject : BridgedStruct?]' to type 'NSDictionary'}}
nsd = [NSObject : BridgedStruct?]() as NSDictionary
nsd = [BridgedClass : AnyObject]() // expected-error {{cannot assign value of type '[BridgedClass : AnyObject]' to type 'NSDictionary'}}
nsd = [BridgedClass : AnyObject]() as NSDictionary
nsd = [OtherClass : AnyObject]() // expected-error {{cannot assign value of type '[OtherClass : AnyObject]' to type 'NSDictionary'}}
nsd = [OtherClass : AnyObject]() as NSDictionary
nsd = [BridgedStruct : AnyObject]() // expected-error {{cannot assign value of type '[BridgedStruct : AnyObject]' to type 'NSDictionary'}}
nsd = [BridgedStruct : AnyObject]() as NSDictionary
nsd = [NotBridgedStruct : AnyObject]() // expected-error{{cannot assign value of type '[NotBridgedStruct : AnyObject]' to type 'NSDictionary'}}
nsd = [NotBridgedStruct : AnyObject]() as NSDictionary
// <rdar://problem/17134986>
var bcOpt: BridgedClass?
nsd = [BridgedStruct() : bcOpt as Any]
bcOpt = nil
_ = nsd
}
// In this case, we should not implicitly convert Dictionary to NSDictionary.
struct NotEquatable {}
func notEquatableError(_ d: Dictionary<Int, NotEquatable>) -> Bool {
// FIXME: Another awful diagnostic.
return d == d // expected-error{{binary operator '==' cannot be applied to two 'Dictionary<Int, NotEquatable>' operands}}
// expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: }}
}
// NSString -> String
var nss1 = "Some great text" as NSString
var nss2: NSString = ((nss1 as String) + ", Some more text") as NSString
// <rdar://problem/17943223>
var inferDouble = 1.0/10
let d: Double = 3.14159
inferDouble = d
// rdar://problem/17962491
_ = 1 % 3 / 3.0 // expected-error{{'%' is unavailable: Use truncatingRemainder instead}}
var inferDouble2 = 1 / 3 / 3.0
let d2: Double = 3.14159
inferDouble2 = d2
// rdar://problem/18269449
var i1: Int = 1.5 * 3.5 // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}}
// rdar://problem/18330319
func rdar18330319(_ s: String, d: [String : AnyObject]) {
_ = d[s] as! String?
}
// rdar://problem/19551164
func rdar19551164a(_ s: String, _ a: [String]) {}
func rdar19551164b(_ s: NSString, _ a: NSArray) {
rdar19551164a(s, a) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{18-18= as String}}
// expected-error@-1{{'NSArray' is not convertible to '[String]'; did you mean to use 'as!' to force downcast?}}{{21-21= as! [String]}}
}
// rdar://problem/19695671
func takesSet<T>(_ p: Set<T>) {} // expected-note {{in call to function 'takesSet'}}
func takesDictionary<K, V>(_ p: Dictionary<K, V>) {} // expected-note {{in call to function 'takesDictionary'}}
func takesArray<T>(_ t: Array<T>) {} // expected-note {{in call to function 'takesArray'}}
func rdar19695671() {
takesSet(NSSet() as! Set) // expected-error{{generic parameter 'T' could not be inferred}}
takesDictionary(NSDictionary() as! Dictionary) // expected-error{{generic parameter 'K' could not be inferred}}
takesArray(NSArray() as! Array) // expected-error{{generic parameter 'T' could not be inferred}}
}
// This failed at one point while fixing rdar://problem/19600325.
func getArrayOfAnyObject(_: AnyObject) -> [AnyObject] { return [] }
func testCallback(_ f: (AnyObject) -> AnyObject?) {}
testCallback { return getArrayOfAnyObject($0) } // expected-error {{cannot convert value of type '[AnyObject]' to closure result type 'AnyObject?'}}
// <rdar://problem/19724719> Type checker thinks "(optionalNSString ?? nonoptionalNSString) as String" is a forced cast
func rdar19724719(_ f: (String) -> (), s1: NSString?, s2: NSString) {
f((s1 ?? s2) as String)
}
// <rdar://problem/19770981>
func rdar19770981(_ s: String, ns: NSString) {
func f(_ s: String) {}
f(ns) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7= as String}}
f(ns as String)
// 'as' has higher precedence than '>' so no parens are necessary with the fixit:
s > ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{9-9= as String}}
_ = s > ns as String
ns > s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{5-5= as String}}
_ = ns as String > s
// 'as' has lower precedence than '+' so add parens with the fixit:
s + ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7=(}}{{9-9= as String)}}
_ = s + (ns as String)
ns + s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{3-3=(}}{{5-5= as String)}}
_ = (ns as String) + s
}
// <rdar://problem/19831919> Fixit offers as! conversions that are known to always fail
func rdar19831919() {
var s1 = 1 + "str"; // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note{{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}}
}
// <rdar://problem/19831698> Incorrect 'as' fixits offered for invalid literal expressions
func rdar19831698() {
var v70 = true + 1 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Int'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}}
var v71 = true + 1.0 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Double'}}
// expected-note@-1{{overloads for '+'}}
var v72 = true + true // expected-error{{binary operator '+' cannot be applied to two 'Bool' operands}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}}
var v73 = true + [] // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and '[Any]'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}}
var v75 = true + "str" // expected-error {{binary operator '+' cannot be applied to operands of type 'Bool' and 'String'}} expected-note {{expected an argument list of type '(String, String)'}}
}
// <rdar://problem/19836341> Incorrect fixit for NSString? to String? conversions
func rdar19836341(_ ns: NSString?, vns: NSString?) {
var vns = vns
let _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}
var _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}
// FIXME: there should be a fixit appending "as String?" to the line; for now
// it's sufficient that it doesn't suggest appending "as String"
// Important part about below diagnostic is that from-type is described as
// 'NSString?' and not '@lvalue NSString?':
let _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}
var _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}
vns = ns
}
// <rdar://problem/20029786> Swift compiler sometimes suggests changing "as!" to "as?!"
func rdar20029786(_ ns: NSString?) {
var s: String = ns ?? "str" as String as String // expected-error{{cannot convert value of type 'NSString?' to expected argument type 'String?'}}
var s2 = ns ?? "str" as String as String // expected-error {{cannot convert value of type 'String' to expected argument type 'NSString'}}
let s3: NSString? = "str" as String? // expected-error {{cannot convert value of type 'String?' to specified type 'NSString?'}}
var s4: String = ns ?? "str" // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{20-20=(}}{{31-31=) as String}}
var s5: String = (ns ?? "str") as String // fixed version
}
// <rdar://problem/19813772> QoI: Using as! instead of as in this case produces really bad diagnostic
func rdar19813772(_ nsma: NSMutableArray) {
var a1 = nsma as! Array // expected-error{{generic parameter 'Element' could not be inferred in cast to 'Array<_>'}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{26-26=<Any>}}
var a2 = nsma as! Array<AnyObject> // expected-warning{{forced cast from 'NSMutableArray' to 'Array<AnyObject>' always succeeds; did you mean to use 'as'?}} {{17-20=as}}
var a3 = nsma as Array<AnyObject>
}
func rdar28856049(_ nsma: NSMutableArray) {
_ = nsma as? [BridgedClass]
_ = nsma as? [BridgedStruct]
_ = nsma as? [BridgedClassSub]
}
// <rdar://problem/20336036> QoI: Add cast-removing fixit for "Forced cast from 'T' to 'T' always succeeds"
func force_cast_fixit(_ a : [NSString]) -> [NSString] {
return a as! [NSString] // expected-warning {{forced cast of '[NSString]' to same type has no effect}} {{12-27=}}
}
// <rdar://problem/21244068> QoI: IUO prevents specific diagnostic + fixit about non-implicitly converted bridge types
func rdar21244068(_ n: NSString!) -> String {
return n // expected-error {{'NSString!' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{11-11= as String}}
}
func forceBridgeDiag(_ obj: BridgedClass!) -> BridgedStruct {
return obj // expected-error{{'BridgedClass!' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}}{{13-13= as BridgedStruct}}
}
struct KnownUnbridged {}
class KnownClass {}
protocol KnownClassProtocol: class {}
func forceUniversalBridgeToAnyObject<T, U: KnownClassProtocol>(a: T, b: U, c: Any, d: KnownUnbridged, e: KnownClass, f: KnownClassProtocol, g: AnyObject, h: String) {
var z: AnyObject
z = a as AnyObject
z = b as AnyObject
z = c as AnyObject
z = d as AnyObject
z = e as AnyObject
z = f as AnyObject
z = g as AnyObject
z = h as AnyObject
z = a // expected-error{{does not conform to 'AnyObject'}}
z = b
z = c // expected-error{{does not conform to 'AnyObject'}}
z = d // expected-error{{does not conform to 'AnyObject'}}
z = e
z = f
z = g
z = h // expected-error{{does not conform to 'AnyObject'}}
_ = z
}
func bridgeAnyContainerToAnyObject(x: [Any], y: [NSObject: Any]) {
var z: AnyObject
z = x as AnyObject
z = y as AnyObject
_ = z
}
func bridgeTupleToAnyObject() {
let x = (1, "two")
let y = x as AnyObject
_ = y
}
| 7b8d57d60659f59c0a7139ddf578675e | 46.163488 | 305 | 0.693685 | false | false | false | false |
arkuhn/SkiFree-iOS | refs/heads/master | SkiFreeiOS/SkiFreeiOS/GameScene.swift | mit | 1 | //
// GameScene.swift
// SkiFreeiOS
//
// Created by ark9719 on 1/31/17.
// Copyright © 2017 ark9719. All rights reserved.
//
import SpriteKit
import UIKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
//World
var background1 = SKSpriteNode()
var background2 = SKSpriteNode()
var touchZone = SKSpriteNode()
var skier = Skier()
var distanceNode = SKLabelNode()
var points = UserDefaults.standard.object(forKey: "HighestScore") as! Int
//Obstacles
var currentObstacles = Array<Obstacle>()
var obstacleMax = 10 //Total allowed obstacles on map
var distanceBetweenObstacles = 65 //How long between spawning obstacles
var lastDistance = 0 //Last distance "seen" by
var distance = 0 //Total distance traveled
var scrollSpeed = 4.0 //How fast terrain/objects pass
override func didMove(to view: SKView) {
super.didMove(to: view)
self.physicsWorld.contactDelegate = self
anchorPoint = CGPoint(x: 0, y: 0)
initBackgrounds()
initTouchZone()
initWorldPhysics()
initDistanceLabel()
//Skier
skier.position = CGPoint(x: frame.width / 2, y: frame.height / 2)
addChild(skier)
}
//SCENE
override func update(_ currentTime: TimeInterval) {
self.moveBackground()
self.distance += 1
self.distanceNode.text = ("Distance: \(distance)")
self.updateObstacles()
self.updateScrollDifficulty()
self.updateHighScore()
}
func didBegin(_ contact: SKPhysicsContact) {
skier.texture = SKTexture(imageNamed: "skifreehit")
let overScene = GameOverScene(size: self.size)
self.view?.presentScene(overScene, transition: SKTransition.fade(withDuration: 2))
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches{
let pos = touch.location(in: self)
let node = self.atPoint(pos)
if node == touchZone {
if(pos.x < frame.width / 3 ){
skier.move(direction: "left")
}
else if(pos.x > frame.width / 3 && pos.x < 2 * frame.width / 3){
skier.move(direction: "down")
}
else if(pos.x > 2 * frame.width / 3){
skier.move(direction: "right")
}
}
}
}
//UTILITY
func updateHighScore(){
if distance > points{
distanceNode.fontColor = UIColor.red
UserDefaults.standard.set(distance, forKey: "HighestScore")
UserDefaults.standard.synchronize()
}
}
func updateObstacles(){
//For every 1000 distance
// - increase total possible obstacles by 2
// - decrease distance neccessary to spawn more obstacles
if (distance % 1000 == 0){
obstacleMax += 2
distanceBetweenObstacles -= 5
}
spawnObstacles()
moveObstacles()
}
func spawnObstacles(){
if distance - lastDistance >= distanceBetweenObstacles{
while currentObstacles.count < obstacleMax{
let newObstacle = Obstacle(frame: self.frame)
currentObstacles.append(newObstacle)
addChild(newObstacle)
lastDistance = distance
}
}
}
func moveObstacles(){
for obstacle in currentObstacles{
obstacle.update(scrollSpeed: scrollSpeed)
let indexObstacle = currentObstacles.index(of: obstacle)
if obstacle.position.y > frame.height {
currentObstacles.remove(at: indexObstacle!)
obstacle.removeFromParent()
}
}
}
func moveBackground(){
if (background1.position.y >= 3 * frame.height / 2){
background1.position = CGPoint(x: frame.width / 2, y: background2.position.y - frame.height)
return
}
background1.position = CGPoint(x: Double(background1.position.x), y: Double(background1.position.y) + scrollSpeed)
if (background2.position.y >= 3 * frame.height / 2){
background2.position = CGPoint(x: frame.width / 2, y: background1.position.y - frame.height)
return
}
background2.position = CGPoint(x: Double(background1.position.x), y: Double(background2.position.y) + scrollSpeed)
}
func updateScrollDifficulty(){
if (distance % 1000 == 0){
let advancement = Double(distance / 1000)
scrollSpeed += (advancement / 1.5)
}
}
//INITIALIZERS
func initBackgrounds(){
//Background
background1 = SKSpriteNode(imageNamed: "background1")
background2 = SKSpriteNode(imageNamed: "background2")
background1.size = frame.size
background2.size = frame.size
background1.position = CGPoint(x: frame.width / 2, y: frame.height / 2 )
background2.position = CGPoint(x: frame.width / 2, y: -frame.height / 2 )
addChild(background1)
addChild(background2)
}
func initTouchZone(){
//TouchZone
touchZone = SKSpriteNode(color: UIColor.clear, size: CGSize(width: frame.width, height: frame.height / 2))
touchZone.position = CGPoint(x: frame.width / 2 , y: frame.height / 2 - touchZone.size.height/2)
addChild(touchZone)
}
func initWorldPhysics(){
//Gravity
physicsWorld.gravity = CGVector(dx: 0, dy: 0)
let gravityVec = vector_float3(0, 1, 0)
let gravityNode = SKFieldNode.linearGravityField(withVector: gravityVec)
gravityNode.strength = 1.5
addChild(gravityNode)
//Confine Skier (Border physics)
let borderBounds = SKPhysicsBody(edgeLoopFrom: self.frame)
borderBounds.friction = 0
self.physicsBody = borderBounds
}
func initDistanceLabel(){
//Distance traveled label
distanceNode.fontColor = UIColor.gray
distanceNode.position = CGPoint(x: frame.width / 5, y: 14 * frame.height / 15 )
distanceNode.fontSize = 20
addChild(distanceNode)
}
}
| 80a9733ad4f71b57c2cc5d6b04830f16 | 29.232877 | 122 | 0.567739 | false | false | false | false |
JaSpa/swift | refs/heads/master | test/ClangImporter/objc_factory_method.swift | apache-2.0 | 5 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %build-clang-importer-objc-overlays
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -target x86_64-apple-macosx10.51 -typecheck %s -verify
// REQUIRES: OS=macosx
// REQUIRES: objc_interop
import AppKit
import NotificationCenter
func testInstanceTypeFactoryMethod(_ queen: Bee) {
_ = Hive(queen: queen)
_ = NSObjectFactory() // okay, prefers init method
_ = NSObjectFactory(integer: 1)
_ = NSObjectFactory(double: 314159)
_ = NSObjectFactory(float: 314159)
}
func testInstanceTypeFactoryMethodInherited() {
_ = NSObjectFactorySub() // okay, prefers init method
_ = NSObjectFactorySub(integer: 1)
_ = NSObjectFactorySub(double: 314159)
_ = NSObjectFactorySub(float: 314159) // expected-error{{argument labels '(float:)' do not match any available overloads}}
// expected-note @-1 {{overloads for 'NSObjectFactorySub' exist with these partially matching parameter lists: (integer: Int), (double: Double)}}
let a = NSObjectFactorySub(buildingWidgets: ()) // expected-error{{argument labels '(buildingWidgets:)' do not match any available overloads}}
// expected-note @-1 {{overloads for 'NSObjectFactorySub' exist with these partially matching parameter lists: (integer: Int), (double: Double)}}
_ = a
}
func testFactoryWithLaterIntroducedInit() {
// Prefer importing more available factory initializer over less
// less available convenience initializer
_ = NSHavingConvenienceFactoryAndLaterConvenienceInit(flim:5)
_ = NSHavingConvenienceFactoryAndLaterConvenienceInit(flam:5)
// Prefer importing more available convenience initializer over less
// less available factory initializer
_ = NSHavingConvenienceFactoryAndEarlierConvenienceInit(flim:5)
_ = NSHavingConvenienceFactoryAndEarlierConvenienceInit(flam:5)
// Don't prefer more available convenience factory initializer over less
// available designated initializer
_ = NSHavingConvenienceFactoryAndLaterDesignatedInit(flim:5) // expected-error {{'init(flim:)' is only available on OS X 10.52 or newer}}
// expected-note @-1 {{add 'if #available' version check}}
// expected-note @-2 {{add @available attribute to enclosing global function}}
_ = NSHavingConvenienceFactoryAndLaterDesignatedInit(flam:5) // expected-error {{'init(flam:)' is only available on OS X 10.52 or newer}}
// expected-note @-1 {{add 'if #available' version check}} {{3-63=if #available(OSX 10.52, *) {\n _ = NSHavingConvenienceFactoryAndLaterDesignatedInit(flam:5)\n \} else {\n // Fallback on earlier versions\n \}}}
// expected-note @-2 {{add @available attribute to enclosing global function}} {{1-1=@available(OSX 10.52, *)\n}}
// Don't prefer more available factory initializer over less
// available designated initializer
_ = NSHavingFactoryAndLaterConvenienceInit(flim:5) // expected-error {{'init(flim:)' is only available on OS X 10.52 or newer}}
// expected-note @-1 {{add 'if #available' version check}}
// expected-note @-2 {{add @available attribute to enclosing global function}}
_ = NSHavingFactoryAndLaterConvenienceInit(flam:5) // expected-error {{'init(flam:)' is only available on OS X 10.52 or newer}}
// expected-note @-1 {{add 'if #available' version check}}
// expected-note @-2 {{add @available attribute to enclosing global function}}
// When both a convenience factory and a convenience initializer have the
// same availability, choose the convenience initializer.
_ = NSHavingConvenienceFactoryAndSameConvenienceInit(flim:5) // expected-warning {{'init(flim:)' was deprecated in OS X 10.51: ConvenienceInit}}
_ = NSHavingConvenienceFactoryAndSameConvenienceInit(flam:5) // expected-warning {{'init(flam:)' was deprecated in OS X 10.51: ConvenienceInit}}
_ = NSHavingConvenienceFactoryAndSameConvenienceInit(flotsam:5) // expected-warning {{'init(flotsam:)' is deprecated: ConvenienceInit}}
_ = NSHavingConvenienceFactoryAndSameConvenienceInit(jetsam:5) // expected-warning {{'init(jetsam:)' is deprecated: ConvenienceInit}}
_ = NSHavingUnavailableFactoryAndUnavailableConvenienceInit(flim:5) // expected-error {{'init(flim:)' is unavailable: ConvenienceInit}}
_ = NSHavingUnavailableFactoryAndUnavailableConvenienceInit(flam:5) // expected-error {{'init(flam:)' is unavailable: ConvenienceInit}}
}
func testNSErrorFactoryMethod(_ path: String) throws {
_ = try NSString(contentsOfFile: path)
}
func testNonInstanceTypeFactoryMethod(_ s: String) {
_ = NSObjectFactory(string: s) // expected-error{{argument labels '(string:)' do not match any available overloads}}
// expected-note @-1 {{(integer: Int), (double: Double), (float: Float)}}
}
func testUseOfFactoryMethod(_ queen: Bee) {
_ = Hive.hiveWithQueen(queen) // expected-error{{'hiveWithQueen' is unavailable: use object construction 'Hive(queen:)'}}
}
func testNonsplittableFactoryMethod() {
_ = NSObjectFactory.factoryBuildingWidgets()
}
func testFactoryMethodBlacklist() {
_ = NCWidgetController.widgetController()
}
func test17261609() {
_ = NSDecimalNumber(mantissa:1, exponent:1, isNegative:true)
_ = NSDecimalNumber.decimalNumberWithMantissa(1, exponent:1, isNegative:true) // expected-error{{'decimalNumberWithMantissa(_:exponent:isNegative:)' is unavailable: use object construction 'NSDecimalNumber(mantissa:exponent:isNegative:)'}}
}
func testURL() {
let url = NSURL(string: "http://www.llvm.org")!
_ = NSURL.URLWithString("http://www.llvm.org") // expected-error{{'URLWithString' is unavailable: use object construction 'NSURL(string:)'}}
NSURLRequest(string: "http://www.llvm.org") // expected-warning{{unused}}
NSURLRequest(url: url as URL) // expected-warning{{unused}}
_ = NSURLRequest.requestWithString("http://www.llvm.org") // expected-error{{'requestWithString' is unavailable: use object construction 'NSURLRequest(string:)'}}
_ = NSURLRequest.URLRequestWithURL(url as URL) // expected-error{{'URLRequestWithURL' is unavailable: use object construction 'NSURLRequest(url:)'}}
}
| 35735501f50d6b8add367683f6d4b616 | 53.026786 | 241 | 0.740539 | false | true | false | false |
everald/JetPack | refs/heads/master | Sources/Measures/Pressure.swift | mit | 2 | // TODO use SI unit for rawValue
// TODO make sure conversation millibar<>inHg is correct
private let inchesOfMercuryPerMillibar = 0.02953
private let millibarsPerInchOfMercury = 1 / inchesOfMercuryPerMillibar
public struct Pressure: Measure {
public static let name = MeasuresStrings.Measure.pressure
public static let rawUnit = PressureUnit.millibars
public var rawValue: Double
public init(_ value: Double, unit: PressureUnit) {
precondition(!value.isNaN, "Value must not be NaN.")
switch unit {
case .inchesOfMercury: rawValue = value * millibarsPerInchOfMercury
case .millibars: rawValue = value
}
}
public init(inchesOfMercury: Double) {
self.init(inchesOfMercury, unit: .inchesOfMercury)
}
public init(millibars: Double) {
self.init(millibars, unit: .millibars)
}
public init(rawValue: Double) {
self.rawValue = rawValue
}
public var inchesOfMercury: Double {
return millibars * inchesOfMercuryPerMillibar
}
public var millibars: Double {
return rawValue
}
public func valueInUnit(_ unit: PressureUnit) -> Double {
switch unit {
case .inchesOfMercury: return inchesOfMercury
case .millibars: return millibars
}
}
}
public enum PressureUnit: Unit {
case inchesOfMercury
case millibars
}
extension PressureUnit {
public var abbreviation: String {
switch self {
case .inchesOfMercury: return MeasuresStrings.Unit.InchOfMercury.abbreviation
case .millibars: return MeasuresStrings.Unit.Millibar.abbreviation
}
}
public var name: PluralizedString {
switch self {
case .inchesOfMercury: return MeasuresStrings.Unit.InchOfMercury.name
case .millibars: return MeasuresStrings.Unit.Millibar.name
}
}
public var symbol: String? {
switch self {
case .inchesOfMercury: return "″Hg"
case .millibars: return nil
}
}
}
| 6ed1ed96c7f204884c6adb4753533d85 | 19.141304 | 79 | 0.733405 | false | false | false | false |
phatblat/3DTouchDemo | refs/heads/master | 3DTouchDemo/TouchCanvas/TouchCanvas/CanvasView.swift | mit | 1 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `CanvasView` tracks `UITouch`es and represents them as a series of `Line`s.
*/
import UIKit
@available(iOS 9.1, *)
class CanvasView: UIView {
// MARK: Properties
let isPredictionEnabled = UIDevice.currentDevice().userInterfaceIdiom == .Pad
let isTouchUpdatingEnabled = true
var usePreciseLocations = false
var isDebuggingEnabled = false
/// Array containing all line objects that need to be drawn in `drawRect(_:)`.
var lines = [Line]()
/**
Holds a map of `UITouch` objects to `Line` objects whose touch has not ended yet.
Use `NSMapTable` to handle association as `UITouch` doesn't conform to `NSCopying`.
*/
let activeLines = NSMapTable.strongToStrongObjectsMapTable()
/**
Holds a map of `UITouch` objects to `Line` objects whose touch has ended but still has points awaiting
updates.
Use `NSMapTable` to handle association as `UITouch` doesn't conform to `NSCopying`.
*/
let pendingLines = NSMapTable.strongToStrongObjectsMapTable()
/// A `CGContext` for drawing the last representation of lines no longer receiving updates into.
lazy var frozenContext: CGContext = {
let scale = self.window!.screen.scale
var size = self.bounds.size
size.width *= scale
size.height *= scale
let colorSpace = CGColorSpaceCreateDeviceRGB()
let context = CGBitmapContextCreate(nil, Int(size.width), Int(size.height), 8, 0, colorSpace, CGImageAlphaInfo.PremultipliedLast.rawValue)
CGContextSetLineCap(context, .Round)
let transform = CGAffineTransformMakeScale(scale, scale)
CGContextConcatCTM(context, transform)
return context!
}()
/// An optional `CGImage` containing the last representation of lines no longer receiving updates.
var frozenImage: CGImage?
// MARK: Drawing
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()!
CGContextSetLineCap(context, .Round)
frozenImage = frozenImage ?? CGBitmapContextCreateImage(frozenContext)
if let frozenImage = frozenImage {
CGContextDrawImage(context, bounds, frozenImage)
}
for line in lines {
line.drawInContext(context, isDebuggingEnabled: isDebuggingEnabled, usePreciseLocation: usePreciseLocations)
}
}
// MARK: Actions
func clear() {
activeLines.removeAllObjects()
pendingLines.removeAllObjects()
lines.removeAll()
frozenImage = nil
CGContextClearRect(frozenContext, bounds)
setNeedsDisplay()
}
// MARK: Convenience
func drawTouches(touches: Set<UITouch>, withEvent event: UIEvent?) {
var updateRect = CGRect.null
for touch in touches {
// Retrieve a line from `activeLines`. If no line exists, create one.
let line = activeLines.objectForKey(touch) as? Line ?? addActiveLineForTouch(touch)
/*
Remove prior predicted points and update the `updateRect` based on the removals. The touches
used to create these points are predictions provided to offer additional data. They are stale
by the time of the next event for this touch.
*/
updateRect.unionInPlace(line.removePointsWithType(.Predicted))
/*
Incorporate coalesced touch data. The data in the last touch in the returned array will match
the data of the touch supplied to `coalescedTouchesForTouch(_:)`
*/
let coalescedTouches = event?.coalescedTouchesForTouch(touch) ?? []
let coalescedRect = addPointsOfType(.Coalesced, forTouches: coalescedTouches, toLine: line, currentUpdateRect: updateRect)
updateRect.unionInPlace(coalescedRect)
/*
Incorporate predicted touch data. This sample draws predicted touches differently; however,
you may want to use them as inputs to smoothing algorithms rather than directly drawing them.
Points derived from predicted touches should be removed from the line at the next event for
this touch.
*/
if isPredictionEnabled {
let predictedTouches = event?.predictedTouchesForTouch(touch) ?? []
let predictedRect = addPointsOfType(.Predicted, forTouches: predictedTouches, toLine: line, currentUpdateRect: updateRect)
updateRect.unionInPlace(predictedRect)
}
}
setNeedsDisplayInRect(updateRect)
}
func addActiveLineForTouch(touch: UITouch) -> Line {
let newLine = Line()
activeLines.setObject(newLine, forKey: touch)
lines.append(newLine)
return newLine
}
func addPointsOfType(var type: LinePoint.PointType, forTouches touches: [UITouch], toLine line: Line, currentUpdateRect updateRect: CGRect) -> CGRect {
var accumulatedRect = CGRect.null
for (idx, touch) in touches.enumerate() {
let isStylus = touch.type == .Stylus
// The visualization displays non-`.Stylus` touches differently.
if !isStylus {
type.unionInPlace(.Finger)
}
// Touches with estimated properties require updates; add this information to the `PointType`.
if isTouchUpdatingEnabled && !touch.estimatedProperties.isEmpty {
type.unionInPlace(.NeedsUpdate)
}
// The last touch in a set of `.Coalesced` touches is the originating touch. Track it differently.
if type.contains(.Coalesced) && idx == touches.count - 1 {
type.subtractInPlace(.Coalesced)
type.unionInPlace(.Standard)
}
let force = isStylus || touch.force > 0 ? touch.force : 1.0
let touchRect = line.addPointAtLocation(touch.locationInView(self), preciseLocation: touch.preciseLocationInView(self), force: force, timestamp: touch.timestamp, type: type)
accumulatedRect.unionInPlace(touchRect)
commitLine(line)
}
return updateRect.union(accumulatedRect)
}
func endTouches(touches: Set<UITouch>, cancel: Bool) {
var updateRect = CGRect.null
for touch in touches {
// Skip over touches that do not correspond to an active line.
guard let line = activeLines.objectForKey(touch) as? Line else { continue }
// If this is a touch cancellation, cancel the associated line.
if cancel { updateRect.unionInPlace(line.cancel()) }
// If the line is complete (no points needing updates) or updating isn't enabled, move the line to the `frozenImage`.
if line.isComplete || !isTouchUpdatingEnabled {
finishLine(line)
}
// Otherwise, add the line to our map of touches to lines pending update.
else {
pendingLines.setObject(line, forKey: touch)
}
// This touch is ending, remove the line corresponding to it from `activeLines`.
activeLines.removeObjectForKey(touch)
}
setNeedsDisplayInRect(updateRect)
}
func updateEstimatedPropertiesForTouches(touches: Set<NSObject>) {
guard isTouchUpdatingEnabled, let touches = touches as? Set<UITouch> else { return }
var updateRect = CGRect.null
for touch in touches {
var isPending = false
// Look to retrieve a line from `activeLines`. If no line exists, look it up in `pendingLines`.
let possibleLine: Line? = activeLines.objectForKey(touch) as? Line ?? {
let pendingLine = pendingLines.objectForKey(touch) as? Line
isPending = pendingLine != nil
return pendingLine
}()
// If no line is related to the touch, return as there is no additional work to do.
guard let line = possibleLine else { return }
let updateEstimatedRect = line.updatePointLocation(touch.locationInView(self), preciseLocation: touch.preciseLocationInView(self), force: touch.force, forTimestamp: touch.timestamp)
updateRect.unionInPlace(updateEstimatedRect)
// If this update updated the last point requiring an update, move the line to the `frozenImage`.
if isPending && line.isComplete {
finishLine(line)
pendingLines.removeObjectForKey(touch)
}
// Otherwise, have the line add any points no longer requiring updates to the `frozenImage`.
else {
commitLine(line)
}
setNeedsDisplayInRect(updateRect)
}
}
func commitLine(line: Line) {
// Have the line draw any segments between points no longer being updated into the `frozenContext` and remove them from the line.
line.drawFixedPointsInContext(frozenContext, isDebuggingEnabled: isDebuggingEnabled, usePreciseLocation: usePreciseLocations)
// Force the `frozenImage` to be regenerated from the `frozenContext` during the next `drawRect(_:)` call.
frozenImage = nil
}
func finishLine(line: Line) {
// Have the line draw any remaining segments into the `frozenContext`.
line.drawInContext(frozenContext, isDebuggingEnabled: isDebuggingEnabled, usePreciseLocation: usePreciseLocations)
// Force the `frozenImage` to be regenerated from the `frozenContext` during the next `drawRect(_:)` call.
frozenImage = nil
// Cease tracking this line now that it is finished.
lines.removeAtIndex(lines.indexOf(line)!)
}
}
| 699ce0d7775d2d591f557a5b91063c9e | 40.366534 | 193 | 0.619282 | false | false | false | false |
jakepolatty/HighSchoolScienceBowlPractice | refs/heads/master | High School Science Bowl Practice/MainMenuViewController.swift | mit | 1 | //
// MainMenuViewController.swift
// High School Science Bowl Practice
//
// Created by David Polatty on 7/20/17.
// Copyright © 2017 Jake Polatty. All rights reserved.
//
import UIKit
class MainMenuViewController: UIViewController {
lazy var header: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "High School Science Bowl Practice"
label.numberOfLines = 0
label.font = UIFont.systemFont(ofSize: 39.0, weight: UIFont.Weight.heavy)
label.textAlignment = NSTextAlignment.center
label.textColor = UIColor.white
return label
}()
lazy var quizModeButton: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Quiz Mode", for: .normal)
button.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.25)
button.tintColor = UIColor.white
button.titleLabel?.font = UIFont.systemFont(ofSize: 18.0, weight: UIFont.Weight.light)
button.clipsToBounds = true
button.layer.cornerRadius = 10
button.addTarget(self, action: #selector(MainMenuViewController.startQuizMode), for: .touchUpInside)
return button
}()
lazy var readerModeButton: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Reader Mode", for: .normal)
button.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.25)
button.tintColor = UIColor.white
button.titleLabel?.font = UIFont.systemFont(ofSize: 18.0, weight: UIFont.Weight.light)
button.clipsToBounds = true
button.layer.cornerRadius = 10
button.addTarget(self, action: #selector(MainMenuViewController.startReaderMode), for: .touchUpInside)
return button
}()
lazy var studyModeButton: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Study Mode", for: .normal)
button.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.25)
button.tintColor = UIColor.white
button.titleLabel?.font = UIFont.systemFont(ofSize: 18.0, weight: UIFont.Weight.light)
button.clipsToBounds = true
button.layer.cornerRadius = 10
button.addTarget(self, action: #selector(MainMenuViewController.startStudyMode), for: .touchUpInside)
return button
}()
lazy var aboutButton: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("About", for: .normal)
button.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.15)
button.tintColor = UIColor.white
button.titleLabel?.font = UIFont.systemFont(ofSize: 14.0, weight: UIFont.Weight.light)
button.clipsToBounds = true
button.layer.cornerRadius = 22
button.addTarget(self, action: #selector(MainMenuViewController.openAboutPage), for: .touchUpInside)
return button
}()
lazy var helpButton: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Help", for: .normal)
button.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.15)
button.tintColor = UIColor.white
button.titleLabel?.font = UIFont.systemFont(ofSize: 14.0, weight: UIFont.Weight.light)
button.clipsToBounds = true
button.layer.cornerRadius = 22
button.addTarget(self, action: #selector(MainMenuViewController.openHelpPage), for: .touchUpInside)
return button
}()
lazy var logoImage: UIImageView = {
let imageView = UIImageView(image: #imageLiteral(resourceName: "Logo"))
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(red: 0.0, green: 147.0/255.0, blue: 255.0/255.0, alpha: 1.0)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
view.addSubview(header)
NSLayoutConstraint.activate([
header.centerXAnchor.constraint(equalTo: view.centerXAnchor),
header.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30),
header.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: 20)
])
view.addSubview(quizModeButton)
NSLayoutConstraint.activate([
quizModeButton.widthAnchor.constraint(equalToConstant: 150),
quizModeButton.heightAnchor.constraint(equalToConstant: 44),
quizModeButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
quizModeButton.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -35)
])
view.addSubview(readerModeButton)
NSLayoutConstraint.activate([
readerModeButton.widthAnchor.constraint(equalToConstant: 150),
readerModeButton.heightAnchor.constraint(equalToConstant: 44),
readerModeButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
readerModeButton.topAnchor.constraint(equalTo: quizModeButton.bottomAnchor, constant: 25)
])
view.addSubview(studyModeButton)
NSLayoutConstraint.activate([
studyModeButton.widthAnchor.constraint(equalToConstant: 150),
studyModeButton.heightAnchor.constraint(equalToConstant: 44),
studyModeButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
studyModeButton.topAnchor.constraint(equalTo: readerModeButton.bottomAnchor, constant: 25)
])
view.addSubview(aboutButton)
NSLayoutConstraint.activate([
aboutButton.widthAnchor.constraint(equalToConstant: 44),
aboutButton.heightAnchor.constraint(equalToConstant: 44),
aboutButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
aboutButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -10)
])
view.addSubview(helpButton)
NSLayoutConstraint.activate([
helpButton.widthAnchor.constraint(equalToConstant: 44),
helpButton.heightAnchor.constraint(equalToConstant: 44),
helpButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
helpButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -10)
])
view.addSubview(logoImage)
NSLayoutConstraint.activate([
logoImage.widthAnchor.constraint(equalToConstant: 80),
logoImage.heightAnchor.constraint(equalToConstant: 80),
logoImage.centerXAnchor.constraint(equalTo: view.centerXAnchor),
logoImage.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -14)
])
}
@objc func startQuizMode() {
let quizSettingsController = QuizSettingsViewController()
let navigationController = UINavigationController(rootViewController: quizSettingsController)
self.present(navigationController, animated: true, completion: nil)
}
@objc func startReaderMode() {
let readerSettingsController = ReaderSettingsViewController()
let navigationController = UINavigationController(rootViewController: readerSettingsController)
self.present(navigationController, animated: true, completion: nil)
}
@objc func startStudyMode() {
let studySettingsController = StudySettingsViewController()
let navigationController = UINavigationController(rootViewController: studySettingsController)
self.present(navigationController, animated: true, completion: nil)
}
@objc func openAboutPage() {
let aboutPageController = AboutPageViewController()
let navigationController = UINavigationController(rootViewController: aboutPageController)
self.present(navigationController, animated: true, completion: nil)
}
@objc func openHelpPage() {
let helpPageController = HelpPageViewController()
let navigationController = UINavigationController(rootViewController: helpPageController)
self.present(navigationController, animated: true, completion: nil)
}
}
| 8a09617890a654384764073cfc03c656 | 45.116402 | 110 | 0.685636 | false | false | false | false |
atl009/WordPress-iOS | refs/heads/develop | WordPress/Classes/ViewRelated/Reader/ReaderGapMarkerCell.swift | gpl-2.0 | 1 | import Foundation
import WordPressShared.WPStyleGuide
open class ReaderGapMarkerCell: UITableViewCell {
@IBOutlet fileprivate weak var tearBackgroundView: UIView!
@IBOutlet fileprivate weak var tearMaskView: UIView!
@IBOutlet fileprivate weak var activityViewBackgroundView: UIView!
@IBOutlet fileprivate weak var activityView: UIActivityIndicatorView!
@IBOutlet fileprivate weak var button: UIButton!
open override func awakeFromNib() {
super.awakeFromNib()
applyStyles()
}
fileprivate func applyStyles() {
// Background styles
contentView.backgroundColor = WPStyleGuide.greyLighten30()
selectedBackgroundView = UIView(frame: contentView.frame)
selectedBackgroundView?.backgroundColor = WPStyleGuide.greyLighten30()
contentView.backgroundColor = WPStyleGuide.greyLighten30()
tearMaskView.backgroundColor = WPStyleGuide.greyLighten30()
// Draw the tear
drawTearBackground()
activityViewBackgroundView.backgroundColor = WPStyleGuide.greyDarken10()
activityViewBackgroundView.layer.cornerRadius = 4.0
activityViewBackgroundView.layer.masksToBounds = true
// Button style
WPStyleGuide.applyGapMarkerButtonStyle(button)
let text = NSLocalizedString("Load more posts", comment: "A short label. A call to action to load more posts.")
button.setTitle(text, for: UIControlState())
button.layer.cornerRadius = 4.0
button.layer.masksToBounds = true
// Disable button interactions so the full cell handles the tap.
button.isUserInteractionEnabled = false
}
open func animateActivityView(_ animate: Bool) {
button.alpha = animate ? WPAlphaZero : WPAlphaFull
if animate {
activityView.startAnimating()
} else {
activityView.stopAnimating()
}
}
open override func setHighlighted(_ highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
button.isHighlighted = highlighted
button.backgroundColor = highlighted ? WPStyleGuide.gapMarkerButtonBackgroundColorHighlighted() : WPStyleGuide.gapMarkerButtonBackgroundColor()
if highlighted {
// Redraw the backgrounds when highlighted
drawTearBackground()
tearMaskView.backgroundColor = WPStyleGuide.greyLighten30()
}
}
func drawTearBackground() {
let tearImage = UIImage(named: "background-reader-tear")
tearBackgroundView.backgroundColor = UIColor(patternImage: tearImage!)
}
}
| 9fa221f8ab1af61c8f58c65b261c46f8 | 38.833333 | 151 | 0.704831 | false | false | false | false |
thisfin/HostsManager | refs/heads/develop | HostsManager/StatusMenu.swift | mit | 1 | //
// WYMenu.swift
// HostsManager
//
// Created by wenyou on 2016/12/26.
// Copyright © 2016年 wenyou. All rights reserved.
//
import AppKit
class StatusMenu: NSMenu {
weak var statusItem: NSStatusItem?
var popover: NSPopover = {
let popover = NSPopover.init()
popover.contentViewController = {
let controller = PopoverViewController()
controller.popover = popover
return controller
}()
return popover
}()
init(statusItem: NSStatusItem?) {
super.init(title: "")
self.statusItem = statusItem
delegate = self
}
required init(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - private
func addDefaultItem() {
addItem(NSMenuItem.separator())
addItem({
let menuItem = NSMenuItem(title: "Edit Hosts", action: #selector(StatusMenu.editClicked(_:)), keyEquivalent: "")
menuItem.target = self
return menuItem
}())
addItem({
let menuItem = NSMenuItem(title: "Preferences...", action: #selector(StatusMenu.settingClicked(_:)), keyEquivalent: "")
menuItem.target = self
return menuItem
}())
addItem(NSMenuItem.separator())
addItem(withTitle: "About \(ProcessInfo.processInfo.processName)", action: #selector(NSApp.orderFrontStandardAboutPanel(_:)), keyEquivalent: "")
addItem(withTitle: "Quit \(ProcessInfo.processInfo.processName)", action: #selector(NSApp.terminate(_:)), keyEquivalent: "")
}
func editClicked(_ sender: NSMenuItem) {
NSRunningApplication.current().activate(options: [.activateIgnoringOtherApps])
NSApp.windows.forEach { (window) in
if let win = window as? SettingWindow {
win.toolbarItemSelected(identifier: .edit)
win.center()
win.makeKeyAndOrderFront(self)
return
}
}
}
func settingClicked(_ sender: NSMenuItem) { // 唤起 window 切换至 setting controller
NSRunningApplication.current().activate(options: [.activateIgnoringOtherApps])
NSApp.windows.forEach { (window) in
if let win = window as? SettingWindow {
win.toolbarItemSelected(identifier: .setting)
win.center()
win.makeKeyAndOrderFront(self)
return
}
}
}
func groupClicked(_ sender: NSMenuItem) {
let filePermissions = FilePermissions.sharedInstance
if !filePermissions.hostFileWritePermissionsCheck() || !filePermissions.bookmarkCheck() {
return
}
let dataManager = HostDataManager.sharedInstance
let group = dataManager.groups[sender.tag - 100]
group.selected = !group.selected
dataManager.updateGroupData()
HostsFileManager.sharedInstance.writeContentToFile(content: dataManager.groups)
NotificationCenter.default.post(name: .WYStatusMenuUpdateHosts, object: nil)
AlertPanel.show("hosts 文件已同步")
}
}
extension StatusMenu: NSMenuDelegate {
func menuWillOpen(_ menu: NSMenu) { // 开启时初始化 menu
removeAllItems()
let dataManager = HostDataManager.sharedInstance
for index in 0 ..< dataManager.groups.count {
let group = dataManager.groups[index]
addItem({
let menuItem = NSMenuItem.init(title: group.name!, action: #selector(StatusMenu.groupClicked(_:)), keyEquivalent: "")
menuItem.tag = index + 100
menuItem.target = self
if group.selected {
menuItem.state = NSOnState
}
return menuItem
}())
}
addDefaultItem()
}
func menuDidClose(_ menu: NSMenu) { // 关闭时关闭浮层
if popover.isShown {
popover.performClose(nil)
}
}
func menu(_ menu: NSMenu, willHighlight item: NSMenuItem?) { // 鼠标浮动变更时改变浮层显示内容
if let menuItem = item, menuItem.tag >= 100, let button = statusItem?.button {
let group = HostDataManager.sharedInstance.groups[(menuItem.tag - 100)]
var string = ""
group.hosts.forEach({ (host) in
string.append((string.characters.count == 0 ? "" : "\n") + "\(host.ip) \(host.domain)")
})
if !popover.isShown {
popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minX)
}
// 此行代码放在下边是因为第一次时, controller viewWillApper 之前调用 fittingSize 返回结果不对
if let controller = popover.contentViewController as? PopoverViewController {
controller.setText(string: string)
}
} else {
if popover.isShown {
popover.performClose(nil)
}
}
}
}
extension Notification.Name {
static let WYStatusMenuUpdateHosts = Notification.Name("StatusMenuUpdateHosts")
}
| 2553fb78d49472ba034462503fa63683 | 34.384615 | 152 | 0.596047 | false | false | false | false |
Lves/LLRefresh | refs/heads/master | LLRefresh/Custom/Footer/LLRefreshAutoNormalFooter.swift | mit | 1 | //
// LLRefreshAutoNormalFooter.swift
// LLRefreshDemo
//
// Created by lixingle on 2017/1/22.
// Copyright © 2017年 com.lvesli. All rights reserved.
//
import UIKit
open class LLRefreshAutoNormalFooter: LLRefreshAutoStateFooter {
var activityIndicatorViewStyle: UIActivityIndicatorViewStyle = .gray{
didSet{
setNeedsLayout()
}
}
fileprivate lazy var loadingView: UIActivityIndicatorView = {
let loadingView = UIActivityIndicatorView(activityIndicatorStyle: self.activityIndicatorViewStyle)
loadingView.hidesWhenStopped = true
self.addSubview(loadingView)
return loadingView
}()
override open func placeSubViews() {
super.placeSubViews()
guard loadingView.constraints.count == 0 else {
return
}
var centerX = ll_w * 0.5
if !refreshingTitleHidden {
centerX -= (stateLabel.ll_textWidth * 0.5 + labelLeftInset)
}
let centerY = ll_h * 0.5
loadingView.center = CGPoint(x: centerX, y: centerY)
loadingView.tintColor = stateLabel.textColor
}
override open func setState(_ state: LLRefreshState) {
super.setState(state)
if state == .noMoreData || state == .normal {
loadingView.stopAnimating()
}else if state == .refreshing {
loadingView.startAnimating()
}
}
}
| 43385740611ebeb5c6187468f0b1ea13 | 28.854167 | 106 | 0.626657 | false | false | false | false |
jsslai/Action | refs/heads/master | Carthage/Checkouts/RxSwift/RxCocoa/Common/Observables/NSObject+Rx.swift | mit | 1 | //
// NSObject+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
#if !DISABLE_SWIZZLING
var deallocatingSubjectTriggerContext: UInt8 = 0
var deallocatingSubjectContext: UInt8 = 0
#endif
var deallocatedSubjectTriggerContext: UInt8 = 0
var deallocatedSubjectContext: UInt8 = 0
/**
KVO is a tricky mechanism.
When observing child in a ownership hierarchy, usually retaining observing target is wanted behavior.
When observing parent in a ownership hierarchy, usually retaining target isn't wanter behavior.
KVO with weak references is especially tricky. For it to work, some kind of swizzling is required.
That can be done by
* replacing object class dynamically (like KVO does)
* by swizzling `dealloc` method on all instances for a class.
* some third method ...
Both approaches can fail in certain scenarios:
* problems arise when swizzlers return original object class (like KVO does when nobody is observing)
* Problems can arise because replacing dealloc method isn't atomic operation (get implementation,
set implementation).
Second approach is chosen. It can fail in case there are multiple libraries dynamically trying
to replace dealloc method. In case that isn't the case, it should be ok.
*/
extension Reactive where Base: NSObject {
/**
Observes values on `keyPath` starting from `self` with `options` and retains `self` if `retainSelf` is set.
`observe` is just a simple and performant wrapper around KVO mechanism.
* it can be used to observe paths starting from `self` or from ancestors in ownership graph (`retainSelf = false`)
* it can be used to observe paths starting from descendants in ownership graph (`retainSelf = true`)
* the paths have to consist only of `strong` properties, otherwise you are risking crashing the system by not unregistering KVO observer before dealloc.
If support for weak properties is needed or observing arbitrary or unknown relationships in the
ownership tree, `observeWeakly` is the preferred option.
- parameter keyPath: Key path of property names to observe.
- parameter options: KVO mechanism notification options.
- parameter retainSelf: Retains self during observation if set `true`.
- returns: Observable sequence of objects on `keyPath`.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func observe<E>(_ type: E.Type, _ keyPath: String, options: NSKeyValueObservingOptions = [.new, .initial], retainSelf: Bool = true) -> Observable<E?> {
return KVOObservable(object: base, keyPath: keyPath, options: options, retainTarget: retainSelf).asObservable()
}
}
#if !DISABLE_SWIZZLING
// KVO
extension Reactive where Base: NSObject {
/**
Observes values on `keyPath` starting from `self` with `options` and doesn't retain `self`.
It can be used in all cases where `observe` can be used and additionally
* because it won't retain observed target, it can be used to observe arbitrary object graph whose ownership relation is unknown
* it can be used to observe `weak` properties
**Since it needs to intercept object deallocation process it needs to perform swizzling of `dealloc` method on observed object.**
- parameter keyPath: Key path of property names to observe.
- parameter options: KVO mechanism notification options.
- returns: Observable sequence of objects on `keyPath`.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func observeWeakly<E>(_ type: E.Type, _ keyPath: String, options: NSKeyValueObservingOptions = [.new, .initial]) -> Observable<E?> {
return observeWeaklyKeyPathFor(base, keyPath: keyPath, options: options)
.map { n in
return n as? E
}
}
}
#endif
// Dealloc
extension Reactive where Base: AnyObject {
/**
Observable sequence of object deallocated events.
After object is deallocated one `()` element will be produced and sequence will immediately complete.
- returns: Observable sequence of object deallocated events.
*/
public var deallocated: Observable<Void> {
return synchronized {
if let deallocObservable = objc_getAssociatedObject(base, &deallocatedSubjectContext) as? DeallocObservable {
return deallocObservable._subject
}
let deallocObservable = DeallocObservable()
objc_setAssociatedObject(base, &deallocatedSubjectContext, deallocObservable, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return deallocObservable._subject
}
}
#if !DISABLE_SWIZZLING
/**
Observable sequence of message arguments that completes when object is deallocated.
Each element is produced before message is invoked on target object. `methodInvoked`
exists in case observing of invoked messages is needed.
In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`.
In case some argument is `nil`, instance of `NSNull()` will be sent.
- returns: Observable sequence of object deallocating events.
*/
public func sentMessage(_ selector: Selector) -> Observable<[Any]> {
return synchronized {
// in case of dealloc selector replay subject behavior needs to be used
if selector == deallocSelector {
return deallocating.map { _ in [] }
}
do {
let proxy: MessageSentProxy = try registerMessageInterceptor(selector)
return proxy.messageSent.asObservable()
}
catch let e {
return Observable.error(e)
}
}
}
/**
Observable sequence of message arguments that completes when object is deallocated.
Each element is produced after message is invoked on target object. `sentMessage`
exists in case interception of sent messages before they were invoked is needed.
In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`.
In case some argument is `nil`, instance of `NSNull()` will be sent.
- returns: Observable sequence of object deallocating events.
*/
public func methodInvoked(_ selector: Selector) -> Observable<[Any]> {
return synchronized {
// in case of dealloc selector replay subject behavior needs to be used
if selector == deallocSelector {
return deallocated.map { _ in [] }
}
do {
let proxy: MessageSentProxy = try registerMessageInterceptor(selector)
return proxy.methodInvoked.asObservable()
}
catch let e {
return Observable.error(e)
}
}
}
/**
Observable sequence of object deallocating events.
When `dealloc` message is sent to `self` one `()` element will be produced and after object is deallocated sequence
will immediately complete.
In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`.
- returns: Observable sequence of object deallocating events.
*/
public var deallocating: Observable<()> {
return synchronized {
do {
let proxy: DeallocatingProxy = try registerMessageInterceptor(deallocSelector)
return proxy.messageSent.asObservable()
}
catch let e {
return Observable.error(e)
}
}
}
fileprivate func registerMessageInterceptor<T: MessageInterceptorSubject>(_ selector: Selector) throws -> T {
let rxSelector = RX_selector(selector)
let selectorReference = RX_reference_from_selector(rxSelector)
let subject: T
if let existingSubject = objc_getAssociatedObject(base, selectorReference) as? T {
subject = existingSubject
}
else {
subject = T()
objc_setAssociatedObject(
base,
selectorReference,
subject,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
if subject.isActive {
return subject
}
var error: NSError?
let targetImplementation = RX_ensure_observing(base, selector, &error)
if targetImplementation == nil {
throw error?.rxCocoaErrorForTarget(base) ?? RxCocoaError.unknown
}
subject.targetImplementation = targetImplementation!
return subject
}
#endif
}
// MARK: Message interceptors
#if !DISABLE_SWIZZLING
fileprivate protocol MessageInterceptorSubject: class {
init()
var isActive: Bool {
get
}
var targetImplementation: IMP { get set }
}
fileprivate final class DeallocatingProxy
: MessageInterceptorSubject
, RXDeallocatingObserver {
typealias E = ()
let messageSent = ReplaySubject<()>.create(bufferSize: 1)
@objc var targetImplementation: IMP = RX_default_target_implementation()
var isActive: Bool {
return targetImplementation != RX_default_target_implementation()
}
init() {
}
@objc func deallocating() -> Void {
messageSent.on(.next())
}
deinit {
messageSent.on(.completed)
}
}
fileprivate final class MessageSentProxy
: MessageInterceptorSubject
, RXMessageSentObserver {
typealias E = [AnyObject]
let messageSent = PublishSubject<[Any]>()
let methodInvoked = PublishSubject<[Any]>()
@objc var targetImplementation: IMP = RX_default_target_implementation()
var isActive: Bool {
return targetImplementation != RX_default_target_implementation()
}
init() {
}
@objc func messageSent(withArguments arguments: [Any]) -> Void {
messageSent.on(.next(arguments))
}
@objc func methodInvoked(withArguments arguments: [Any]) -> Void {
methodInvoked.on(.next(arguments))
}
deinit {
messageSent.on(.completed)
methodInvoked.on(.completed)
}
}
#endif
fileprivate class DeallocObservable {
let _subject = ReplaySubject<Void>.create(bufferSize:1)
init() {
}
deinit {
_subject.on(.next(()))
_subject.on(.completed)
}
}
// MARK: KVO
fileprivate protocol KVOObservableProtocol {
var target: AnyObject { get }
var keyPath: String { get }
var retainTarget: Bool { get }
var options: NSKeyValueObservingOptions { get }
}
fileprivate class KVOObserver
: _RXKVOObserver
, Disposable {
typealias Callback = (Any?) -> Void
var retainSelf: KVOObserver? = nil
init(parent: KVOObservableProtocol, callback: @escaping Callback) {
#if TRACE_RESOURCES
OSAtomicIncrement32(&resourceCount)
#endif
super.init(target: parent.target, retainTarget: parent.retainTarget, keyPath: parent.keyPath, options: parent.options, callback: callback)
self.retainSelf = self
}
override func dispose() {
super.dispose()
self.retainSelf = nil
}
deinit {
#if TRACE_RESOURCES
OSAtomicDecrement32(&resourceCount)
#endif
}
}
fileprivate class KVOObservable<Element>
: ObservableType
, KVOObservableProtocol {
typealias E = Element?
unowned var target: AnyObject
var strongTarget: AnyObject?
var keyPath: String
var options: NSKeyValueObservingOptions
var retainTarget: Bool
init(object: AnyObject, keyPath: String, options: NSKeyValueObservingOptions, retainTarget: Bool) {
self.target = object
self.keyPath = keyPath
self.options = options
self.retainTarget = retainTarget
if retainTarget {
self.strongTarget = object
}
}
func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element? {
let observer = KVOObserver(parent: self) { (value) in
if value as? NSNull != nil {
observer.on(.next(nil))
return
}
observer.on(.next(value as? Element))
}
return Disposables.create(with: observer.dispose)
}
}
#if !DISABLE_SWIZZLING
fileprivate func observeWeaklyKeyPathFor(_ target: NSObject, keyPath: String, options: NSKeyValueObservingOptions) -> Observable<AnyObject?> {
let components = keyPath.components(separatedBy: ".").filter { $0 != "self" }
let observable = observeWeaklyKeyPathFor(target, keyPathSections: components, options: options)
.finishWithNilWhenDealloc(target)
if !options.intersection(.initial).isEmpty {
return observable
}
else {
return observable
.skip(1)
}
}
// This should work correctly
// Identifiers can't contain `,`, so the only place where `,` can appear
// is as a delimiter.
// This means there is `W` as element in an array of property attributes.
fileprivate func isWeakProperty(_ properyRuntimeInfo: String) -> Bool {
return properyRuntimeInfo.range(of: ",W,") != nil
}
fileprivate extension ObservableType where E == AnyObject? {
func finishWithNilWhenDealloc(_ target: NSObject)
-> Observable<AnyObject?> {
let deallocating = target.rx.deallocating
return deallocating
.map { _ in
return Observable.just(nil)
}
.startWith(self.asObservable())
.switchLatest()
}
}
fileprivate func observeWeaklyKeyPathFor(
_ target: NSObject,
keyPathSections: [String],
options: NSKeyValueObservingOptions
) -> Observable<AnyObject?> {
weak var weakTarget: AnyObject? = target
let propertyName = keyPathSections[0]
let remainingPaths = Array(keyPathSections[1..<keyPathSections.count])
let property = class_getProperty(object_getClass(target), propertyName)
if property == nil {
return Observable.error(RxCocoaError.invalidPropertyName(object: target, propertyName: propertyName))
}
let propertyAttributes = property_getAttributes(property)
// should dealloc hook be in place if week property, or just create strong reference because it doesn't matter
let isWeak = isWeakProperty(propertyAttributes.map(String.init) ?? "")
let propertyObservable = KVOObservable(object: target, keyPath: propertyName, options: options.union(.initial), retainTarget: false) as KVOObservable<AnyObject>
// KVO recursion for value changes
return propertyObservable
.flatMapLatest { (nextTarget: AnyObject?) -> Observable<AnyObject?> in
if nextTarget == nil {
return Observable.just(nil)
}
let nextObject = nextTarget! as? NSObject
let strongTarget: AnyObject? = weakTarget
if nextObject == nil {
return Observable.error(RxCocoaError.invalidObjectOnKeyPath(object: nextTarget!, sourceObject: strongTarget ?? NSNull(), propertyName: propertyName))
}
// if target is alive, then send change
// if it's deallocated, don't send anything
if strongTarget == nil {
return Observable.empty()
}
let nextElementsObservable = keyPathSections.count == 1
? Observable.just(nextTarget)
: observeWeaklyKeyPathFor(nextObject!, keyPathSections: remainingPaths, options: options)
if isWeak {
return nextElementsObservable
.finishWithNilWhenDealloc(nextObject!)
}
else {
return nextElementsObservable
}
}
}
#endif
// MARK Constants
fileprivate let deallocSelector = NSSelectorFromString("dealloc")
// MARK: AnyObject + Reactive
extension Reactive where Base: AnyObject {
func synchronized<T>( _ action: () -> T) -> T {
objc_sync_enter(self.base)
let result = action()
objc_sync_exit(self.base)
return result
}
}
extension Reactive where Base: AnyObject {
/**
Helper to make sure that `Observable` returned from `createCachedObservable` is only created once.
This is important because there is only one `target` and `action` properties on `NSControl` or `UIBarButtonItem`.
*/
func lazyInstanceObservable<T: AnyObject>(_ key: UnsafeRawPointer, createCachedObservable: () -> T) -> T {
if let value = objc_getAssociatedObject(base, key) {
return value as! T
}
let observable = createCachedObservable()
objc_setAssociatedObject(base, key, observable, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return observable
}
}
| be224fee77501d1a8e3cc37f4908a6fd | 32.477842 | 169 | 0.638101 | false | false | false | false |
QuarkX/Quark | refs/heads/master | Sources/Quark/HTTP/Serializer/ResponseSerializer.swift | mit | 1 | public class ResponseSerializer {
let stream: Stream
let bufferSize: Int
public init(stream: Stream, bufferSize: Int = 2048) {
self.stream = stream
self.bufferSize = bufferSize
}
public func serialize(_ response: Response) throws {
let newLine: Data = Data([13, 10])
try stream.write("HTTP/\(response.version.major).\(response.version.minor) \(response.status.statusCode) \(response.status.reasonPhrase)")
try stream.write(newLine)
for (name, value) in response.headers.headers {
try stream.write("\(name): \(value)")
try stream.write(newLine)
}
for cookie in response.cookieHeaders {
try stream.write("Set-Cookie: \(cookie)".data)
try stream.write(newLine)
}
try stream.write(newLine)
switch response.body {
case .buffer(let buffer):
try stream.write(buffer)
case .reader(let reader):
var buffer = Data(count: bufferSize)
while !reader.closed {
let bytesRead = try reader.read(into: &buffer)
if bytesRead == 0 {
break
}
try stream.write(String(bytesRead, radix: 16))
try stream.write(newLine)
try stream.write(buffer, length: bytesRead)
try stream.write(newLine)
}
try stream.write("0")
try stream.write(newLine)
try stream.write(newLine)
case .writer(let writer):
let body = BodyStream(stream)
try writer(body)
try stream.write("0")
try stream.write(newLine)
try stream.write(newLine)
}
try stream.flush()
}
}
| cd4754be28843737d43da0070a8d3e93 | 28.52459 | 146 | 0.548029 | false | false | false | false |
darrarski/SwipeToReveal-iOS | refs/heads/master | Source/SwipeToRevealView.swift | mit | 1 | import UIKit
import SnapKit
public protocol SwipeToRevealViewDelegate: class {
func swipeToRevealView(_ view: SwipeToRevealView, didCloseAnimated animated: Bool)
func swipeToRevealView(_ view: SwipeToRevealView, didRevealRightAnimated animated: Bool)
func swipeToRevealView(_ view: SwipeToRevealView, didPan pan: UIPanGestureRecognizer)
}
/// Swipe-to-reveal view
public class SwipeToRevealView: UIView {
public weak var delegate: SwipeToRevealViewDelegate?
/// Create SwipeToRevealView
///
/// - Parameter frame: frame
override public init(frame: CGRect) {
super.init(frame: frame)
loadSubviews()
setupLayout()
setupGestureRecognizing()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Close, so not extra content is revealed
///
/// - Parameter animated: perform with animation
public func close(animated: Bool) {
contentOffset = closedOffset
layoutIfNeeded(animated: animated)
delegate?.swipeToRevealView(self, didCloseAnimated: animated)
}
/// Reveal right view
///
/// - Parameter animated: perform with animation
public func revealRight(animated: Bool) {
contentOffset = rightRevealedOffset
layoutIfNeeded(animated: animated)
delegate?.swipeToRevealView(self, didRevealRightAnimated: animated)
}
// MARK: Subviews
/// Main view, displayed fully when no extra content is revealed
public var contentView: UIView? {
didSet {
if let oldValue = oldValue {
oldValue.removeFromSuperview()
}
if let newValue = contentView {
centerContainer.addSubview(newValue)
newValue.snp.makeConstraints { $0.edges.equalToSuperview() }
}
}
}
/// Right view, hidden by default, can be revelead with swipe gesture
public var rightView: UIView? {
didSet {
if let oldValue = oldValue {
oldValue.removeFromSuperview()
}
if let newValue = rightView {
rightContainer.addSubview(newValue)
newValue.snp.makeConstraints { $0.edges.equalToSuperview() }
}
}
}
private func loadSubviews() {
addSubview(centerContainer)
addSubview(rightContainer)
}
private let centerContainer = UIView(frame: .zero)
private let rightContainer = UIView(frame: .zero)
// MARK: Layout
/// Content offset - changes when swiping
public var contentOffset = CGFloat(0) {
didSet { centerContainer.snp.updateConstraints { $0.left.equalTo(contentOffset) } }
}
/// Value for content offset in default state
public let closedOffset = CGFloat(0)
/// Value for content offset when right view is fully revealed
public var rightRevealedOffset: CGFloat {
return -rightContainer.frame.width
}
private func setupLayout() {
centerContainer.snp.makeConstraints {
$0.top.equalToSuperview()
$0.bottom.equalToSuperview()
$0.size.equalToSuperview()
$0.left.equalTo(contentOffset)
}
rightContainer.snp.makeConstraints {
$0.top.equalTo(centerContainer.snp.top)
$0.left.equalTo(centerContainer.snp.right)
$0.bottom.equalTo(centerContainer.snp.bottom)
}
}
private func layoutIfNeeded(animated: Bool) {
guard animated else {
super.layoutIfNeeded()
return
}
UIView.animate(withDuration: 0.2,
delay: 0,
options: UIViewAnimationOptions.curveEaseInOut,
animations: { [weak self] in self?.layoutIfNeeded() })
}
// MARK: Gesture recognizing
private func setupGestureRecognizing() {
panGeastureRecognizer.delegate = self
panGeastureRecognizer.addTarget(self, action: #selector(self.panGestureRecognizerUpdate(_:)))
addGestureRecognizer(panGeastureRecognizer)
}
private let panGeastureRecognizer = UIPanGestureRecognizer()
private struct Pan {
let startPoint: CGFloat
let startOffset: CGFloat
var currentPoint: CGFloat {
didSet { previousPoint = oldValue }
}
private var previousPoint: CGFloat
var lastDelta: CGFloat {
return currentPoint - previousPoint
}
var delta: CGFloat {
return currentPoint - startPoint
}
init(point: CGFloat, offset: CGFloat) {
self.startPoint = point
self.startOffset = offset
self.currentPoint = point
self.previousPoint = point
}
}
private var pan: Pan?
func panGestureRecognizerUpdate(_ pgr: UIPanGestureRecognizer) {
switch pgr.state {
case .possible: break
case .began:
handlePanBegan(point: pgr.translation(in: self).x)
case .changed:
handlePanChanged(point: pgr.translation(in: self).x)
case .ended, .cancelled, .failed:
handlePanEnded()
}
delegate?.swipeToRevealView(self, didPan: pgr)
}
private func handlePanBegan(point: CGFloat) {
pan = Pan(point: point, offset: contentOffset)
}
private func handlePanChanged(point: CGFloat) {
pan?.currentPoint = point
guard let pan = pan else { return }
let targetOffset = pan.startOffset + pan.delta
contentOffset = max(rightRevealedOffset, min(closedOffset, targetOffset))
}
private func handlePanEnded() {
guard let pan = pan else { return }
if pan.lastDelta > 0 {
contentOffset = closedOffset
} else {
contentOffset = rightRevealedOffset
}
layoutIfNeeded(animated: true)
self.pan = nil
}
}
extension SwipeToRevealView: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith
otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
override public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard let pgr = gestureRecognizer as? UIPanGestureRecognizer else { fatalError() }
let velocity = pgr.velocity(in: self)
return fabs(velocity.x) > fabs(velocity.y)
}
}
| 58659071ee8e13dcafa7d0e5a5f33e89 | 29.666667 | 105 | 0.625302 | false | false | false | false |
billdonner/sheetcheats9 | refs/heads/master | CircleMenuLib/CircleMenuButton/CircleMenuButton.swift | apache-2.0 | 1 | //
// CircleMenuButton.swift
//
// Copyright (c) 18/01/16. Ramotion Inc. (http://ramotion.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
internal class CircleMenuButton: UIButton {
// MARK: properties
weak var container: UIView?
// MARK: life cycle
init(size: CGSize, platform: UIView, distance: Float, angle: Float = 0) {
super.init(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: size))
self.backgroundColor = Col.r ( .gigMatrixMenuBackground)
self.layer.cornerRadius = size.height / 2.0
let aContainer = createContainer(CGSize(width: size.width, height:CGFloat(distance)), platform: platform)
// hack view for rotate
let view = UIView(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height))
view.backgroundColor = UIColor.clear
view.addSubview(self)
//...
aContainer.addSubview(view)
container = aContainer
view.layer.transform = CATransform3DMakeRotation(-CGFloat(angle.degrees), 0, 0, 1)
self.rotatedZ(angle: angle, animated: false)
}
required internal init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: configure
fileprivate func createContainer(_ size: CGSize, platform: UIView) -> UIView {
let container = Init(UIView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: size))) {
$0.backgroundColor = UIColor.clear
$0.translatesAutoresizingMaskIntoConstraints = false
$0.layer.anchorPoint = CGPoint(x: 0.5, y: 1)
}
platform.addSubview(container)
// added constraints
let height = NSLayoutConstraint(item: container,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .height,
multiplier: 1,
constant: size.height)
height.identifier = "height"
container.addConstraint(height)
container.addConstraint(NSLayoutConstraint(item: container,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .width,
multiplier: 1,
constant: size.width))
platform.addConstraint(NSLayoutConstraint(item: platform,
attribute: .centerX,
relatedBy: .equal,
toItem: container,
attribute: .centerX,
multiplier: 1,
constant:0))
platform.addConstraint(NSLayoutConstraint(item: platform,
attribute: .centerY,
relatedBy: .equal,
toItem: container,
attribute: .centerY,
multiplier: 1,
constant:0))
return container
}
// MARK: methods
internal func rotatedZ(angle: Float, animated: Bool, duration: Double = 0, delay: Double = 0) {
guard let container = self.container else {
fatalError("contaner don't create")
}
let rotateTransform = CATransform3DMakeRotation(CGFloat(angle.degrees), 0, 0, 1)
if animated {
UIView.animate(
withDuration: duration,
delay: delay,
options: UIViewAnimationOptions(),
animations: { () -> Void in
container.layer.transform = rotateTransform
},
completion: nil)
} else {
container.layer.transform = rotateTransform
}
}
}
// MARK: Animations
internal extension CircleMenuButton {
internal func showAnimation(distance: Float, duration: Double, delay: Double = 0) {
guard let heightConstraint = (self.container?.constraints.filter {$0.identifier == "height"})?.first else {
fatalError()
}
self.transform = CGAffineTransform(scaleX: 0, y: 0)
self.container?.superview?.layoutIfNeeded()
self.alpha = 0
heightConstraint.constant = CGFloat(distance)
UIView.animate(
withDuration: duration,
delay: delay,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0,
options: UIViewAnimationOptions.curveLinear,
animations: { () -> Void in
self.container?.superview?.layoutIfNeeded()
self.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.alpha = 1
}, completion: { (success) -> Void in
})
}
internal func hideAnimation(distance: Float, duration: Double, delay: Double = 0) {
guard let heightConstraint = (self.container?.constraints.filter {$0.identifier == "height"})?.first else {
fatalError()
}
heightConstraint.constant = CGFloat(distance)
UIView.animate(
withDuration: duration,
delay: delay,
options: UIViewAnimationOptions.curveEaseIn,
animations: { () -> Void in
self.container?.superview?.layoutIfNeeded()
self.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
}, completion: { (success) -> Void in
self.alpha = 0
if let _ = self.container {
self.container?.removeFromSuperview() // remove container
}
})
}
internal func changeDistance(_ distance: CGFloat, animated: Bool, duration: Double = 0, delay: Double = 0) {
guard let heightConstraint = (self.container?.constraints.filter {$0.identifier == "height"})?.first else {
fatalError()
}
heightConstraint.constant = distance
UIView.animate(
withDuration: duration,
delay: delay,
options: UIViewAnimationOptions.curveEaseIn,
animations: { () -> Void in
self.container?.superview?.layoutIfNeeded()
},
completion: nil)
}
// MARK: layer animation
internal func rotationAnimation(_ angle: Float, duration: Double) {
let rotation = Init(CABasicAnimation(keyPath: "transform.rotation")) {
$0.duration = TimeInterval(duration)
$0.toValue = (angle.degrees)
$0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
}
container?.layer.add(rotation, forKey: "rotation")
}
}
| 95e659b98d18e18768e03b9a210d7a60 | 36.209524 | 111 | 0.582672 | false | false | false | false |
esttorhe/RxSwift | refs/heads/feature/swift2.0 | RxSwift/RxSwift/Observables/Implementations/Filter.swift | mit | 1 | //
// Filter.swift
// Rx
//
// Created by Krunoslav Zaher on 2/17/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class Where_<O : ObserverType>: Sink<O>, ObserverType {
typealias Element = O.Element
typealias Parent = Where<Element>
let parent: Parent
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(event: Event<Element>) {
switch event {
case .Next(let value):
_ = self.parent.predicate(value).recoverWith { e in
trySendError(observer, e)
self.dispose()
return failure(e)
}.flatMap { satisfies -> RxResult<Void> in
if satisfies {
trySend(observer, event)
}
return SuccessResult
}
case .Completed: fallthrough
case .Error:
trySend(observer, event)
self.dispose()
}
}
}
class Where<Element> : Producer<Element> {
typealias Predicate = (Element) -> RxResult<Bool>
let source: Observable<Element>
let predicate: Predicate
init(source: Observable<Element>, predicate: Predicate) {
self.source = source
self.predicate = predicate
}
override func run<O: ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = Where_(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return source.subscribeSafe(sink)
}
} | fbdfefab1a9b48f6828149c1ed72fbb7 | 28.066667 | 145 | 0.55938 | false | false | false | false |
eastsss/SwiftyUtilities | refs/heads/master | Pods/Ogra/Sources/Encodable.swift | mit | 2 | //
// Encodable.swift
// Ogra
//
// Created by Craig Edwards on 27/07/2015.
// Copyright © 2015 Craig Edwards. All rights reserved.
//
import Foundation
import Argo
public protocol Encodable {
func encode() -> JSON
}
extension JSON: Encodable {
public func encode() -> JSON {
return self
}
}
extension String: Encodable {
public func encode() -> JSON {
return .string(self)
}
}
extension Bool: Encodable {
public func encode() -> JSON {
return .bool(self)
}
}
extension Int: Encodable {
public func encode() -> JSON {
return .number(self as NSNumber)
}
}
extension Double: Encodable {
public func encode() -> JSON {
return .number(self as NSNumber)
}
}
extension Float: Encodable {
public func encode() -> JSON {
return .number(self as NSNumber)
}
}
extension UInt: Encodable {
public func encode() -> JSON {
return .number(self as NSNumber)
}
}
extension UInt64: Encodable {
public func encode() -> JSON {
return .number(NSNumber(value: self))
}
}
extension Optional where Wrapped: Encodable {
public func encode() -> JSON {
switch self {
case .none: return .null
case .some(let v): return v.encode()
}
}
}
extension Collection where Self: ExpressibleByDictionaryLiteral, Self.Key: ExpressibleByStringLiteral, Self.Value: Encodable, Iterator.Element == (key: Self.Key, value: Self.Value) {
public func encode() -> JSON {
var values = [String : JSON]()
for (key, value) in self {
values[String(describing: key)] = value.encode()
}
return .object(values)
}
}
extension Optional where Wrapped: Collection & ExpressibleByDictionaryLiteral, Wrapped.Key: ExpressibleByStringLiteral, Wrapped.Value: Encodable, Wrapped.Iterator.Element == (key: Wrapped.Key, value: Wrapped.Value) {
public func encode() -> JSON {
return self.map { $0.encode() } ?? .null
}
}
extension Collection where Self: ExpressibleByArrayLiteral, Self.Element: Encodable, Iterator.Element: Encodable {
public func encode() -> JSON {
return JSON.array(self.map { $0.encode() })
}
}
extension Optional where Wrapped: Collection & ExpressibleByArrayLiteral, Wrapped.Element: Encodable, Wrapped.Iterator.Element == Wrapped.Element {
public func encode() -> JSON {
return self.map { $0.encode() } ?? .null
}
}
extension Encodable where Self: RawRepresentable, Self.RawValue == String {
public func encode() -> JSON {
return .string(self.rawValue)
}
}
extension Encodable where Self: RawRepresentable, Self.RawValue == Int {
public func encode() -> JSON {
return .number(self.rawValue as NSNumber)
}
}
extension Encodable where Self: RawRepresentable, Self.RawValue == Double {
public func encode() -> JSON {
return .number(self.rawValue as NSNumber)
}
}
extension Encodable where Self: RawRepresentable, Self.RawValue == Float {
public func encode() -> JSON {
return .number(self.rawValue as NSNumber)
}
}
extension Encodable where Self: RawRepresentable, Self.RawValue == UInt {
public func encode() -> JSON {
return .number(self.rawValue as NSNumber)
}
}
extension Encodable where Self: RawRepresentable, Self.RawValue == UInt64 {
public func encode() -> JSON {
return .number(NSNumber(value: self.rawValue))
}
}
extension JSON {
public func JSONObject() -> Any {
switch self {
case .null: return NSNull()
case .string(let value): return value
case .number(let value): return value
case .array(let array): return array.map { $0.JSONObject() }
case .bool(let value): return value
case .object(let object):
var dict: [Swift.String : Any] = [:]
for (key, value) in object {
dict[key] = value.JSONObject()
}
return dict as Any
}
}
}
| 0432d3f3e0318f626f57f035bc33990e | 23.503268 | 216 | 0.677247 | false | false | false | false |
fxm90/GradientProgressBar | refs/heads/main | Example/Pods/SnapshotTesting/Sources/SnapshotTesting/Snapshotting/NSBezierPath.swift | mit | 1 | #if os(macOS)
import Cocoa
extension Snapshotting where Value == NSBezierPath, Format == NSImage {
/// A snapshot strategy for comparing bezier paths based on pixel equality.
public static var image: Snapshotting {
return .image()
}
/// A snapshot strategy for comparing bezier paths based on pixel equality.
///
/// - Parameter precision: The percentage of pixels that must match.
public static func image(precision: Float = 1) -> Snapshotting {
return SimplySnapshotting.image(precision: precision).pullback { path in
// Move path info frame:
let bounds = path.bounds
let transform = AffineTransform(translationByX: -bounds.origin.x, byY: -bounds.origin.y)
path.transform(using: transform)
let image = NSImage(size: path.bounds.size)
image.lockFocus()
path.fill()
image.unlockFocus()
return image
}
}
}
extension Snapshotting where Value == NSBezierPath, Format == String {
/// A snapshot strategy for comparing bezier paths based on pixel equality.
@available(iOS 11.0, *)
public static var elementsDescription: Snapshotting {
return .elementsDescription(numberFormatter: defaultNumberFormatter)
}
/// A snapshot strategy for comparing bezier paths based on pixel equality.
///
/// - Parameter numberFormatter: The number formatter used for formatting points.
@available(iOS 11.0, *)
public static func elementsDescription(numberFormatter: NumberFormatter) -> Snapshotting {
let namesByType: [NSBezierPath.ElementType: String] = [
.moveTo: "MoveTo",
.lineTo: "LineTo",
.curveTo: "CurveTo",
.closePath: "Close",
]
let numberOfPointsByType: [NSBezierPath.ElementType: Int] = [
.moveTo: 1,
.lineTo: 1,
.curveTo: 3,
.closePath: 0,
]
return SimplySnapshotting.lines.pullback { path in
var string: String = ""
var elementPoints = [CGPoint](repeating: .zero, count: 3)
for elementIndex in 0..<path.elementCount {
let elementType = path.element(at: elementIndex, associatedPoints: &elementPoints)
let name = namesByType[elementType] ?? "Unknown"
if elementType == .moveTo && !string.isEmpty {
string += "\n"
}
string += name
if let numberOfPoints = numberOfPointsByType[elementType] {
let points = elementPoints[0..<numberOfPoints]
string += " " + points.map { point in
let x = numberFormatter.string(from: point.x as NSNumber)!
let y = numberFormatter.string(from: point.y as NSNumber)!
return "(\(x), \(y))"
}.joined(separator: " ")
}
string += "\n"
}
return string
}
}
}
private let defaultNumberFormatter: NumberFormatter = {
let numberFormatter = NumberFormatter()
numberFormatter.minimumFractionDigits = 1
numberFormatter.maximumFractionDigits = 3
return numberFormatter
}()
#endif
| ba4a782874f2be4e47be8bb80f86ca6c | 30.763441 | 94 | 0.661476 | false | false | false | false |
mcdappdev/Vapor-Template | refs/heads/master | Sources/App/Middleware/RESTMiddleware.swift | mit | 1 | import Vapor
import HTTP
class RESTMiddleware: Middleware {
let config: Config
init(config: Config) {
self.config = config
}
func respond(to request: Request, chainingTo next: Responder) throws -> Response {
let unauthorizedError = Abort(.unauthorized, reason: "Please include an API-KEY")
guard let correctAPIKey = config["app", "API-KEY"]?.string else { throw Abort.badRequest }
guard let submittedAPIKey = request.headers["API-KEY"]?.string else { throw unauthorizedError }
if correctAPIKey == submittedAPIKey {
return try next.respond(to: request)
} else {
throw unauthorizedError
}
}
}
| 533c903e31df1a371b8a3ff326ed1f93 | 30.304348 | 103 | 0.626389 | false | true | false | false |
IAskWind/IAWExtensionTool | refs/heads/master | IAWExtensionTool/IAWExtensionTool/Classes/Common/IAW_WebViewController.swift | mit | 1 | //
// WebViewController.swift
// CtkApp
//
// Created by winston on 16/12/9.
// Copyright © 2016年 winston. All rights reserved.
//
import UIKit
open class IAW_WebViewController: IAW_BaseViewController {
fileprivate var webView = UIWebView()
fileprivate var urlStr: String?
fileprivate let loadProgressAnimationView: LoadProgressAnimationView = LoadProgressAnimationView(bgColor: UIColor.brown,frame: CGRect(x:0, y: 64, width: UIScreen.iawWidth, height: 3))
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
view.addSubview(webView)
webView.snp.makeConstraints{
(make) in
make.edges.equalTo(self.view)
}
webView.addSubview(loadProgressAnimationView)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(urlStr: String) {
self.init(nibName: nil, bundle: nil)
IAW_WebViewTool.webViewLoadUrl(webView: webView, urlStr: urlStr)
self.urlStr = urlStr
}
override open func viewDidLoad() {
super.viewDidLoad()
buildRightItemBarButton()
// view.backgroundColor = UIColor.colorWithCustom(230, g: 230, b: 230)
// webView.backgroundColor = UIColor.colorWithCustom(230, g: 230, b: 230)
webView.delegate = self
// / 自动对页面进行缩放以适应屏幕
webView.scalesPageToFit = true
webView.dataDetectorTypes = .all
webView.scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
fileprivate func buildRightItemBarButton() {
let rightButton = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 44))
rightButton.setImage(IAW_ImgXcassetsTool.v2_refreshWhite.image, for: UIControl.State())
rightButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -53)
rightButton.addTarget(self, action: #selector(IAW_WebViewController.refreshClick), for: UIControl.Event.touchUpInside)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
}
// MARK: - Action
@objc func refreshClick() {
if urlStr != nil && urlStr!.count > 1 {
IAW_WebViewTool.webViewLoadUrl(webView: webView, urlStr: urlStr!)
}
}
}
extension IAW_WebViewController: UIWebViewDelegate {
public func webViewDidStartLoad(_ webView: UIWebView) {
loadProgressAnimationView.startLoadProgressAnimation()
}
public func webViewDidFinishLoad(_ webView: UIWebView) {
loadProgressAnimationView.endLoadProgressAnimation()
IAW_WebViewTool.webViewDealValidateToken(webView: webView)
}
}
| 16d27fa3be40dae07296e20cc47fa7ce | 34.094118 | 187 | 0.660409 | false | false | false | false |
evnaz/Design-Patterns-In-Swift | refs/heads/master | source-cn/behavioral/strategy.swift | gpl-3.0 | 2 | /*:
💡 策略(Strategy)
--------------
对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。策略模式:
* 定义了一族算法(业务规则);
* 封装了每个算法;
* 这族的算法可互换代替(interchangeable)。
### 示例:
*/
struct TestSubject {
let pupilDiameter: Double
let blushResponse: Double
let isOrganic: Bool
}
protocol RealnessTesting: AnyObject {
func testRealness(_ testSubject: TestSubject) -> Bool
}
final class VoightKampffTest: RealnessTesting {
func testRealness(_ testSubject: TestSubject) -> Bool {
return testSubject.pupilDiameter < 30.0 || testSubject.blushResponse == 0.0
}
}
final class GeneticTest: RealnessTesting {
func testRealness(_ testSubject: TestSubject) -> Bool {
return testSubject.isOrganic
}
}
final class BladeRunner {
private let strategy: RealnessTesting
init(test: RealnessTesting) {
self.strategy = test
}
func testIfAndroid(_ testSubject: TestSubject) -> Bool {
return !strategy.testRealness(testSubject)
}
}
/*:
### 用法
*/
let rachel = TestSubject(pupilDiameter: 30.2,
blushResponse: 0.3,
isOrganic: false)
// Deckard is using a traditional test
let deckard = BladeRunner(test: VoightKampffTest())
let isRachelAndroid = deckard.testIfAndroid(rachel)
// Gaff is using a very precise method
let gaff = BladeRunner(test: GeneticTest())
let isDeckardAndroid = gaff.testIfAndroid(rachel)
| 681e433027d2df79fd155516831f7153 | 21.770492 | 83 | 0.678186 | false | true | false | false |
littlelightwang/firefox-ios | refs/heads/master | Storage/Storage/SQL/GenericTable.swift | mpl-2.0 | 2 | /* 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
class GenericTable<T>: Table {
typealias Type = T
// Implementors need override these methods
let debug_enabled = false
var name: String { return "" }
var rows: String { return "" }
var factory: ((row: SDRow) -> Type)? {
return nil
}
// These methods take an inout object to avoid some runtime crashes that seem to be due
// to using generics. Yay Swift!
func getInsertAndArgs(inout item: Type) -> (String, [AnyObject?])? {
return nil
}
func getUpdateAndArgs(inout item: Type) -> (String, [AnyObject?])? {
return nil
}
func getDeleteAndArgs(inout item: Type?) -> (String, [AnyObject?])? {
return nil
}
func getQueryAndArgs(options: QueryOptions?) -> (String, [AnyObject?])? {
return nil
}
// Here's the real implementation
func debug(msg: String) {
if debug_enabled {
println("GenericTable: \(msg)")
}
}
func create(db: SQLiteDBConnection, version: Int) -> Bool {
db.executeChange("CREATE TABLE IF NOT EXISTS \(name) (\(rows))")
return true
}
func updateTable(db: SQLiteDBConnection, from: Int, to: Int) -> Bool {
debug("Update table \(name) from \(from) to \(to)")
return false
}
func insert(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int {
debug("Insert into \(name) \(item)")
if var site = item {
if let (query, args) = getInsertAndArgs(&site) {
if let error = db.executeChange(query, withArgs: args) {
err = error
return -1
}
return db.lastInsertedRowID
}
}
err = NSError(domain: "mozilla.org", code: 0, userInfo: [
NSLocalizedDescriptionKey: "Tried to save something that isn't a site"
])
return -1
}
func update(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int {
if var item = item {
if let (query, args) = getUpdateAndArgs(&item) {
if let error = db.executeChange(query, withArgs: args) {
println(error.description)
err = error
return 0
}
return db.numberOfRowsModified
}
}
err = NSError(domain: "mozilla.org", code: 0, userInfo: [
NSLocalizedDescriptionKey: "Tried to save something that isn't a site"
])
return 0
}
func delete(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int {
debug("Delete from \(name) \(item)")
var numDeleted: Int = 0
if var item: Type? = item {
if let (query, args) = getDeleteAndArgs(&item) {
if let error = db.executeChange(query, withArgs: args) {
println(error.description)
err = error
return 0
}
return db.numberOfRowsModified
}
}
return 0
}
func query(db: SQLiteDBConnection, options: QueryOptions?) -> Cursor {
if var (query, args) = getQueryAndArgs(options) {
if let factory = self.factory {
let c = db.executeQuery(query, factory: factory, withArgs: args)
debug("Insert \(query) \(args) = \(c)")
return c
}
}
return Cursor(status: CursorStatus.Failure, msg: "Invalid query: \(options?.filter)")
}
}
| 387d0103f6f007e67307b8a95d16f3be | 31.101695 | 93 | 0.545143 | false | false | false | false |
roecrew/AudioKit | refs/heads/master | AudioKit/Common/Playgrounds/Analysis.playground/Pages/Tracking Frequency of Audio File.xcplaygroundpage/Contents.swift | mit | 1 | //: ## Tracking Frequency of an Audio File
//: A more real-world example of tracking the pitch of an audio stream
import XCPlayground
import AudioKit
let file = try AKAudioFile(readFileName: "leadloop.wav", baseDir: .Resources)
var player = try AKAudioPlayer(file: file)
player.looping = true
let tracker = AKFrequencyTracker(player)
AudioKit.output = tracker
AudioKit.start()
player.play()
//: User Interface
class PlaygroundView: AKPlaygroundView {
var trackedAmplitudeSlider: AKPropertySlider?
var trackedFrequencySlider: AKPropertySlider?
override func setup() {
AKPlaygroundLoop(every: 0.1) {
self.trackedAmplitudeSlider?.value = tracker.amplitude
self.trackedFrequencySlider?.value = tracker.frequency
}
addTitle("Tracking An Audio File")
trackedAmplitudeSlider = AKPropertySlider(
property: "Tracked Amplitude",
format: "%0.3f",
value: 0, maximum: 0.55,
color: AKColor.greenColor()
) { sliderValue in
// Do nothing, just for display
}
addSubview(trackedAmplitudeSlider!)
trackedFrequencySlider = AKPropertySlider(
property: "Tracked Frequency",
format: "%0.3f",
value: 0, maximum: 1000,
color: AKColor.redColor()
) { sliderValue in
// Do nothing, just for display
}
addSubview(trackedFrequencySlider!)
addSubview(AKRollingOutputPlot.createView())
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
| 18434e4a51d73154ea3aebf687b0bcbb | 27.859649 | 77 | 0.663222 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.