repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PerTerbin/PTCalendarPicker | PTCalendarPicker/PTCalendarPickerView/PTCalendarPickerCollectionViewCell.swift | 1 | 2423 | //
// PTCalendarPickerCollectionViewCell.swift
// WeiShop
//
// Created by apple on 16/9/20.
// Copyright © 2016年 zou. All rights reserved.
//
import UIKit
class PTCalendarPickerCollectionViewCell: UICollectionViewCell {
var dateLabel: UILabel?
var backView: UIView?
var typeLabel: UILabel?
var selectedBackgroundColor: UIColor = UIColor(red: 74/255.0 ,green: 137/255.0 ,blue: 220/255.0, alpha: 1)
var startTitle: String = "起始"
var endTitle: String = "结束"
override init(frame: CGRect) {
super.init(frame: frame)
let backWidth: CGFloat = self.bounds.width > self.bounds.height ? self.bounds.height : self.bounds.width
backView = UIView(frame: CGRectMake((self.bounds.width - backWidth) / 2, (self.bounds.height - backWidth) / 2, backWidth, backWidth))
backView?.backgroundColor = selectedBackgroundColor
backView?.layer.cornerRadius = (backView?.frame.size.height)! / 2
backView?.hidden = true
self.addSubview(backView!)
dateLabel = UILabel(frame: self.bounds)
dateLabel?.textAlignment = .Center
dateLabel?.textColor = UIColor.darkGrayColor()
self.addSubview(dateLabel!)
typeLabel = UILabel(frame: CGRectMake(0, self.bounds.height * 0.4, self.bounds.width, self.bounds.height / 2))
typeLabel?.textColor = UIColor.whiteColor()
typeLabel?.textAlignment = .Center
typeLabel?.font = UIFont.systemFontOfSize(13)
typeLabel?.hidden = true
self.addSubview(typeLabel!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func changeCell() {
dateLabel?.frame = self.bounds
dateLabel?.font = UIFont.systemFontOfSize(17)
typeLabel?.hidden = true
backView?.hidden = true
}
func selectedCell(isStart isStart: Bool) {
dateLabel?.frame = CGRectMake(0, self.bounds.height * 0.05, self.bounds.width, self.bounds.height / 2)
dateLabel?.textColor = UIColor.whiteColor()
dateLabel?.font = UIFont.systemFontOfSize(13)
backView?.hidden = false
typeLabel?.hidden = false
if isStart {
typeLabel?.text = startTitle
}else {
typeLabel?.text = endTitle
}
}
}
| mit | c2f831226b44416bcec4138f39806270 | 32.041096 | 141 | 0.624378 | 4.483271 | false | false | false | false |
lennartkerkvliet/LKStoreButton | LKStoreButton/LKStoreButton.swift | 1 | 8181 | //
// LKStoreButton.swift
// LKStoreButton
//
// Created by Lennart Kerkvliet on 02-08-17.
// Copyright © 2017 Lennart Kerkvliet. All rights reserved.
//
import UIKit
enum LKStoreButtonState {
case normal
case downloading
case confirmed
}
protocol LKStoreButtonDelegate {
func startDownloading(button: LKStoreButton)
func cancelDownloading(button: LKStoreButton)
func openDownload(button: LKStoreButton)
}
@IBDesignable class LKStoreButton: UIControl {
private static let RotationKey: String = "LKStoreButtonRotation"
private var label = UILabel()
private var confirmedLabel = UILabel()
private static let insets = CGSize(width: 20, height: 8)
public var delegate: LKStoreButtonDelegate?
public var buttonState: LKStoreButtonState = .normal {
didSet {
switch buttonState {
case .normal:
normal()
case .downloading:
downloading()
case .confirmed:
confirm()
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
self.backgroundColor = buttonColor
label.text = text
label.font = UIFont.boldSystemFont(ofSize: 12)
label.textColor = self.tintColor
label.translatesAutoresizingMaskIntoConstraints = false
addSubview(label)
addConstraint(NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: label, attribute: .centerX, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: label, attribute: .centerY, multiplier: 1.0, constant: 0))
confirmedLabel.text = confirmText
confirmedLabel.font = UIFont.boldSystemFont(ofSize: 12)
confirmedLabel.textColor = self.tintColor
confirmedLabel.alpha = 0
confirmedLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(confirmedLabel)
addConstraint(NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: confirmedLabel, attribute: .centerX, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: confirmedLabel, attribute: .centerY, multiplier: 1.0, constant: 0))
self.layer.cornerRadius = self.intrinsicContentSize.height / 2
self.layer.borderWidth = 2
self.layer.borderColor = buttonColor.cgColor
self.addTarget(self, action: #selector(LKStoreButton.touchDown), for: .touchDown)
self.addTarget(self, action: #selector(LKStoreButton.touchUpInside), for: .touchUpInside)
self.addTarget(self, action: #selector(LKStoreButton.touchUp), for: .touchUpOutside)
}
override var intrinsicContentSize: CGSize {
if buttonState == .normal {
var size = label.intrinsicContentSize
size.height += LKStoreButton.insets.height
size.width += LKStoreButton.insets.width
return size
} else if buttonState == .confirmed {
var size = confirmedLabel.intrinsicContentSize
size.height += LKStoreButton.insets.height
size.width += LKStoreButton.insets.width
return size
} else {
var size = label.intrinsicContentSize
size.height += LKStoreButton.insets.height
size.width = size.height
return size
}
}
private func removeRotation() {
subviews.filter{ $0 is UIImageView }.forEach { (imageView: UIView) in
imageView.layer.removeAnimation(forKey: LKStoreButton.RotationKey)
imageView.removeFromSuperview()
}
self.layer.borderColor = buttonColor.cgColor
}
private func circleWithCut() -> UIImage? {
let size = self.intrinsicContentSize
UIGraphicsBeginImageContextWithOptions(size, false, 0)
buttonColor.setStroke()
UIGraphicsGetCurrentContext()?.saveGState()
let path = UIBezierPath(ovalIn: CGRect(origin: CGPoint.zero, size: size))
path.lineWidth = 2 * UIScreen.main.scale
path.addClip()
path.stroke()
UIGraphicsGetCurrentContext()?.saveGState()
UIRectFillUsingBlendMode(CGRect(x: size.width - 6, y: size.height / 2 - 2, width: 6, height: 6), .clear)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image?.withRenderingMode(.alwaysOriginal)
}
//# MARK - Touch Events
@objc func touchDown() {
if buttonState == .normal || buttonState == .confirmed {
UIView.animate(withDuration: 0.15) {
self.backgroundColor = self.selectedColor
}
}
}
@objc func touchUpInside() {
if buttonState == .normal {
buttonState = .downloading
} else if buttonState == .downloading {
buttonState = .normal
delegate?.cancelDownloading(button: self)
} else if buttonState == .confirmed {
touchUp()
delegate?.openDownload(button: self)
}
}
@objc func touchUp() {
if buttonState == .normal || buttonState == .confirmed {
UIView.animate(withDuration: 0.15) {
self.backgroundColor = self.buttonColor
}
}
}
//# MARK - State Change Events
private func downloading() {
UIView.animate(withDuration: 0.4, animations: {
self.label.alpha = 0.0
self.invalidateIntrinsicContentSize()
self.superview?.setNeedsLayout()
self.superview?.layoutIfNeeded()
}, completion: { (completion: Bool) in
self.delegate?.startDownloading(button: self)
if let image = self.circleWithCut() {
self.layer.borderColor = UIColor.clear.cgColor
let imageView = UIImageView(image: image)
self.addSubview(imageView)
/* Rotation animation.*/
let rotation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.toValue = Double.pi * 2
rotation.duration = 1
rotation.isCumulative = true
rotation.repeatCount = HUGE
imageView.layer.add(rotation, forKey: LKStoreButton.RotationKey)
}
})
}
private func normal() {
removeRotation()
UIView.animate(withDuration: 0.4, animations: {
self.label.alpha = 1.0
self.confirmedLabel.alpha = 0.0
self.backgroundColor = self.buttonColor
self.invalidateIntrinsicContentSize()
self.superview?.setNeedsLayout()
self.superview?.layoutIfNeeded()
})
}
private func confirm() {
removeRotation()
UIView.animate(withDuration: 0.4, animations: {
self.label.alpha = 0.0
self.confirmedLabel.alpha = 1.0
self.backgroundColor = self.buttonColor
self.invalidateIntrinsicContentSize()
self.superview?.setNeedsLayout()
self.superview?.layoutIfNeeded()
})
}
//# MARK - IBInspectable properties
@IBInspectable public var buttonColor: UIColor = .white {
didSet {
self.backgroundColor = buttonColor
self.layer.borderColor = buttonColor.cgColor
}
}
@IBInspectable public var selectedColor: UIColor = .clear
@IBInspectable public var text: String = "DOWNLOAD" {
didSet { self.label.text = self.text }
}
@IBInspectable public var confirmText: String = "OPEN" {
didSet { self.confirmedLabel.text = self.confirmText }
}
}
| mit | 770509e8f6fe0a1ef8d07696ba218b1f | 33.957265 | 168 | 0.605379 | 5.134965 | false | false | false | false |
Msr-B/FanFan-iOS | WeCenterMobile/Controller/QuestionListViewController.swift | 3 | 5561 | //
// QuestionListViewController.swift
// WeCenterMobile
//
// Created by Darren Liu on 14/11/17.
// Copyright (c) 2014年 ifLab. All rights reserved.
//
import MJRefresh
import UIKit
@objc enum QuestionListType: Int {
case User = 1
}
class QuestionListViewController: UITableViewController {
let user: User
let listType: QuestionListType
var questions = [Question]()
var page = 1
let count = 20
init(user: User) {
self.user = user
listType = .User
super.init(nibName: nil, bundle: nil)
}
required init!(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let cellReuseIdentifier = "QuestionCell"
let cellNibName = "QuestionCell"
override func loadView() {
super.loadView()
title = "\(user.name!) 的提问"
let theme = SettingsManager.defaultManager.currentTheme
view.backgroundColor = theme.backgroundColorA
tableView.indicatorStyle = theme.scrollViewIndicatorStyle
tableView.separatorStyle = .None
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
tableView.registerNib(UINib(nibName: cellNibName, bundle: NSBundle.mainBundle()), forCellReuseIdentifier: cellReuseIdentifier)
tableView.panGestureRecognizer.requireGestureRecognizerToFail(appDelegate.mainViewController.contentViewController.interactivePopGestureRecognizer)
tableView.panGestureRecognizer.requireGestureRecognizerToFail(appDelegate.mainViewController.sidebar.screenEdgePanGestureRecognizer)
tableView.msr_setTouchesShouldCancel(true, inContentViewWhichIsKindOfClass: UIButton.self)
tableView.delaysContentTouches = false
tableView.msr_wrapperView?.delaysContentTouches = false
tableView.wc_addRefreshingHeaderWithTarget(self, action: "refresh")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.mj_header.beginRefreshing()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return questions.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier, forIndexPath: indexPath) as! QuestionCell
cell.update(question: questions[indexPath.row])
cell.userButton.addTarget(self, action: "didPressUserButton:", forControlEvents: .TouchUpInside)
cell.questionButton.addTarget(self, action: "didPressQuestionButton:", forControlEvents: .TouchUpInside)
return cell
}
override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
func didPressUserButton(sender: UIButton) {
if let user = sender.msr_userInfo as? User {
msr_navigationController!.pushViewController(UserViewController(user: user), animated: true)
}
}
func didPressQuestionButton(sender: UIButton) {
if let question = sender.msr_userInfo as? Question {
msr_navigationController!.pushViewController(QuestionViewController(question: question), animated: true)
}
}
var shouldReloadAfterLoadingMore = true
internal func refresh() {
shouldReloadAfterLoadingMore = false
tableView.mj_footer?.endRefreshing()
let success: ([Question]) -> Void = {
[weak self] questions in
if let self_ = self {
self_.page = 1
self_.questions = questions
self_.tableView.mj_header.endRefreshing()
self_.tableView.reloadData()
if self_.tableView.mj_footer == nil {
self_.tableView.wc_addRefreshingFooterWithTarget(self_, action: "loadMore")
}
}
}
let failure: (NSError) -> Void = {
[weak self] error in
self?.tableView.mj_header.endRefreshing()
return
}
switch listType {
case .User:
user.fetchQuestions(page: 1, count: count, success: success, failure: failure)
break
}
}
internal func loadMore() {
if tableView.mj_header.isRefreshing() {
tableView.mj_footer.endRefreshing()
return
}
shouldReloadAfterLoadingMore = true
let success: ([Question]) -> Void = {
[weak self] questions in
if let self_ = self {
if self_.shouldReloadAfterLoadingMore {
++self_.page
self_.questions.appendContentsOf(questions)
self_.tableView.reloadData()
}
}
self?.tableView.mj_footer.endRefreshing()
}
let failure: (NSError) -> Void = {
[weak self] error in
self?.tableView.mj_footer.endRefreshing()
return
}
switch listType {
case .User:
user.fetchQuestions(page: page + 1, count: count, success: success, failure: failure)
break
}
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return SettingsManager.defaultManager.currentTheme.statusBarStyle
}
}
| gpl-2.0 | efc8ec066abf6e91a202c350254a972d | 34.825806 | 155 | 0.640555 | 5.412281 | false | false | false | false |
emilstahl/swift | test/Interpreter/super_constructor.swift | 14 | 1167 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
struct S {
var a, b : Int
init(_ a : Int, _ b : Int) {
self.a = a
self.b = b
}
init(_ x:UnicodeScalar) {
a = 219
b = 912
print("constructed \(x)")
}
}
class C {
var a, b : Int
init(x:UnicodeScalar) {
a = 20721
b = 12702
print("constructed \(x)")
}
}
class D : C {
init() {
super.init(x: "z")
print("...in bed")
}
}
func print(s: S) {
print("S(a=\(s.a), b=\(s.b))")
}
func print(c: C) {
print("C(a=\(c.a), b=\(c.b))")
}
// CHECK: S(a=1, b=2)
print(S(1, 2))
// CHECK: constructed x
// CHECK: S(a=219, b=912)
print(S("x"))
// CHECK: constructed y
// CHECK: C(a=20721, b=12702)
print(C(x: "y"))
// CHECK: constructed z
// CHECK: ...in bed
// CHECK: C(a=20721, b=12702)
print(D())
class BaseWithDummyParameter {
init() {
fatalError("wrong init")
}
init(dummy: ()) {
print("correct")
}
}
class DerivedWithDummyParameter : BaseWithDummyParameter {
override init() {
super.init(dummy: ())
}
}
_ = BaseWithDummyParameter(dummy: ()) // CHECK: correct
_ = DerivedWithDummyParameter() // CHECK: correct
| apache-2.0 | 6dd19a2a570762bc2f18e5796f24283f | 15.208333 | 58 | 0.557841 | 2.707657 | false | false | false | false |
OAuthSwift/OAuthSwift | Sources/OAuth1Swift.swift | 2 | 9659 | //
// OAuth1Swift.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/22/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import Foundation
open class OAuth1Swift: OAuthSwift {
/// If your oauth provider doesn't provide `oauth_verifier`
/// set this value to true (default: false)
open var allowMissingOAuthVerifier: Bool = false
/// Optionally add callback URL to authorize Url (default: false)
open var addCallbackURLToAuthorizeURL: Bool = false
/// Optionally add consumer key to authorize Url (default: false)
open var addConsumerKeyToAuthorizeURL: Bool = false
/// Optionally change the standard `oauth_token` param name of the authorize Url
open var authorizeURLOAuthTokenParam: String = "oauth_token"
/// Optionally change the standard `oauth_consumer_key` param name of the authorize Url
open var authorizeURLConsumerKeyParam: String = "oauth_consumer_key"
/// Encode token using RFC3986
open var useRFC3986ToEncodeToken: Bool = false
var consumerKey: String
var consumerSecret: String
var requestTokenUrl: String
var authorizeUrl: String
var accessTokenUrl: String
// MARK: init
public init(consumerKey: String, consumerSecret: String, requestTokenUrl: URLConvertible, authorizeUrl: URLConvertible, accessTokenUrl: URLConvertible) {
self.consumerKey = consumerKey
self.consumerSecret = consumerSecret
self.requestTokenUrl = requestTokenUrl.string
self.authorizeUrl = authorizeUrl.string
self.accessTokenUrl = accessTokenUrl.string
super.init(consumerKey: consumerKey, consumerSecret: consumerSecret)
self.client.credential.version = .oauth1
}
public convenience override init(consumerKey: String, consumerSecret: String) {
self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, requestTokenUrl: "", authorizeUrl: "", accessTokenUrl: "")
}
public convenience init?(parameters: ConfigParameters) {
guard let consumerKey = parameters["consumerKey"], let consumerSecret = parameters["consumerSecret"],
let requestTokenUrl = parameters["requestTokenUrl"], let authorizeUrl = parameters["authorizeUrl"], let accessTokenUrl = parameters["accessTokenUrl"] else {
return nil
}
self.init(consumerKey: consumerKey, consumerSecret: consumerSecret,
requestTokenUrl: requestTokenUrl,
authorizeUrl: authorizeUrl,
accessTokenUrl: accessTokenUrl)
}
open var parameters: ConfigParameters {
return [
"consumerKey": consumerKey,
"consumerSecret": consumerSecret,
"requestTokenUrl": requestTokenUrl,
"authorizeUrl": authorizeUrl,
"accessTokenUrl": accessTokenUrl
]
}
// MARK: functions
// 0. Start
@discardableResult
open func authorize(withCallbackURL url: URLConvertible, headers: OAuthSwift.Headers? = nil, completionHandler completion: @escaping TokenCompletionHandler) -> OAuthSwiftRequestHandle? {
guard let callbackURL = url.url else {
completion(.failure(.encodingError(urlString: url.string)))
return nil
}
let completionHandler: TokenCompletionHandler = { [unowned self] result in
switch result {
case .success(let (credential, _, _)):
self.observeCallback { [weak self] url in
guard let this = self else { OAuthSwift.retainError(completion); return }
var responseParameters = [String: String]()
if let query = url.query {
responseParameters += query.parametersFromQueryString
}
if let fragment = url.fragment, !fragment.isEmpty {
responseParameters += fragment.parametersFromQueryString
}
if let token = responseParameters["token"] {
responseParameters["oauth_token"] = token
}
if let token = responseParameters["oauth_token"], !token.isEmpty {
this.client.credential.oauthToken = token.safeStringByRemovingPercentEncoding
if let oauth_verifier = responseParameters["oauth_verifier"] {
this.client.credential.oauthVerifier = oauth_verifier.safeStringByRemovingPercentEncoding
} else {
if !this.allowMissingOAuthVerifier {
completion(.failure(.configurationError(message: "Missing oauth_verifier. Maybe use allowMissingOAuthVerifier=true")))
return
}
}
this.postOAuthAccessTokenWithRequestToken(headers: headers, completionHandler: completion)
} else {
completion(.failure(.missingToken))
return
}
}
// 2. Authorize
if let token = self.encode(token: credential.oauthToken) {
var urlString = self.authorizeUrl + (self.authorizeUrl.contains("?") ? "&" : "?")
urlString += "\(self.authorizeURLOAuthTokenParam)=\(token)"
if self.addConsumerKeyToAuthorizeURL {
urlString += "&\(self.authorizeURLConsumerKeyParam)=\(self.consumerKey)"
}
if self.addCallbackURLToAuthorizeURL {
urlString += "&oauth_callback=\(callbackURL.absoluteString)"
}
if let queryURL = URL(string: urlString) {
self.authorizeURLHandler.handle(queryURL)
} else {
completion(.failure(.encodingError(urlString: urlString)))
}
} else {
completion(.failure(.encodingError(urlString: credential.oauthToken))) // TODO specific error
}
case .failure(let error):
completion(.failure(error))
}
}
self.postOAuthRequestToken(callbackURL: callbackURL, headers: headers, completionHandler: completionHandler)
return self
}
private func encode(token: String) -> String? {
if useRFC3986ToEncodeToken {
return token.urlEncoded
}
return token.urlQueryEncoded
}
// 1. Request token
func postOAuthRequestToken(callbackURL: URL, headers: OAuthSwift.Headers? = nil, completionHandler completion: @escaping TokenCompletionHandler) {
var parameters = [String: Any]()
parameters["oauth_callback"] = callbackURL.absoluteString
let completionHandler: OAuthSwiftHTTPRequest.CompletionHandler = { [weak self] result in
guard let this = self else { OAuthSwift.retainError(completion); return }
switch result {
case .success(let response):
let parameters = response.string?.parametersFromQueryString ?? [:]
if let oauthToken = parameters["oauth_token"] {
this.client.credential.oauthToken = oauthToken.safeStringByRemovingPercentEncoding
}
if let oauthTokenSecret=parameters["oauth_token_secret"] {
this.client.credential.oauthTokenSecret = oauthTokenSecret.safeStringByRemovingPercentEncoding
}
completion(.success((this.client.credential, response, parameters)))
case .failure(let error):
completion(.failure(error))
}
}
if let handle = self.client.post(
self.requestTokenUrl, parameters: parameters, headers: headers,
completionHandler: completionHandler) {
self.putHandle(handle, withKey: UUID().uuidString)
}
}
// 3. Get Access token
func postOAuthAccessTokenWithRequestToken(headers: OAuthSwift.Headers? = nil, completionHandler completion: @escaping TokenCompletionHandler) {
var parameters = [String: Any]()
parameters["oauth_token"] = self.client.credential.oauthToken
if !self.allowMissingOAuthVerifier {
parameters["oauth_verifier"] = self.client.credential.oauthVerifier
}
let completionHandler: OAuthSwiftHTTPRequest.CompletionHandler = { [weak self] result in
guard let this = self else { OAuthSwift.retainError(completion); return }
switch result {
case .success(let response):
let parameters = response.string?.parametersFromQueryString ?? [:]
if let oauthToken = parameters["oauth_token"] {
this.client.credential.oauthToken = oauthToken.safeStringByRemovingPercentEncoding
}
if let oauthTokenSecret = parameters["oauth_token_secret"] {
this.client.credential.oauthTokenSecret = oauthTokenSecret.safeStringByRemovingPercentEncoding
}
completion(.success((this.client.credential, response, parameters)))
case .failure(let error):
completion(.failure(error))
}
}
if let handle = self.client.post(
self.accessTokenUrl, parameters: parameters, headers: headers,
completionHandler: completionHandler) {
self.putHandle(handle, withKey: UUID().uuidString)
}
}
}
| mit | 945aec333d0016121b33231345f5222c | 44.777251 | 190 | 0.612486 | 5.914881 | false | false | false | false |
mapsme/omim | iphone/Maps/Core/Theme/Renderers/UITextViewRenderer.swift | 5 | 817 | extension UITextView {
@objc override func applyTheme() {
for style in StyleManager.shared.getStyle(styleName)
where !style.isEmpty && !style.hasExclusion(view: self) {
UITextViewRenderer.render(self, style: style)
}
}
}
class UITextViewRenderer {
class func render(_ control: UITextView, style: Style) {
if let backgroundColor = style.backgroundColor {
control.backgroundColor = backgroundColor
}
if let font = style.font {
control.font = font
}
if let fontColor = style.fontColor {
control.textColor = fontColor
}
if let textContainerInset = style.textContainerInset {
control.textContainerInset = textContainerInset
}
if let linkAttributes = style.linkAttributes {
control.linkTextAttributes = linkAttributes
}
}
}
| apache-2.0 | 96071471fb0bafd7115fc97795690579 | 28.178571 | 63 | 0.69033 | 4.695402 | false | false | false | false |
blockstack/blockstack-portal | native/macos/Blockstack/Pods/Swifter/Sources/String+Misc.swift | 7 | 741 | //
// String+Misc.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
import Foundation
extension String {
public func unquote() -> String {
var scalars = self.unicodeScalars;
if scalars.first == "\"" && scalars.last == "\"" && scalars.count >= 2 {
scalars.removeFirst();
scalars.removeLast();
return String(scalars)
}
return self
}
}
extension UnicodeScalar {
public func asWhitespace() -> UInt8? {
if self.value >= 9 && self.value <= 13 {
return UInt8(self.value)
}
if self.value == 32 {
return UInt8(self.value)
}
return nil
}
}
| mpl-2.0 | 36dd1b3e708d10337657ef1a7226b60e | 19.555556 | 80 | 0.528378 | 4.252874 | false | false | false | false |
aijaz/icw1502 | playgrounds/Week07.playground/Pages/Protocols.xcplaygroundpage/Sources/Vertex.swift | 1 | 821 | import Foundation
public struct Vertex{
var x: Double
let y: Double
public func whatAmI() {
print("I am a vertex")
}
// public func moveByX(deltaX: Double) -> Vertex {
// return Vertex(x: x+deltaX, y: y)
//
// }
public init (x: Double, y: Double) {
self.x = x
self.y = y
}
}
extension Vertex : Movable {
public var location: Vertex {
return self
}
public func moveByX(deltaX: Double) -> Vertex {
return Vertex(x: x+deltaX, y: y)
}
}
extension Vertex : CustomStringConvertible {
public var description: String {
return "(\(x), \(y))"
}
}
extension Vertex : Equatable {}
public func ==(lhs: Vertex, rhs: Vertex) -> Bool {
return (lhs.x == rhs.x && lhs.y == rhs.y)
}
| mit | f24655cf25383c58cef23ffca97c716b | 15.755102 | 53 | 0.53715 | 3.648889 | false | false | false | false |
Burning-Man-Earth/iBurn-iOS | iBurn/BRCImageColors.swift | 1 | 6878 | //
// Colors.swift
// iBurn
//
// Created by Chris Ballinger on 7/15/18.
// Copyright © 2018 Burning Man Earth. All rights reserved.
//
import Foundation
extension UIColor {
public convenience init(hex: UInt32, alpha: CGFloat = 1.0) {
let r = CGFloat((hex & 0xFF0000) >> 16)
let g = CGFloat((hex & 0xFF00) >> 8)
let b = CGFloat(hex & 0xFF)
self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: alpha)
}
}
extension BRCImageColors {
static let adult = BRCImageColors(backgroundColor: UIColor(hex: 0x222222),
primaryColor: UIColor(hex: 0xD92F2F),
secondaryColor: UIColor(hex: 0xE17C84),
detailColor: UIColor(hex: 0xEAC8C8))
static let party2 = BRCImageColors(backgroundColor: UIColor(hex: 0x101034),
primaryColor: UIColor(hex: 0x3957CE),
secondaryColor: UIColor(hex: 0x59A0EF),
detailColor: UIColor(hex: 0xCECCF2))
static let food = BRCImageColors(backgroundColor: UIColor(hex: 0xD40404),
primaryColor: UIColor(hex: 0xFBC92C),
secondaryColor: UIColor(hex: 0xFBF9F9),
detailColor: UIColor(hex: 0xFBF9F9))
static let ceremony = BRCImageColors(backgroundColor: UIColor(hex: 0xCDCCD2),
primaryColor: UIColor(hex: 0x43492C),
secondaryColor: UIColor(hex: 0xFBF9F9),
detailColor: UIColor(hex: 0xFBF9F9))
static let fire = BRCImageColors(backgroundColor: UIColor(hex: 0xFBBB0C),
primaryColor: UIColor(hex: 0x740C04),
secondaryColor: UIColor(hex: 0xA61B04),
detailColor: UIColor(hex: 0xD33204))
static let party = BRCImageColors(backgroundColor: UIColor(hex: 0xE9D8F6),
primaryColor: UIColor(hex: 0x34C4DA),
secondaryColor: UIColor(hex: 0xB7329F),
detailColor: UIColor(hex: 0x8D4A60))
static let kid = BRCImageColors(backgroundColor: UIColor(hex: 0xFDE74C),
primaryColor: UIColor(hex: 0xC3423F),
secondaryColor: UIColor(hex: 0x9BC53D),
detailColor: UIColor(hex: 0x5BC0EB))
static let game = BRCImageColors(backgroundColor: UIColor(hex: 0xF0F8EA),
primaryColor: UIColor(hex: 0xE4572E),
secondaryColor: UIColor(hex: 0xF52F57),
detailColor: UIColor(hex: 0xA8C686))
static let parade = BRCImageColors(backgroundColor: UIColor(hex: 0x8D6A9F),
primaryColor: UIColor(hex: 0xBB342F),
secondaryColor: UIColor(hex: 0xDDA448),
detailColor: UIColor(hex: 0x8CBCB9))
static let support = BRCImageColors(backgroundColor: UIColor(hex: 0x50A2A7),
primaryColor: UIColor(hex: 0xBB0A21),
secondaryColor: UIColor(hex: 0xE9B44C),
detailColor: UIColor(hex: 0xE4D6A7))
static let performance = BRCImageColors(backgroundColor: UIColor(hex: 0xFEFFED),
primaryColor: UIColor(hex: 0xC55F53),
secondaryColor: UIColor(hex: 0x489B9B),
detailColor: UIColor(hex: 0x392232))
static let workshop = BRCImageColors(backgroundColor: UIColor(hex: 0x5F0F40),
primaryColor: UIColor(hex: 0xFB8B24),
secondaryColor: UIColor(hex: 0xE36414),
detailColor: UIColor(hex: 0xBB0A21))
static let plain = BRCImageColors(backgroundColor: .white,
primaryColor: .darkText,
secondaryColor: .darkText,
detailColor: .lightGray)
static let plainDark = BRCImageColors(backgroundColor: .black,
primaryColor: .white,
secondaryColor: .white,
detailColor: .white)
static let light = BRCImageColors(backgroundColor: .white,
primaryColor: UIColor(hex: 0xdb8700),
secondaryColor: .darkText,
detailColor: .lightGray)
static let dark = BRCImageColors(backgroundColor: UIColor(hex: 0x202020),
primaryColor: UIColor(hex: 0xdb8700),
secondaryColor: .white,
detailColor: .lightGray)
@objc public static func colors(for eventType: BRCEventType) -> BRCImageColors {
guard Appearance.contrast == .colorful else {
switch Appearance.theme {
case .light:
return plain
case .dark:
return plainDark
}
}
switch eventType {
case .adult:
return adult
case .ceremony:
return ceremony
case .fire:
return fire
case .food:
return food
case .game:
return game
case .kid:
return kid
case .none, .unknown:
break
case .parade:
return parade
case .party:
return party
case .performance:
return performance
case .support:
return support
case .workshop:
return workshop
@unknown default:
return plain
}
return plain
}
}
extension BRCEventObjectTableViewCell {
public override func setColorTheme(_ colors: BRCImageColors, animated: Bool) {
backgroundColor = colors.backgroundColor
descriptionLabel.textColor = colors.secondaryColor
titleLabel.textColor = colors.primaryColor
hostLabel?.textColor = colors.detailColor
eventTypeLabel.textColor = colors.primaryColor
locationLabel.textColor = colors.detailColor
subtitleLabel.textColor = colors.detailColor
rightSubtitleLabel.textColor = colors.detailColor
}
}
| mpl-2.0 | 9a4973baa26b255be43976eb94534ab8 | 47.090909 | 84 | 0.506762 | 5.201967 | false | false | false | false |
rob5408/UNLEDTableDriver | TableDriver/TableDriver.swift | 2 | 7233 | //
// TableDriver.swift
// OSSM
//
// Created by Robert Johnson on 11/15/14.
// Copyright (c) 2014 Unled, LLC. All rights reserved.
//
import UIKit
//// If the Section containing this Row has an object in it's `rows` property at the same index as this Row, it will be passed via the object parameter
//typedef CGFloat (^UNLEDTableDriverHeightForRowAtIndexPath)(UITableView *tableView, NSIndexPath *indexPath, id object);
//public typealias TableDriverConfigCellForRowAtIndexPath = (tableView: UITableView, indexPath: NSIndexPath, object: Any?) -> UITableViewCell
public typealias TableDriverCellForRowAtIndexPath = (tableView: UITableView, indexPath: NSIndexPath, object: Any?) -> UITableViewCell
public typealias TableDriverDidSelectRowAtIndexPath = (tableView: UITableView, indexPath: NSIndexPath, object: Any?) -> Void
// Inheriting from NSObject to get around implementing NSObjectProtocol
public class TableDriver: NSObject, UITableViewDataSource, UITableViewDelegate {
var tableView: UITableView?
var scrollViewDelegate: UIScrollViewDelegate?
public var sections = Array<Section>()
public init(tableView: UITableView?) {
self.tableView = tableView
super.init()
self.tableView?.dataSource = self
self.tableView?.delegate = self
}
// MARK: UITableViewDataSource
public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.sections.count
}
public func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sections[section].title
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.sections[section].staticRowCount != 0) {
return self.sections[section].staticRowCount
} else {
return self.sections[section].rows.count
}
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (self.sections[indexPath.section].staticRowCount != 0) {
let row: Any = self.sections[indexPath.section].rows[0]
return (row as! Row).cellForRowAtIndexPath!(tableView: tableView, indexPath: indexPath, object: nil)
} else {
let row: Any = self.sections[indexPath.section].rows[indexPath.row]
if let row = row as? Row {
return row.cellForRowAtIndexPath!(tableView: tableView, indexPath: indexPath, object: nil)
} else if let row = row as? RowNameable {
let section = self.sections[indexPath.section]
if let rowCandidate = section.rowTypeRegistry[row.rowName()] {
return rowCandidate.cellForRowAtIndexPath!(tableView: tableView, indexPath: indexPath, object: row)
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("BasicCell", forIndexPath: indexPath)
cell.textLabel?.text = "..."
return cell
}
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("BasicCell", forIndexPath: indexPath)
cell.textLabel?.text = "..."
return cell
}
}
}
// MARK: UITableViewDelegate
public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if (tableView.rowHeight == UITableViewAutomaticDimension) {
return UITableViewAutomaticDimension
} else {
let row: Any = {
if (self.sections[indexPath.section].staticRowCount != 0) {
return self.sections[indexPath.section].rows[0]
} else {
return self.sections[indexPath.section].rows[indexPath.row]
}
}()
//let row: AnyObject = self.sections[indexPath.section].rows[indexPath.row]
if let row = row as? Row {
return row.height
} else {
return 44.0
}
}
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if (self.sections[indexPath.section].staticRowCount != 0) {
// check to make sure there are rows
if let row = self.sections[indexPath.section].rows[0] as? Row where row.didSelectRowAtIndexPath != nil {
row.didSelectRowAtIndexPath!(tableView: tableView, indexPath: indexPath, object: nil)
}
} else {
let row: Any = self.sections[indexPath.section].rows[indexPath.row]
if let row = row as? Row where row.didSelectRowAtIndexPath != nil {
// if ((row is Row) && ((row as! Row).didSelectRowAtIndexPath) != nil) {
row.didSelectRowAtIndexPath!(tableView: tableView, indexPath: indexPath, object: nil)
} else if let row = row as? RowNameable {
let section = self.sections[indexPath.section]
if let rowCandidate = section.rowTypeRegistry[row.rowName()] {
if (((rowCandidate as Row).didSelectRowAtIndexPath) != nil) {
(rowCandidate as Row).didSelectRowAtIndexPath!(tableView: tableView, indexPath: indexPath, object: row)
}
}
}
}
}
public func scrollViewDidScroll(scrollView: UIScrollView) {
self.scrollViewDelegate?.scrollViewDidScroll?(scrollView)
}
}
// MARK: - Section
public class Section {
private var rowTypeRegistry = [String:Row]()
public var title: String? = nil
private var staticRowCount = 0
public var rows = Array<Any>()
public init() {
}
public func registerRow(row: Row, forClassName className: String) {
self.rowTypeRegistry[className] = row
}
}
// MARK: - Row
public class Row {
// public var configCellForRowAtIndexPath: TableDriverConfigCellForRowAtIndexPath = { (tableView: UITableView, indexPath: NSIndexPath, object: Any?) -> UITableViewCell in
// var tableViewCell = tableView.dequeueReusableCellWithIdentifier(UITableViewCell.defaultReuseIdentifier)
// if (tableViewCell == nil) {
// tableViewCell = UITableViewCell(style: .Default, reuseIdentifier: UITableViewCell.defaultReuseIdentifier)
// }
//
// return tableViewCell!
// }
public var cellForRowAtIndexPath: TableDriverCellForRowAtIndexPath? = nil
public var didSelectRowAtIndexPath: TableDriverDidSelectRowAtIndexPath? = nil
var height: CGFloat = 44.0
public init() {
}
}
// MARK: - RowNameable
// TODO: See if there's a generics approach
public protocol RowNameable {
func rowName() -> String
}
// MARK: - RowDescribable
public protocol RowDescription {
func rowDescription() -> String
}
private extension UITableViewCell {
class var defaultReuseIdentifier: String { get { return "UITableViewCell" }}
}
| mit | 4bc1087835a74fe9b70e851ccee5e61e | 36.283505 | 173 | 0.630859 | 5.207343 | false | false | false | false |
te-th/xID3 | Source/AttachedPictureFrame.swift | 1 | 2702 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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
/// Represents the attached Picture, APIC frame
public struct AttachedPictureFrame : ID3Frame {
public let mimetype: String?
public let type: UInt8?
public let desc: String?
public let imageData: [UInt8]
init(mimetype: String?, type: UInt8?, description: String?, imageData: [UInt8]) {
self.mimetype = mimetype
self.type = type
self.desc = description
self.imageData = imageData
}
}
/// Implements the Attached Picture Frame APIC regarding this spec.
/// <Header for 'Attached picture', ID: "APIC">
/// Text encoding $xx
/// MIME type <text string> $00
/// Picture type $xx
/// Description <text string according to encoding> $00 (00)
/// Picture data <binary data>
final class AttachedPictureProcessor : FrameProcessor {
func from(_ id3tagFrame: ID3TagFrame) -> ID3Frame? {
var content = ArraySlice(id3tagFrame.content)
let encoding = ID3Utils.encodingFrom(content.popFirst()!)
var mimetypeBuffer = [UInt8]()
while content.first != nil && content.first! != ID3Utils.zeroByte {
mimetypeBuffer.append(content.popFirst()!)
}
let mimetype = String(bytes: mimetypeBuffer, encoding: String.Encoding.utf8)
content = content.dropFirst()
let pictureType = content.popFirst()
var descriptionBuffer = [UInt8]()
while content.first != nil && content.first! != ID3Utils.zeroByte {
descriptionBuffer.append(content.popFirst()!)
}
let description = String(bytes: descriptionBuffer, encoding: encoding)
var pictureBuffer = [UInt8]()
content.forEach({pictureBuffer.append($0)})
return AttachedPictureFrame(mimetype: mimetype, type: pictureType, description: description, imageData: pictureBuffer)
}
func supports(_ frameId: String) -> Bool {
return "APIC" == frameId
}
}
| apache-2.0 | 71d124d0669b5c419de00a8345e42fff | 33.202532 | 126 | 0.69208 | 4.358065 | false | false | false | false |
xwu/swift | test/stdlib/Error.swift | 1 | 6856 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -o %t/Error -DPTR_SIZE_%target-ptrsize -module-name main %/s
// RUN: %target-codesign %t/Error
// RUN: %target-run %t/Error
// REQUIRES: executable_test
// REQUIRES: reflection
import StdlibUnittest
func shouldCheckErrorLocation() -> Bool {
// Location information for runtime traps is only emitted in debug builds.
guard _isDebugAssertConfiguration() else { return false }
// The runtime error location format changed after the 5.3 release.
// (https://github.com/apple/swift/pull/34665)
if #available(macOS 11.3, iOS 14.5, tvOS 14.5, watchOS 7.4, *) {
return true
} else {
return false
}
}
var ErrorTests = TestSuite("Error")
var NoisyErrorLifeCount = 0
var NoisyErrorDeathCount = 0
protocol OtherProtocol {
var otherProperty: String { get }
}
protocol OtherClassProtocol : AnyObject {
var otherClassProperty: String { get }
}
class NoisyError : Error, OtherProtocol, OtherClassProtocol {
init() { NoisyErrorLifeCount += 1 }
deinit { NoisyErrorDeathCount += 1 }
let _domain = "NoisyError"
let _code = 123
let otherProperty = "otherProperty"
let otherClassProperty = "otherClassProperty"
}
ErrorTests.test("erasure") {
NoisyErrorLifeCount = 0
NoisyErrorDeathCount = 0
do {
let e: Error = NoisyError()
expectEqual(e._domain, "NoisyError")
expectEqual(e._code, 123)
}
expectEqual(NoisyErrorDeathCount, NoisyErrorLifeCount)
}
ErrorTests.test("reflection") {
NoisyErrorLifeCount = 0
NoisyErrorDeathCount = 0
do {
let ne = NoisyError()
let e: Error = ne
var neDump = "", eDump = ""
dump(ne, to: &neDump)
dump(e, to: &eDump)
expectEqual(eDump, neDump)
}
expectEqual(NoisyErrorDeathCount, NoisyErrorLifeCount)
}
ErrorTests.test("dynamic casts") {
NoisyErrorLifeCount = 0
NoisyErrorDeathCount = 0
do {
let ne = NoisyError()
let e: Error = ne
expectTrue(e as! NoisyError === ne)
expectEqual((e as! OtherClassProtocol).otherClassProperty, "otherClassProperty")
expectEqual((e as! OtherProtocol).otherProperty, "otherProperty")
let op: OtherProtocol = ne
expectEqual((op as! Error)._domain, "NoisyError")
expectEqual((op as! Error)._code, 123)
let ocp: OtherClassProtocol = ne
expectEqual((ocp as! Error)._domain, "NoisyError")
expectEqual((ocp as! Error)._code, 123)
// Do the same with rvalues, so we exercise the
// take-on-success/destroy-on-failure paths.
expectEqual(((NoisyError() as Error) as! NoisyError)._domain, "NoisyError")
expectEqual(((NoisyError() as Error) as! OtherClassProtocol).otherClassProperty, "otherClassProperty")
expectEqual(((NoisyError() as Error) as! OtherProtocol).otherProperty, "otherProperty")
expectEqual(((NoisyError() as OtherProtocol) as! Error)._domain, "NoisyError")
expectEqual(((NoisyError() as OtherProtocol) as! Error)._code, 123)
expectEqual(((NoisyError() as OtherClassProtocol) as! Error)._domain, "NoisyError")
expectEqual(((NoisyError() as OtherClassProtocol) as! Error)._code, 123)
}
expectEqual(NoisyErrorDeathCount, NoisyErrorLifeCount)
}
struct DefaultStruct : Error { }
class DefaultClass : Error { }
ErrorTests.test("default domain and code") {
expectEqual(DefaultStruct()._domain, "main.DefaultStruct")
expectEqual(DefaultStruct()._code, 1)
expectEqual(DefaultClass()._domain, "main.DefaultClass")
expectEqual(DefaultClass()._code, 1)
}
enum SillyError: Error { case JazzHands }
ErrorTests.test("try!")
.skip(.custom({ _isFastAssertConfiguration() },
reason: "trap is not guaranteed to happen in -Ounchecked"))
.crashOutputMatches(shouldCheckErrorLocation()
? "'try!' expression unexpectedly raised an error: "
+ "main.SillyError.JazzHands"
: "")
.code {
expectCrashLater()
let _: () = try! { throw SillyError.JazzHands }()
}
ErrorTests.test("try!/location")
.skip(.custom({ _isFastAssertConfiguration() },
reason: "trap is not guaranteed to happen in -Ounchecked"))
.crashOutputMatches(shouldCheckErrorLocation()
? "main/Error.swift:140"
: "")
.code {
expectCrashLater()
let _: () = try! { throw SillyError.JazzHands }()
}
ErrorTests.test("try?") {
var value = try? { () throws -> Int in return 1 }()
expectType(Optional<Int>.self, &value)
expectEqual(Optional(1), value)
expectNil(try? { () throws -> Int in throw SillyError.JazzHands }())
}
enum LifetimeError : Error {
case MistakeOfALifetime(LifetimeTracked, yearsIncarcerated: Int)
}
ErrorTests.test("existential in lvalue") {
expectEqual(0, LifetimeTracked.instances)
do {
var e: Error?
do {
throw LifetimeError.MistakeOfALifetime(LifetimeTracked(0),
yearsIncarcerated: 25)
} catch {
e = error
}
expectEqual(1, LifetimeTracked.instances)
expectEqual(0, e?._code)
}
expectEqual(0, LifetimeTracked.instances)
}
enum UnsignedError: UInt, Error {
#if PTR_SIZE_64
case negativeOne = 0xFFFFFFFFFFFFFFFF
#elseif PTR_SIZE_32
case negativeOne = 0xFFFFFFFF
#else
#error ("Unknown pointer size")
#endif
}
ErrorTests.test("unsigned raw value") {
let negOne: Error = UnsignedError.negativeOne
expectEqual(-1, negOne._code)
}
ErrorTests.test("test dealloc empty error box") {
struct Foo<T>: Error { let value: T }
func makeFoo<T>() throws -> Foo<T> {
throw Foo(value: "makeFoo throw error")
}
func makeError<T>(of: T.Type) throws -> Error {
return try makeFoo() as Foo<T>
}
do {
_ = try makeError(of: Int.self)
} catch let foo as Foo<String> {
expectEqual(foo.value, "makeFoo throw error")
} catch {
expectUnreachableCatch(error)
}
}
var errors: [Error] = []
@inline(never)
func throwNegativeOne() throws {
throw UnsignedError.negativeOne
}
@inline(never)
func throwJazzHands() throws {
throw SillyError.JazzHands
}
ErrorTests.test("willThrow") {
if #available(macOS 10.15.4, iOS 13.4, watchOS 6.2, tvOS 13.4, *) {
// Error isn't allowed in a @convention(c) function when ObjC interop is
// not available, so pass it through an OpaquePointer.
typealias WillThrow = @convention(c) (OpaquePointer) -> Void
let willThrow = pointerToSwiftCoreSymbol(name: "_swift_willThrow")!
let callback: WillThrow = {
errors.append(unsafeBitCast($0, to: Error.self))
}
willThrow.storeBytes(of: callback, as: WillThrow.self)
expectTrue(errors.isEmpty)
do {
try throwNegativeOne()
} catch {}
expectEqual(UnsignedError.self, type(of: errors.last!))
do {
try throwJazzHands()
} catch {}
expectEqual(2, errors.count)
expectEqual(SillyError.self, type(of: errors.last!))
}
}
runAllTests()
| apache-2.0 | d1a4f69b4eaa33ebac8ae6435042ba58 | 27.098361 | 106 | 0.674446 | 3.995338 | false | true | false | false |
xwu/swift | test/attr/attr_availability.swift | 1 | 81107 | // RUN: %target-typecheck-verify-swift
@available(*, unavailable)
func unavailable_func() {}
@available(*, unavailable, message: "message")
func unavailable_func_with_message() {}
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(iOS, unavailable)
@available(OSX, unavailable)
func unavailable_multiple_platforms() {}
@available // expected-error {{expected '(' in 'available' attribute}}
func noArgs() {}
@available(*) // expected-error {{expected ',' in 'available' attribute}}
func noKind() {}
@available(badPlatform, unavailable) // expected-warning {{unknown platform 'badPlatform' for attribute 'available'}}
func unavailable_bad_platform() {}
// Handle unknown platform.
@available(HAL9000, unavailable) // expected-warning {{unknown platform 'HAL9000'}}
func availabilityUnknownPlatform() {}
// <rdar://problem/17669805> Availability can't appear on a typealias
@available(*, unavailable, message: "oh no you don't")
typealias int = Int // expected-note {{'int' has been explicitly marked unavailable here}}
@available(*, unavailable, renamed: "Float")
typealias float = Float // expected-note {{'float' has been explicitly marked unavailable here}}
protocol MyNewerProtocol {}
@available(*, unavailable, renamed: "MyNewerProtocol")
protocol MyOlderProtocol {} // expected-note {{'MyOlderProtocol' has been explicitly marked unavailable here}}
extension Int: MyOlderProtocol {} // expected-error {{'MyOlderProtocol' has been renamed to 'MyNewerProtocol'}}
struct MyCollection<Element> {
@available(*, unavailable, renamed: "Element")
typealias T = Element // expected-note 2{{'T' has been explicitly marked unavailable here}}
func foo(x: T) { } // expected-error {{'T' has been renamed to 'Element'}} {{15-16=Element}}
}
extension MyCollection {
func append(element: T) { } // expected-error {{'T' has been renamed to 'Element'}} {{24-25=Element}}
}
@available(*, unavailable, renamed: "MyCollection")
typealias YourCollection<Element> = MyCollection<Element> // expected-note {{'YourCollection' has been explicitly marked unavailable here}}
var x : YourCollection<Int> // expected-error {{'YourCollection' has been renamed to 'MyCollection'}}{{9-23=MyCollection}}
var y : int // expected-error {{'int' is unavailable: oh no you don't}}
var z : float // expected-error {{'float' has been renamed to 'Float'}}{{9-14=Float}}
// Encoded message
@available(*, unavailable, message: "This message has a double quote \"")
func unavailableWithDoubleQuoteInMessage() {} // expected-note {{'unavailableWithDoubleQuoteInMessage()' has been explicitly marked unavailable here}}
func useWithEscapedMessage() {
unavailableWithDoubleQuoteInMessage() // expected-error {{'unavailableWithDoubleQuoteInMessage()' is unavailable: This message has a double quote \"}}
}
// More complicated parsing.
@available(OSX, message: "x", unavailable)
let _: Int
@available(OSX, introduced: 1, deprecated: 2.0, obsoleted: 3.0.0)
let _: Int
@available(OSX, introduced: 1.0.0, deprecated: 2.0, obsoleted: 3, unavailable, renamed: "x")
let _: Int
// Meaningless but accepted.
@available(OSX, message: "x")
let _: Int
// Parse errors.
@available() // expected-error{{expected platform name or '*' for 'available' attribute}}
let _: Int
@available(OSX,) // expected-error{{expected 'available' option such as 'unavailable', 'introduced', 'deprecated', 'obsoleted', 'message', or 'renamed'}}
let _: Int
@available(OSX, message) // expected-error{{expected ':' after 'message' in 'available' attribute}}
let _: Int
@available(OSX, message: ) // expected-error{{expected string literal in 'available' attribute}}
let _: Int
@available(OSX, message: x) // expected-error{{expected string literal in 'available' attribute}}
let _: Int
@available(OSX, unavailable:) // expected-error{{expected ')' in 'available' attribute}} expected-error{{expected declaration}}
let _: Int
@available(OSX, introduced) // expected-error{{expected ':' after 'introduced' in 'available' attribute}}
let _: Int
@available(OSX, introduced: ) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: x) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: 1.x) // expected-error{{expected ')' in 'available' attribute}} expected-error {{expected declaration}}
let _: Int
@available(OSX, introduced: 1.0.x) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: 0x1) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: 1.0e4) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: -1) // expected-error{{expected version number in 'available' attribute}} expected-error{{expected declaration}}
let _: Int
@available(OSX, introduced: 1.0.1e4) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: 1.0.0x4) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(*, renamed: "bad name") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "_") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "a+b") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "a(") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "a(:)") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "a(:b:)") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, deprecated, unavailable, message: "message") // expected-error{{'available' attribute cannot be both unconditionally 'unavailable' and 'deprecated'}}
struct BadUnconditionalAvailability { };
@available(*, unavailable, message="oh no you don't") // expected-error {{'=' has been replaced with ':' in attribute arguments}} {{35-36=: }}
typealias EqualFixIt1 = Int
@available(*, unavailable, message = "oh no you don't") // expected-error {{'=' has been replaced with ':' in attribute arguments}} {{36-37=:}}
typealias EqualFixIt2 = Int
// Encoding in messages
@available(*, deprecated, message: "Say \"Hi\"")
func deprecated_func_with_message() {}
// 'PANDA FACE' (U+1F43C)
@available(*, deprecated, message: "Pandas \u{1F43C} are cute")
struct DeprecatedTypeWithMessage { }
func use_deprecated_with_message() {
deprecated_func_with_message() // expected-warning{{'deprecated_func_with_message()' is deprecated: Say \"Hi\"}}
var _: DeprecatedTypeWithMessage // expected-warning{{'DeprecatedTypeWithMessage' is deprecated: Pandas \u{1F43C} are cute}}
}
@available(*, deprecated, message: "message")
func use_deprecated_func_with_message2() {
deprecated_func_with_message() // no diagnostic
}
@available(*, deprecated, renamed: "blarg")
func deprecated_func_with_renamed() {}
@available(*, deprecated, message: "blarg is your friend", renamed: "blarg")
func deprecated_func_with_message_renamed() {}
@available(*, deprecated, renamed: "wobble")
struct DeprecatedTypeWithRename { }
func use_deprecated_with_renamed() {
deprecated_func_with_renamed() // expected-warning{{'deprecated_func_with_renamed()' is deprecated: renamed to 'blarg'}}
// expected-note@-1{{use 'blarg'}}{{3-31=blarg}}
deprecated_func_with_message_renamed() //expected-warning{{'deprecated_func_with_message_renamed()' is deprecated: blarg is your friend}}
// expected-note@-1{{use 'blarg'}}{{3-39=blarg}}
var _: DeprecatedTypeWithRename // expected-warning{{'DeprecatedTypeWithRename' is deprecated: renamed to 'wobble'}}
// expected-note@-1{{use 'wobble'}}{{10-34=wobble}}
}
// Short form of @available()
@available(iOS 8.0, *)
func functionWithShortFormIOSAvailable() {}
@available(iOS 8, *)
func functionWithShortFormIOSVersionNoPointAvailable() {}
@available(iOS 8.0, OSX 10.10.3, *)
func functionWithShortFormIOSOSXAvailable() {}
@available(iOS 8.0 // expected-error {{must handle potential future platforms with '*'}} {{19-19=, *}}
func shortFormMissingParen() { // expected-error {{expected ')' in 'available' attribute}}
}
@available(iOS 8.0, // expected-error {{expected platform name}}
func shortFormMissingPlatform() {
}
@available(iOS 8.0, iDishwasherOS 22.0, *) // expected-warning {{unrecognized platform name 'iDishwasherOS'}}
func shortFormWithUnrecognizedPlatform() {
}
@available(iOS 8.0, iDishwasherOS 22.0, iRefrigeratorOS 18.0, *)
// expected-warning@-1 {{unrecognized platform name 'iDishwasherOS'}}
// expected-warning@-2 {{unrecognized platform name 'iRefrigeratorOS'}}
func shortFormWithTwoUnrecognizedPlatforms() {
}
// Make sure that even after the parser hits an unrecognized
// platform it validates the availability.
@available(iOS 8.0, iDishwasherOS 22.0, iOS 9.0, *)
// expected-warning@-1 {{unrecognized platform name 'iDishwasherOS'}}
// expected-error@-2 {{version for 'iOS' already specified}}
func shortFormWithUnrecognizedPlatformContinueValidating() {
}
@available(iOS 8.0, *
func shortFormMissingParenAfterWildcard() { // expected-error {{expected ')' in 'available' attribute}}
}
@available(*) // expected-error {{expected ',' in 'available' attribute}}
func onlyWildcardInAvailable() {}
@available(iOS 8.0, *, OSX 10.10.3)
func shortFormWithWildcardInMiddle() {}
@available(iOS 8.0, OSX 10.10.3) // expected-error {{must handle potential future platforms with '*'}} {{32-32=, *}}
func shortFormMissingWildcard() {}
@availability(OSX, introduced: 10.10) // expected-error {{'@availability' has been renamed to '@available'}} {{2-14=available}}
func someFuncUsingOldAttribute() { }
// <rdar://problem/23853709> Compiler crash on call to unavailable "print"
@available(*, unavailable, message: "Please use the 'to' label for the target stream: 'print((...), to: &...)'")
func print<T>(_: T, _: inout TextOutputStream) {} // expected-note {{}}
func TextOutputStreamTest(message: String, to: inout TextOutputStream) {
print(message, &to) // expected-error {{'print' is unavailable: Please use the 'to' label for the target stream: 'print((...), to: &...)'}}
}
struct DummyType {}
@available(*, unavailable, renamed: "&+")
func +(x: DummyType, y: DummyType) {} // expected-note {{here}}
@available(*, deprecated, renamed: "&-")
func -(x: DummyType, y: DummyType) {}
func testOperators(x: DummyType, y: DummyType) {
x + y // expected-error {{'+' has been renamed to '&+'}} {{5-6=&+}}
x - y // expected-warning {{'-' is deprecated: renamed to '&-'}} expected-note {{use '&-' instead}} {{5-6=&-}}
}
@available(*, unavailable, renamed: "DummyType.foo")
func unavailableMember() {} // expected-note {{here}}
@available(*, deprecated, renamed: "DummyType.bar")
func deprecatedMember() {}
@available(*, unavailable, renamed: "DummyType.Inner.foo")
func unavailableNestedMember() {} // expected-note {{here}}
@available(*, unavailable, renamed: "DummyType.Foo")
struct UnavailableType {} // expected-note {{here}}
@available(*, deprecated, renamed: "DummyType.Bar")
typealias DeprecatedType = Int
func testGlobalToMembers() {
unavailableMember() // expected-error {{'unavailableMember()' has been renamed to 'DummyType.foo'}} {{3-20=DummyType.foo}}
deprecatedMember() // expected-warning {{'deprecatedMember()' is deprecated: renamed to 'DummyType.bar'}} expected-note {{use 'DummyType.bar' instead}} {{3-19=DummyType.bar}}
unavailableNestedMember() // expected-error {{'unavailableNestedMember()' has been renamed to 'DummyType.Inner.foo'}} {{3-26=DummyType.Inner.foo}}
let x: UnavailableType? = nil // expected-error {{'UnavailableType' has been renamed to 'DummyType.Foo'}} {{10-25=DummyType.Foo}}
_ = x
let y: DeprecatedType? = nil // expected-warning {{'DeprecatedType' is deprecated: renamed to 'DummyType.Bar'}} expected-note {{use 'DummyType.Bar' instead}} {{10-24=DummyType.Bar}}
_ = y
}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableArgNames(a: Int) {} // expected-note {{here}}
@available(*, deprecated, renamed: "moreShinyLabeledArguments(example:)")
func deprecatedArgNames(b: Int) {}
@available(*, unavailable, renamed: "DummyType.shinyLabeledArguments(example:)")
func unavailableMemberArgNames(a: Int) {} // expected-note {{here}}
@available(*, deprecated, renamed: "DummyType.moreShinyLabeledArguments(example:)")
func deprecatedMemberArgNames(b: Int) {}
@available(*, unavailable, renamed: "DummyType.shinyLabeledArguments(example:)", message: "ha")
func unavailableMemberArgNamesMsg(a: Int) {} // expected-note {{here}}
@available(*, deprecated, renamed: "DummyType.moreShinyLabeledArguments(example:)", message: "ha")
func deprecatedMemberArgNamesMsg(b: Int) {}
@available(*, unavailable, renamed: "shinyLabeledArguments()")
func unavailableNoArgs() {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:)")
func unavailableSame(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableUnnamedSame(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableNewlyUnnamed(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ:)")
func unavailableVeryLongArgNames(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)")
func unavailableMultiSame(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:another:)")
func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.init(other:)")
func unavailableInit(a: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "Foo.Bar.init(other:)")
func unavailableNestedInit(a: Int) {} // expected-note 2 {{here}}
func testArgNames() {
unavailableArgNames(a: 0) // expected-error {{'unavailableArgNames(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{3-22=shinyLabeledArguments}} {{23-24=example}}
deprecatedArgNames(b: 1) // expected-warning {{'deprecatedArgNames(b:)' is deprecated: renamed to 'moreShinyLabeledArguments(example:)'}} expected-note {{use 'moreShinyLabeledArguments(example:)' instead}} {{3-21=moreShinyLabeledArguments}} {{22-23=example}}
unavailableMemberArgNames(a: 0) // expected-error {{'unavailableMemberArgNames(a:)' has been replaced by 'DummyType.shinyLabeledArguments(example:)'}} {{3-28=DummyType.shinyLabeledArguments}} {{29-30=example}}
deprecatedMemberArgNames(b: 1) // expected-warning {{'deprecatedMemberArgNames(b:)' is deprecated: replaced by 'DummyType.moreShinyLabeledArguments(example:)'}} expected-note {{use 'DummyType.moreShinyLabeledArguments(example:)' instead}} {{3-27=DummyType.moreShinyLabeledArguments}} {{28-29=example}}
unavailableMemberArgNamesMsg(a: 0) // expected-error {{'unavailableMemberArgNamesMsg(a:)' has been replaced by 'DummyType.shinyLabeledArguments(example:)': ha}} {{3-31=DummyType.shinyLabeledArguments}} {{32-33=example}}
deprecatedMemberArgNamesMsg(b: 1) // expected-warning {{'deprecatedMemberArgNamesMsg(b:)' is deprecated: ha}} expected-note {{use 'DummyType.moreShinyLabeledArguments(example:)' instead}} {{3-30=DummyType.moreShinyLabeledArguments}} {{31-32=example}}
unavailableNoArgs() // expected-error {{'unavailableNoArgs()' has been renamed to 'shinyLabeledArguments()'}} {{3-20=shinyLabeledArguments}}
unavailableSame(a: 0) // expected-error {{'unavailableSame(a:)' has been renamed to 'shinyLabeledArguments(a:)'}} {{3-18=shinyLabeledArguments}}
unavailableUnnamed(0) // expected-error {{'unavailableUnnamed' has been renamed to 'shinyLabeledArguments(example:)'}} {{3-21=shinyLabeledArguments}} {{22-22=example: }}
unavailableUnnamedSame(0) // expected-error {{'unavailableUnnamedSame' has been renamed to 'shinyLabeledArguments(_:)'}} {{3-25=shinyLabeledArguments}}
unavailableNewlyUnnamed(a: 0) // expected-error {{'unavailableNewlyUnnamed(a:)' has been renamed to 'shinyLabeledArguments(_:)'}} {{3-26=shinyLabeledArguments}} {{27-30=}}
unavailableVeryLongArgNames(a: 0) // expected-error {{'unavailableVeryLongArgNames(a:)' has been renamed to 'shinyLabeledArguments(veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ:)'}} {{3-30=shinyLabeledArguments}} {{31-32=veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ}}
unavailableMultiSame(a: 0, b: 1) // expected-error {{'unavailableMultiSame(a:b:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-23=shinyLabeledArguments}}
unavailableMultiUnnamed(0, 1) // expected-error {{'unavailableMultiUnnamed' has been renamed to 'shinyLabeledArguments(example:another:)'}} {{3-26=shinyLabeledArguments}} {{27-27=example: }} {{30-30=another: }}
unavailableMultiUnnamedSame(0, 1) // expected-error {{'unavailableMultiUnnamedSame' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{3-30=shinyLabeledArguments}}
unavailableMultiNewlyUnnamed(a: 0, b: 1) // expected-error {{'unavailableMultiNewlyUnnamed(a:b:)' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{3-31=shinyLabeledArguments}} {{32-35=}} {{38-41=}}
unavailableInit(a: 0) // expected-error {{'unavailableInit(a:)' has been replaced by 'Int.init(other:)'}} {{3-18=Int}} {{19-20=other}}
let fn = unavailableInit // expected-error {{'unavailableInit(a:)' has been replaced by 'Int.init(other:)'}} {{12-27=Int.init}}
fn(1)
unavailableNestedInit(a: 0) // expected-error {{'unavailableNestedInit(a:)' has been replaced by 'Foo.Bar.init(other:)'}} {{3-24=Foo.Bar}} {{25-26=other}}
let fn2 = unavailableNestedInit // expected-error {{'unavailableNestedInit(a:)' has been replaced by 'Foo.Bar.init(other:)'}} {{13-34=Foo.Bar.init}}
fn2(1)
}
@available(*, unavailable, renamed: "shinyLabeledArguments()")
func unavailableTooFew(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments()")
func unavailableTooFewUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)")
func unavailableTooMany(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)")
func unavailableTooManyUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:)")
func unavailableNoArgsTooMany() {} // expected-note {{here}}
func testRenameArgMismatch() {
unavailableTooFew(a: 0) // expected-error{{'unavailableTooFew(a:)' has been renamed to 'shinyLabeledArguments()'}} {{3-20=shinyLabeledArguments}}
unavailableTooFewUnnamed(0) // expected-error{{'unavailableTooFewUnnamed' has been renamed to 'shinyLabeledArguments()'}} {{3-27=shinyLabeledArguments}}
unavailableTooMany(a: 0) // expected-error{{'unavailableTooMany(a:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-21=shinyLabeledArguments}}
unavailableTooManyUnnamed(0) // expected-error{{'unavailableTooManyUnnamed' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-28=shinyLabeledArguments}}
unavailableNoArgsTooMany() // expected-error{{'unavailableNoArgsTooMany()' has been renamed to 'shinyLabeledArguments(a:)'}} {{3-27=shinyLabeledArguments}}
}
@available(*, unavailable, renamed: "Int.foo(self:)")
func unavailableInstance(a: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "Int.foo(self:)")
func unavailableInstanceUnlabeled(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:other:)")
func unavailableInstanceFirst(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(other:self:)")
func unavailableInstanceSecond(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(_:self:c:)")
func unavailableInstanceSecondOfThree(a: Int, b: Int, c: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:)", message: "blah")
func unavailableInstanceMessage(a: Int) {} // expected-note {{here}}
@available(*, deprecated, renamed: "Int.foo(self:)")
func deprecatedInstance(a: Int) {}
@available(*, deprecated, renamed: "Int.foo(self:)", message: "blah")
func deprecatedInstanceMessage(a: Int) {}
@available(*, unavailable, renamed: "Foo.Bar.foo(self:)")
func unavailableNestedInstance(a: Int) {} // expected-note {{here}}
func testRenameInstance() {
unavailableInstance(a: 0) // expected-error{{'unavailableInstance(a:)' has been replaced by instance method 'Int.foo()'}} {{3-22=0.foo}} {{23-27=}}
unavailableInstanceUnlabeled(0) // expected-error{{'unavailableInstanceUnlabeled' has been replaced by instance method 'Int.foo()'}} {{3-31=0.foo}} {{32-33=}}
unavailableInstanceFirst(a: 0, b: 1) // expected-error{{'unavailableInstanceFirst(a:b:)' has been replaced by instance method 'Int.foo(other:)'}} {{3-27=0.foo}} {{28-34=}} {{34-35=other}}
unavailableInstanceSecond(a: 0, b: 1) // expected-error{{'unavailableInstanceSecond(a:b:)' has been replaced by instance method 'Int.foo(other:)'}} {{3-28=1.foo}} {{29-30=other}} {{33-39=}}
unavailableInstanceSecondOfThree(a: 0, b: 1, c: 2) // expected-error{{'unavailableInstanceSecondOfThree(a:b:c:)' has been replaced by instance method 'Int.foo(_:c:)'}} {{3-35=1.foo}} {{36-39=}} {{42-48=}}
unavailableInstance(a: 0 + 0) // expected-error{{'unavailableInstance(a:)' has been replaced by instance method 'Int.foo()'}} {{3-22=(0 + 0).foo}} {{23-31=}}
unavailableInstanceMessage(a: 0) // expected-error{{'unavailableInstanceMessage(a:)' has been replaced by instance method 'Int.foo()': blah}} {{3-29=0.foo}} {{30-34=}}
deprecatedInstance(a: 0) // expected-warning{{'deprecatedInstance(a:)' is deprecated: replaced by instance method 'Int.foo()'}} expected-note{{use 'Int.foo()' instead}} {{3-21=0.foo}} {{22-26=}}
deprecatedInstanceMessage(a: 0) // expected-warning{{'deprecatedInstanceMessage(a:)' is deprecated: blah}} expected-note{{use 'Int.foo()' instead}} {{3-28=0.foo}} {{29-33=}}
unavailableNestedInstance(a: 0) // expected-error{{'unavailableNestedInstance(a:)' has been replaced by instance method 'Foo.Bar.foo()'}} {{3-28=0.foo}} {{29-33=}}
}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)")
func unavailableInstanceTooFew(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)")
func unavailableInstanceTooFewUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:b:)")
func unavailableInstanceTooMany(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:b:)")
func unavailableInstanceTooManyUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)")
func unavailableInstanceNoArgsTooMany() {} // expected-note {{here}}
func testRenameInstanceArgMismatch() {
unavailableInstanceTooFew(a: 0, b: 1) // expected-error{{'unavailableInstanceTooFew(a:b:)' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}}
unavailableInstanceTooFewUnnamed(0, 1) // expected-error{{'unavailableInstanceTooFewUnnamed' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}}
unavailableInstanceTooMany(a: 0) // expected-error{{'unavailableInstanceTooMany(a:)' has been replaced by instance method 'Int.shinyLabeledArguments(b:)'}} {{none}}
unavailableInstanceTooManyUnnamed(0) // expected-error{{'unavailableInstanceTooManyUnnamed' has been replaced by instance method 'Int.shinyLabeledArguments(b:)'}} {{none}}
unavailableInstanceNoArgsTooMany() // expected-error{{'unavailableInstanceNoArgsTooMany()' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}}
}
@available(*, unavailable, renamed: "getter:Int.prop(self:)")
func unavailableInstanceProperty(a: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "getter:Int.prop(self:)")
func unavailableInstancePropertyUnlabeled(_ a: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "getter:Int.prop()")
func unavailableClassProperty() {} // expected-note {{here}}
@available(*, unavailable, renamed: "getter:global()")
func unavailableGlobalProperty() {} // expected-note {{here}}
@available(*, unavailable, renamed: "getter:Int.prop(self:)", message: "blah")
func unavailableInstancePropertyMessage(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "getter:Int.prop()", message: "blah")
func unavailableClassPropertyMessage() {} // expected-note {{here}}
@available(*, unavailable, renamed: "getter:global()", message: "blah")
func unavailableGlobalPropertyMessage() {} // expected-note {{here}}
@available(*, deprecated, renamed: "getter:Int.prop(self:)")
func deprecatedInstanceProperty(a: Int) {}
@available(*, deprecated, renamed: "getter:Int.prop()")
func deprecatedClassProperty() {}
@available(*, deprecated, renamed: "getter:global()")
func deprecatedGlobalProperty() {}
@available(*, deprecated, renamed: "getter:Int.prop(self:)", message: "blah")
func deprecatedInstancePropertyMessage(a: Int) {}
@available(*, deprecated, renamed: "getter:Int.prop()", message: "blah")
func deprecatedClassPropertyMessage() {}
@available(*, deprecated, renamed: "getter:global()", message: "blah")
func deprecatedGlobalPropertyMessage() {}
func testRenameGetters() {
unavailableInstanceProperty(a: 1) // expected-error{{'unavailableInstanceProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=1.prop}} {{30-36=}}
unavailableInstancePropertyUnlabeled(1) // expected-error{{'unavailableInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-39=1.prop}} {{39-42=}}
unavailableInstanceProperty(a: 1 + 1) // expected-error{{'unavailableInstanceProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=(1 + 1).prop}} {{30-40=}}
unavailableInstancePropertyUnlabeled(1 + 1) // expected-error{{'unavailableInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-39=(1 + 1).prop}} {{39-46=}}
unavailableClassProperty() // expected-error{{'unavailableClassProperty()' has been replaced by property 'Int.prop'}} {{3-27=Int.prop}} {{27-29=}}
unavailableGlobalProperty() // expected-error{{'unavailableGlobalProperty()' has been replaced by 'global'}} {{3-28=global}} {{28-30=}}
unavailableInstancePropertyMessage(a: 1) // expected-error{{'unavailableInstancePropertyMessage(a:)' has been replaced by property 'Int.prop': blah}} {{3-37=1.prop}} {{37-43=}}
unavailableClassPropertyMessage() // expected-error{{'unavailableClassPropertyMessage()' has been replaced by property 'Int.prop': blah}} {{3-34=Int.prop}} {{34-36=}}
unavailableGlobalPropertyMessage() // expected-error{{'unavailableGlobalPropertyMessage()' has been replaced by 'global': blah}} {{3-35=global}} {{35-37=}}
deprecatedInstanceProperty(a: 1) // expected-warning {{'deprecatedInstanceProperty(a:)' is deprecated: replaced by property 'Int.prop'}} expected-note{{use 'Int.prop' instead}} {{3-29=1.prop}} {{29-35=}}
deprecatedClassProperty() // expected-warning {{'deprecatedClassProperty()' is deprecated: replaced by property 'Int.prop'}} expected-note{{use 'Int.prop' instead}} {{3-26=Int.prop}} {{26-28=}}
deprecatedGlobalProperty() // expected-warning {{'deprecatedGlobalProperty()' is deprecated: replaced by 'global'}} expected-note{{use 'global' instead}} {{3-27=global}} {{27-29=}}
deprecatedInstancePropertyMessage(a: 1) // expected-warning {{'deprecatedInstancePropertyMessage(a:)' is deprecated: blah}} expected-note{{use 'Int.prop' instead}} {{3-36=1.prop}} {{36-42=}}
deprecatedClassPropertyMessage() // expected-warning {{'deprecatedClassPropertyMessage()' is deprecated: blah}} expected-note{{use 'Int.prop' instead}} {{3-33=Int.prop}} {{33-35=}}
deprecatedGlobalPropertyMessage() // expected-warning {{'deprecatedGlobalPropertyMessage()' is deprecated: blah}} expected-note{{use 'global' instead}} {{3-34=global}} {{34-36=}}
}
@available(*, unavailable, renamed: "setter:Int.prop(self:_:)")
func unavailableSetInstanceProperty(a: Int, b: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(_:self:)")
func unavailableSetInstancePropertyReverse(a: Int, b: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(self:newValue:)")
func unavailableSetInstancePropertyUnlabeled(_ a: Int, _ b: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(newValue:self:)")
func unavailableSetInstancePropertyUnlabeledReverse(_ a: Int, _ b: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(x:)")
func unavailableSetClassProperty(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "setter:global(_:)")
func unavailableSetGlobalProperty(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(self:_:)")
func unavailableSetInstancePropertyInout(a: inout Int, b: Int) {} // expected-note {{here}}
func testRenameSetters() {
unavailableSetInstanceProperty(a: 1, b: 2) // expected-error{{'unavailableSetInstanceProperty(a:b:)' has been replaced by property 'Int.prop'}} {{3-33=1.prop}} {{33-43= = }} {{44-45=}}
unavailableSetInstancePropertyUnlabeled(1, 2) // expected-error{{'unavailableSetInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-42=1.prop}} {{42-46= = }} {{47-48=}}
unavailableSetInstancePropertyReverse(a: 1, b: 2) // expected-error{{'unavailableSetInstancePropertyReverse(a:b:)' has been replaced by property 'Int.prop'}} {{3-40=2.prop}} {{40-44= = }} {{45-52=}}
unavailableSetInstancePropertyUnlabeledReverse(1, 2) // expected-error{{'unavailableSetInstancePropertyUnlabeledReverse' has been replaced by property 'Int.prop'}} {{3-49=2.prop}} {{49-50= = }} {{51-55=}}
unavailableSetInstanceProperty(a: 1 + 1, b: 2 + 2) // expected-error{{'unavailableSetInstanceProperty(a:b:)' has been replaced by property 'Int.prop'}} {{3-33=(1 + 1).prop}} {{33-47= = }} {{52-53=}}
unavailableSetInstancePropertyUnlabeled(1 + 1, 2 + 2) // expected-error{{'unavailableSetInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-42=(1 + 1).prop}} {{42-50= = }} {{55-56=}}
unavailableSetInstancePropertyReverse(a: 1 + 1, b: 2 + 2) // expected-error{{'unavailableSetInstancePropertyReverse(a:b:)' has been replaced by property 'Int.prop'}} {{3-40=(2 + 2).prop}} {{40-44= = }} {{49-60=}}
unavailableSetInstancePropertyUnlabeledReverse(1 + 1, 2 + 2) // expected-error{{'unavailableSetInstancePropertyUnlabeledReverse' has been replaced by property 'Int.prop'}} {{3-49=(2 + 2).prop}} {{49-50= = }} {{55-63=}}
unavailableSetClassProperty(a: 1) // expected-error{{'unavailableSetClassProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=Int.prop}} {{30-34= = }} {{35-36=}}
unavailableSetGlobalProperty(1) // expected-error{{'unavailableSetGlobalProperty' has been replaced by 'global'}} {{3-31=global}} {{31-32= = }} {{33-34=}}
var x = 0
unavailableSetInstancePropertyInout(a: &x, b: 2) // expected-error{{'unavailableSetInstancePropertyInout(a:b:)' has been replaced by property 'Int.prop'}} {{3-38=x.prop}} {{38-49= = }} {{50-51=}}
}
@available(*, unavailable, renamed: "Int.foo(self:execute:)")
func trailingClosure(_ value: Int, fn: () -> Void) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:bar:execute:)")
func trailingClosureArg(_ value: Int, _ other: Int, fn: () -> Void) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(bar:self:execute:)")
func trailingClosureArg2(_ value: Int, _ other: Int, fn: () -> Void) {} // expected-note {{here}}
func testInstanceTrailingClosure() {
// FIXME: regression in fixit due to noescape-by-default
trailingClosure(0) {} // expected-error {{'trailingClosure(_:fn:)' has been replaced by instance method 'Int.foo(execute:)'}} // FIXME: {{3-18=0.foo}} {{19-20=}}
trailingClosureArg(0, 1) {} // expected-error {{'trailingClosureArg(_:_:fn:)' has been replaced by instance method 'Int.foo(bar:execute:)'}} // FIXME: {{3-21=0.foo}} {{22-25=}} {{25-25=bar: }}
trailingClosureArg2(0, 1) {} // expected-error {{'trailingClosureArg2(_:_:fn:)' has been replaced by instance method 'Int.foo(bar:execute:)'}} // FIXME: {{3-22=1.foo}} {{23-23=bar: }} {{24-27=}}
}
@available(*, unavailable, renamed: "+")
func add(_ value: Int, _ other: Int) {} // expected-note {{here}}
infix operator ***
@available(*, unavailable, renamed: "add")
func ***(value: (), other: ()) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:_:)")
func ***(value: Int, other: Int) {} // expected-note {{here}}
prefix operator ***
@available(*, unavailable, renamed: "add")
prefix func ***(value: Int?) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:)")
prefix func ***(value: Int) {} // expected-note {{here}}
postfix operator ***
@available(*, unavailable, renamed: "add")
postfix func ***(value: Int?) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:)")
postfix func ***(value: Int) {} // expected-note {{here}}
func testOperators() {
add(0, 1) // expected-error {{'add' has been renamed to '+'}} {{none}}
() *** () // expected-error {{'***' has been renamed to 'add'}} {{none}}
0 *** 1 // expected-error {{'***' has been replaced by instance method 'Int.foo(_:)'}} {{none}}
***nil // expected-error {{'***' has been renamed to 'add'}} {{none}}
***0 // expected-error {{'***' has been replaced by instance method 'Int.foo()'}} {{none}}
nil*** // expected-error {{'***' has been renamed to 'add'}} {{none}}
0*** // expected-error {{'***' has been replaced by instance method 'Int.foo()'}} {{none}}
}
extension Int {
@available(*, unavailable, renamed: "init(other:)")
@discardableResult
static func factory(other: Int) -> Int { return other } // expected-note 2 {{here}}
@available(*, unavailable, renamed: "Int.init(other:)")
@discardableResult
static func factory2(other: Int) -> Int { return other } // expected-note 2 {{here}}
static func testFactoryMethods() {
factory(other: 1) // expected-error {{'factory(other:)' has been replaced by 'init(other:)'}} {{none}}
factory2(other: 1) // expected-error {{'factory2(other:)' has been replaced by 'Int.init(other:)'}} {{5-13=Int}}
}
}
func testFactoryMethods() {
Int.factory(other: 1) // expected-error {{'factory(other:)' has been replaced by 'init(other:)'}} {{6-14=}}
Int.factory2(other: 1) // expected-error {{'factory2(other:)' has been replaced by 'Int.init(other:)'}} {{3-15=Int}}
}
class Base {
@available(*, unavailable)
func bad() {} // expected-note {{here}}
@available(*, unavailable, message: "it was smelly")
func smelly() {} // expected-note {{here}}
@available(*, unavailable, renamed: "new")
func old() {} // expected-note {{here}}
@available(*, unavailable, renamed: "new", message: "it was smelly")
func oldAndSmelly() {} // expected-note {{here}}
@available(*, unavailable)
func expendable() {}
@available(*, unavailable)
var badProp: Int { return 0 } // expected-note {{here}}
@available(*, unavailable, message: "it was smelly")
var smellyProp: Int { return 0 } // expected-note {{here}}
@available(*, unavailable, renamed: "new")
var oldProp: Int { return 0 } // expected-note {{here}}
@available(*, unavailable, renamed: "new", message: "it was smelly")
var oldAndSmellyProp: Int { return 0 } // expected-note {{here}}
@available(*, unavailable)
var expendableProp: Int { return 0 }
@available(*, unavailable, renamed: "init")
func nowAnInitializer() {} // expected-note {{here}}
@available(*, unavailable, renamed: "init()")
func nowAnInitializer2() {} // expected-note {{here}}
@available(*, unavailable, renamed: "foo")
init(nowAFunction: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "foo(_:)")
init(nowAFunction2: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableArgNames(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableArgRenamed(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments()")
func unavailableNoArgs() {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:)")
func unavailableSame(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableUnnamedSame(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableNewlyUnnamed(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)")
func unavailableMultiSame(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:another:)")
func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "init(shinyNewName:)")
init(unavailableArgNames: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "init(a:)")
init(_ unavailableUnnamed: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "init(_:)")
init(unavailableNewlyUnnamed: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "init(a:b:)")
init(_ unavailableMultiUnnamed: Int, _ b: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "init(_:_:)")
init(unavailableMultiNewlyUnnamed a: Int, b: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(x:)")
func unavailableTooFew(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(x:b:)")
func unavailableTooMany(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(x:)")
func unavailableNoArgsTooMany() {} // expected-note {{here}}
@available(*, unavailable, renamed: "Base.shinyLabeledArguments()")
func unavailableHasType() {} // expected-note {{here}}
}
class Sub : Base {
override func bad() {} // expected-error {{cannot override 'bad' which has been marked unavailable}} {{none}} expected-note {{remove 'override' modifier to declare a new 'bad'}} {{3-12=}}
override func smelly() {} // expected-error {{cannot override 'smelly' which has been marked unavailable: it was smelly}} {{none}} expected-note {{remove 'override' modifier to declare a new 'smelly'}} {{3-12=}}
override func old() {} // expected-error {{'old()' has been renamed to 'new'}} {{17-20=new}} expected-note {{remove 'override' modifier to declare a new 'old'}} {{3-12=}}
override func oldAndSmelly() {} // expected-error {{'oldAndSmelly()' has been renamed to 'new': it was smelly}} {{17-29=new}} expected-note {{remove 'override' modifier to declare a new 'oldAndSmelly'}} {{3-12=}}
func expendable() {} // no-error
override var badProp: Int { return 0 } // expected-error {{cannot override 'badProp' which has been marked unavailable}} {{none}} expected-note {{remove 'override' modifier to declare a new 'badProp'}} {{3-12=}}
override var smellyProp: Int { return 0 } // expected-error {{cannot override 'smellyProp' which has been marked unavailable: it was smelly}} {{none}} expected-note {{remove 'override' modifier to declare a new 'smellyProp'}} {{3-12=}}
override var oldProp: Int { return 0 } // expected-error {{'oldProp' has been renamed to 'new'}} {{16-23=new}} expected-note {{remove 'override' modifier to declare a new 'oldProp'}} {{3-12=}}
override var oldAndSmellyProp: Int { return 0 } // expected-error {{'oldAndSmellyProp' has been renamed to 'new': it was smelly}} {{16-32=new}} expected-note {{remove 'override' modifier to declare a new 'oldAndSmellyProp'}} {{3-12=}}
var expendableProp: Int { return 0 } // no-error
override func nowAnInitializer() {} // expected-error {{'nowAnInitializer()' has been replaced by 'init'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'nowAnInitializer'}} {{3-12=}}
override func nowAnInitializer2() {} // expected-error {{'nowAnInitializer2()' has been replaced by 'init()'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'nowAnInitializer2'}} {{3-12=}}
override init(nowAFunction: Int) {} // expected-error {{'init(nowAFunction:)' has been renamed to 'foo'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}}
override init(nowAFunction2: Int) {} // expected-error {{'init(nowAFunction2:)' has been renamed to 'foo(_:)'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}}
override func unavailableArgNames(a: Int) {} // expected-error {{'unavailableArgNames(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-36=shinyLabeledArguments}} {{37-37=example }} expected-note {{remove 'override' modifier to declare a new 'unavailableArgNames'}} {{3-12=}}
override func unavailableArgRenamed(a param: Int) {} // expected-error {{'unavailableArgRenamed(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-38=shinyLabeledArguments}} {{39-40=example}} expected-note {{remove 'override' modifier to declare a new 'unavailableArgRenamed'}} {{3-12=}}
override func unavailableNoArgs() {} // expected-error {{'unavailableNoArgs()' has been renamed to 'shinyLabeledArguments()'}} {{17-34=shinyLabeledArguments}} expected-note {{remove 'override' modifier to declare a new 'unavailableNoArgs'}} {{3-12=}}
override func unavailableSame(a: Int) {} // expected-error {{'unavailableSame(a:)' has been renamed to 'shinyLabeledArguments(a:)'}} {{17-32=shinyLabeledArguments}} expected-note {{remove 'override' modifier to declare a new 'unavailableSame'}} {{3-12=}}
override func unavailableUnnamed(_ a: Int) {} // expected-error {{'unavailableUnnamed' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-35=shinyLabeledArguments}} {{36-37=example}} expected-note {{remove 'override' modifier to declare a new 'unavailableUnnamed'}} {{3-12=}}
override func unavailableUnnamedSame(_ a: Int) {} // expected-error {{'unavailableUnnamedSame' has been renamed to 'shinyLabeledArguments(_:)'}} {{17-39=shinyLabeledArguments}} expected-note {{remove 'override' modifier to declare a new 'unavailableUnnamedSame'}} {{3-12=}}
override func unavailableNewlyUnnamed(a: Int) {} // expected-error {{'unavailableNewlyUnnamed(a:)' has been renamed to 'shinyLabeledArguments(_:)'}} {{17-40=shinyLabeledArguments}} {{41-41=_ }} expected-note {{remove 'override' modifier to declare a new 'unavailableNewlyUnnamed'}} {{3-12=}}
override func unavailableMultiSame(a: Int, b: Int) {} // expected-error {{'unavailableMultiSame(a:b:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{17-37=shinyLabeledArguments}} expected-note {{remove 'override' modifier to declare a new 'unavailableMultiSame'}} {{3-12=}}
override func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-error {{'unavailableMultiUnnamed' has been renamed to 'shinyLabeledArguments(example:another:)'}} {{17-40=shinyLabeledArguments}} {{41-42=example}} {{51-52=another}} expected-note {{remove 'override' modifier to declare a new 'unavailableMultiUnnamed'}} {{3-12=}}
override func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-error {{'unavailableMultiUnnamedSame' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{17-44=shinyLabeledArguments}} expected-note {{remove 'override' modifier to declare a new 'unavailableMultiUnnamedSame'}} {{3-12=}}
override func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-error {{'unavailableMultiNewlyUnnamed(a:b:)' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{17-45=shinyLabeledArguments}} {{46-46=_ }} {{54-54=_ }} expected-note {{remove 'override' modifier to declare a new 'unavailableMultiNewlyUnnamed'}} {{3-12=}}
override init(unavailableArgNames: Int) {} // expected-error {{'init(unavailableArgNames:)' has been renamed to 'init(shinyNewName:)'}} {{17-17=shinyNewName }} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}}
override init(_ unavailableUnnamed: Int) {} // expected-error {{'init(_:)' has been renamed to 'init(a:)'}} {{17-18=a}} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}}
override init(unavailableNewlyUnnamed: Int) {} // expected-error {{'init(unavailableNewlyUnnamed:)' has been renamed to 'init(_:)'}} {{17-17=_ }} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}}
override init(_ unavailableMultiUnnamed: Int, _ b: Int) {} // expected-error {{'init(_:_:)' has been renamed to 'init(a:b:)'}} {{17-18=a}} {{49-51=}} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}}
override init(unavailableMultiNewlyUnnamed a: Int, b: Int) {} // expected-error {{'init(unavailableMultiNewlyUnnamed:b:)' has been renamed to 'init(_:_:)'}} {{17-45=_}} {{54-54=_ }} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}}
override func unavailableTooFew(a: Int, b: Int) {} // expected-error {{'unavailableTooFew(a:b:)' has been renamed to 'shinyLabeledArguments(x:)'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'unavailableTooFew'}} {{3-12=}}
override func unavailableTooMany(a: Int) {} // expected-error {{'unavailableTooMany(a:)' has been renamed to 'shinyLabeledArguments(x:b:)'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'unavailableTooMany'}} {{3-12=}}
override func unavailableNoArgsTooMany() {} // expected-error {{'unavailableNoArgsTooMany()' has been renamed to 'shinyLabeledArguments(x:)'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'unavailableNoArgsTooMany'}} {{3-12=}}
override func unavailableHasType() {} // expected-error {{'unavailableHasType()' has been replaced by 'Base.shinyLabeledArguments()'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'unavailableHasType'}} {{3-12=}}
}
// U: Unnamed, L: Labeled
@available(*, unavailable, renamed: "after(fn:)")
func closure_U_L(_ x: () -> Int) {} // expected-note 3 {{here}}
@available(*, unavailable, renamed: "after(fn:)")
func closure_L_L(x: () -> Int) {} // expected-note 3 {{here}}
@available(*, unavailable, renamed: "after(_:)")
func closure_L_U(x: () -> Int) {} // expected-note 3 {{here}}
@available(*, unavailable, renamed: "after(arg:fn:)")
func closure_UU_LL(_ x: Int, _ y: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:fn:)")
func closure_LU_LL(x: Int, _ y: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:fn:)")
func closure_LL_LL(x: Int, y: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:fn:)")
func closure_UU_LL_ne(_ x: Int, _ y: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:_:)")
func closure_UU_LU(_ x: Int, _ closure: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:_:)")
func closure_LU_LU(x: Int, _ closure: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:_:)")
func closure_LL_LU(x: Int, y: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:_:)")
func closure_UU_LU_ne(_ x: Int, _ y: () -> Int) {} // expected-note 2 {{here}}
func testTrailingClosure() {
closure_U_L { 0 } // expected-error {{'closure_U_L' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}}
closure_U_L() { 0 } // expected-error {{'closure_U_L' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}}
closure_U_L({ 0 }) // expected-error {{'closure_U_L' has been renamed to 'after(fn:)'}} {{3-14=after}} {{15-15=fn: }} {{none}}
closure_L_L { 0 } // expected-error {{'closure_L_L(x:)' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}}
closure_L_L() { 0 } // expected-error {{'closure_L_L(x:)' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}}
closure_L_L(x: { 0 }) // expected-error {{'closure_L_L(x:)' has been renamed to 'after(fn:)'}} {{3-14=after}} {{15-16=fn}} {{none}}
closure_L_U { 0 } // expected-error {{'closure_L_U(x:)' has been renamed to 'after(_:)'}} {{3-14=after}} {{none}}
closure_L_U() { 0 } // expected-error {{'closure_L_U(x:)' has been renamed to 'after(_:)'}} {{3-14=after}} {{none}}
closure_L_U(x: { 0 }) // expected-error {{'closure_L_U(x:)' has been renamed to 'after(_:)'}} {{3-14=after}} {{15-18=}} {{none}}
closure_UU_LL(0) { 0 } // expected-error {{'closure_UU_LL' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-17=arg: }} {{none}}
closure_UU_LL(0, { 0 }) // expected-error {{'closure_UU_LL' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-17=arg: }} {{20-20=fn: }} {{none}}
closure_LU_LL(x: 0) { 0 } // expected-error {{'closure_LU_LL(x:_:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{none}}
closure_LU_LL(x: 0, { 0 }) // expected-error {{'closure_LU_LL(x:_:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{23-23=fn: }} {{none}}
closure_LL_LL(x: 1) { 1 } // expected-error {{'closure_LL_LL(x:y:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{none}}
closure_LL_LL(x: 1, y: { 0 }) // expected-error {{'closure_LL_LL(x:y:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{23-24=fn}} {{none}}
closure_UU_LL_ne(1) { 1 } // expected-error {{'closure_UU_LL_ne' has been renamed to 'after(arg:fn:)'}} {{3-19=after}} {{20-20=arg: }} {{none}}
closure_UU_LL_ne(1, { 0 }) // expected-error {{'closure_UU_LL_ne' has been renamed to 'after(arg:fn:)'}} {{3-19=after}} {{20-20=arg: }} {{23-23=fn: }} {{none}}
closure_UU_LU(0) { 0 } // expected-error {{'closure_UU_LU' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-17=arg: }} {{none}}
closure_UU_LU(0, { 0 }) // expected-error {{'closure_UU_LU' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-17=arg: }} {{none}}
closure_LU_LU(x: 0) { 0 } // expected-error {{'closure_LU_LU(x:_:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{none}}
closure_LU_LU(x: 0, { 0 }) // expected-error {{'closure_LU_LU(x:_:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{none}}
closure_LL_LU(x: 1) { 1 } // expected-error {{'closure_LL_LU(x:y:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{none}}
closure_LL_LU(x: 1, y: { 0 }) // expected-error {{'closure_LL_LU(x:y:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{23-26=}} {{none}}
closure_UU_LU_ne(1) { 1 } // expected-error {{'closure_UU_LU_ne' has been renamed to 'after(arg:_:)'}} {{3-19=after}} {{20-20=arg: }} {{none}}
closure_UU_LU_ne(1, { 0 }) // expected-error {{'closure_UU_LU_ne' has been renamed to 'after(arg:_:)'}} {{3-19=after}} {{20-20=arg: }} {{none}}
}
@available(*, unavailable, renamed: "after(x:)")
func defaultUnnamed(_ a: Int = 1) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(x:y:)")
func defaultBeforeRequired(a: Int = 1, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "after(x:y:z:)")
func defaultPlusTrailingClosure(a: Int = 1, b: Int = 2, c: () -> Void) {} // expected-note 3 {{here}}
func testDefaults() {
defaultUnnamed() // expected-error {{'defaultUnnamed' has been renamed to 'after(x:)'}} {{3-17=after}} {{none}}
defaultUnnamed(1) // expected-error {{'defaultUnnamed' has been renamed to 'after(x:)'}} {{3-17=after}} {{18-18=x: }} {{none}}
defaultBeforeRequired(b: 5) // expected-error {{'defaultBeforeRequired(a:b:)' has been renamed to 'after(x:y:)'}} {{3-24=after}} {{25-26=y}} {{none}}
defaultPlusTrailingClosure {} // expected-error {{'defaultPlusTrailingClosure(a:b:c:)' has been renamed to 'after(x:y:z:)'}} {{3-29=after}} {{none}}
defaultPlusTrailingClosure(c: {}) // expected-error {{'defaultPlusTrailingClosure(a:b:c:)' has been renamed to 'after(x:y:z:)'}} {{3-29=after}} {{30-31=z}} {{none}}
defaultPlusTrailingClosure(a: 1) {} // expected-error {{'defaultPlusTrailingClosure(a:b:c:)' has been renamed to 'after(x:y:z:)'}} {{3-29=after}} {{30-31=x}} {{none}}
}
@available(*, unavailable, renamed: "after(x:y:)")
func variadic1(a: Int ..., b: Int = 0) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(x:y:)")
func variadic2(a: Int, _ b: Int ...) {} // expected-note {{here}}
@available(*, unavailable, renamed: "after(x:_:y:z:)")
func variadic3(_ a: Int, b: Int ..., c: String = "", d: String) {} // expected-note 2 {{here}}
func testVariadic() {
variadic1(a: 1, 2) // expected-error {{'variadic1(a:b:)' has been renamed to 'after(x:y:)'}} {{3-12=after}} {{13-14=x}} {{none}}
variadic1(a: 1, 2, b: 3) // expected-error {{'variadic1(a:b:)' has been renamed to 'after(x:y:)'}} {{3-12=after}} {{13-14=x}} {{22-23=y}} {{none}}
variadic2(a: 1, 2, 3) // expected-error {{'variadic2(a:_:)' has been renamed to 'after(x:y:)'}} {{3-12=after}} {{13-14=x}} {{19-19=y: }} {{none}}
variadic3(1, b: 2, 3, d: "test") // expected-error {{'variadic3(_:b:c:d:)' has been renamed to 'after(x:_:y:z:)'}} {{3-12=after}} {{13-13=x: }} {{16-19=}} {{25-26=z}} {{none}}
variadic3(1, d:"test") // expected-error {{'variadic3(_:b:c:d:)' has been renamed to 'after(x:_:y:z:)'}} {{3-12=after}} {{13-13=x: }} {{16-17=z}} {{none}}
}
enum E_32526620 {
case foo
case bar
func set() {}
}
@available(*, unavailable, renamed: "E_32526620.set(self:)")
func rdar32526620_1(a: E_32526620) {} // expected-note {{here}}
rdar32526620_1(a: .foo)
// expected-error@-1 {{'rdar32526620_1(a:)' has been replaced by instance method 'E_32526620.set()'}} {{1-15=E_32526620.foo.set}} {{16-23=}}
@available(*, unavailable, renamed: "E_32526620.set(a:self:)")
func rdar32526620_2(a: Int, b: E_32526620) {} // expected-note {{here}}
rdar32526620_2(a: 42, b: .bar)
// expected-error@-1 {{'rdar32526620_2(a:b:)' has been replaced by instance method 'E_32526620.set(a:)'}} {{1-15=E_32526620.bar.set}} {{21-30=}}
@available(*, unavailable, renamed: "E_32526620.set(a:self:c:)")
func rdar32526620_3(a: Int, b: E_32526620, c: String) {} // expected-note {{here}}
rdar32526620_3(a: 42, b: .bar, c: "question")
// expected-error@-1 {{'rdar32526620_3(a:b:c:)' has been replaced by instance method 'E_32526620.set(a:c:)'}} {{1-15=E_32526620.bar.set}} {{23-32=}}
var deprecatedGetter: Int {
@available(*, deprecated) get { return 0 }
set {}
}
var deprecatedGetterOnly: Int {
@available(*, deprecated) get { return 0 }
}
var deprecatedSetter: Int {
get { return 0 }
@available(*, deprecated) set {}
}
var deprecatedBoth: Int {
@available(*, deprecated) get { return 0 }
@available(*, deprecated) set {}
}
var deprecatedMessage: Int {
@available(*, deprecated, message: "bad getter") get { return 0 }
@available(*, deprecated, message: "bad setter") set {}
}
var deprecatedRename: Int {
@available(*, deprecated, renamed: "betterThing()") get { return 0 }
@available(*, deprecated, renamed: "setBetterThing(_:)") set {}
}
@available(*, deprecated, message: "bad variable")
var deprecatedProperty: Int {
@available(*, deprecated, message: "bad getter") get { return 0 }
@available(*, deprecated, message: "bad setter") set {}
}
_ = deprecatedGetter // expected-warning {{getter for 'deprecatedGetter' is deprecated}} {{none}}
deprecatedGetter = 0
deprecatedGetter += 1 // expected-warning {{getter for 'deprecatedGetter' is deprecated}} {{none}}
_ = deprecatedGetterOnly // expected-warning {{getter for 'deprecatedGetterOnly' is deprecated}} {{none}}
_ = deprecatedSetter
deprecatedSetter = 0 // expected-warning {{setter for 'deprecatedSetter' is deprecated}} {{none}}
deprecatedSetter += 1 // expected-warning {{setter for 'deprecatedSetter' is deprecated}} {{none}}
_ = deprecatedBoth // expected-warning {{getter for 'deprecatedBoth' is deprecated}} {{none}}
deprecatedBoth = 0 // expected-warning {{setter for 'deprecatedBoth' is deprecated}} {{none}}
deprecatedBoth += 1 // expected-warning {{getter for 'deprecatedBoth' is deprecated}} {{none}} expected-warning {{setter for 'deprecatedBoth' is deprecated}} {{none}}
_ = deprecatedMessage // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}}
deprecatedMessage = 0 // expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}}
deprecatedMessage += 1 // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}} expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}}
_ = deprecatedRename // expected-warning {{getter for 'deprecatedRename' is deprecated: renamed to 'betterThing()'}} {{none}}
deprecatedRename = 0 // expected-warning {{setter for 'deprecatedRename' is deprecated: renamed to 'setBetterThing(_:)'}} {{none}}
deprecatedRename += 1 // expected-warning {{getter for 'deprecatedRename' is deprecated: renamed to 'betterThing()'}} {{none}} expected-warning {{setter for 'deprecatedRename' is deprecated: renamed to 'setBetterThing(_:)'}} {{none}}
_ = deprecatedProperty // expected-warning {{'deprecatedProperty' is deprecated: bad variable}} {{none}}
deprecatedProperty = 0 // expected-warning {{'deprecatedProperty' is deprecated: bad variable}} {{none}}
deprecatedProperty += 1 // expected-warning {{'deprecatedProperty' is deprecated: bad variable}} {{none}}
var unavailableGetter: Int {
@available(*, unavailable) get { return 0 } // expected-note * {{here}}
set {}
}
var unavailableGetterOnly: Int {
@available(*, unavailable) get { return 0 } // expected-note * {{here}}
}
var unavailableSetter: Int {
get { return 0 }
@available(*, unavailable) set {} // expected-note * {{here}}
}
var unavailableBoth: Int {
@available(*, unavailable) get { return 0 } // expected-note * {{here}}
@available(*, unavailable) set {} // expected-note * {{here}}
}
var unavailableMessage: Int {
@available(*, unavailable, message: "bad getter") get { return 0 } // expected-note * {{here}}
@available(*, unavailable, message: "bad setter") set {} // expected-note * {{here}}
}
var unavailableRename: Int {
@available(*, unavailable, renamed: "betterThing()") get { return 0 } // expected-note * {{here}}
@available(*, unavailable, renamed: "setBetterThing(_:)") set {} // expected-note * {{here}}
}
@available(*, unavailable, message: "bad variable")
var unavailableProperty: Int { // expected-note * {{here}}
@available(*, unavailable, message: "bad getter") get { return 0 }
@available(*, unavailable, message: "bad setter") set {}
}
_ = unavailableGetter // expected-error {{getter for 'unavailableGetter' is unavailable}} {{none}}
unavailableGetter = 0
unavailableGetter += 1 // expected-error {{getter for 'unavailableGetter' is unavailable}} {{none}}
_ = unavailableGetterOnly // expected-error {{getter for 'unavailableGetterOnly' is unavailable}} {{none}}
_ = unavailableSetter
unavailableSetter = 0 // expected-error {{setter for 'unavailableSetter' is unavailable}} {{none}}
unavailableSetter += 1 // expected-error {{setter for 'unavailableSetter' is unavailable}} {{none}}
_ = unavailableBoth // expected-error {{getter for 'unavailableBoth' is unavailable}} {{none}}
unavailableBoth = 0 // expected-error {{setter for 'unavailableBoth' is unavailable}} {{none}}
unavailableBoth += 1 // expected-error {{getter for 'unavailableBoth' is unavailable}} {{none}} expected-error {{setter for 'unavailableBoth' is unavailable}} {{none}}
_ = unavailableMessage // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}}
unavailableMessage = 0 // expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}}
unavailableMessage += 1 // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}} expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}}
_ = unavailableRename // expected-error {{getter for 'unavailableRename' has been renamed to 'betterThing()'}} {{none}}
unavailableRename = 0 // expected-error {{setter for 'unavailableRename' has been renamed to 'setBetterThing(_:)'}} {{none}}
unavailableRename += 1 // expected-error {{getter for 'unavailableRename' has been renamed to 'betterThing()'}} {{none}} expected-error {{setter for 'unavailableRename' has been renamed to 'setBetterThing(_:)'}} {{none}}
_ = unavailableProperty // expected-error {{'unavailableProperty' is unavailable: bad variable}} {{none}}
unavailableProperty = 0 // expected-error {{'unavailableProperty' is unavailable: bad variable}} {{none}}
unavailableProperty += 1 // expected-error {{'unavailableProperty' is unavailable: bad variable}} {{none}}
struct DeprecatedAccessors {
var deprecatedMessage: Int {
@available(*, deprecated, message: "bad getter") get { return 0 }
@available(*, deprecated, message: "bad setter") set {}
}
static var staticDeprecated: Int {
@available(*, deprecated, message: "bad getter") get { return 0 }
@available(*, deprecated, message: "bad setter") set {}
}
@available(*, deprecated, message: "bad property")
var deprecatedProperty: Int {
@available(*, deprecated, message: "bad getter") get { return 0 }
@available(*, deprecated, message: "bad setter") set {}
}
subscript(_: Int) -> Int {
@available(*, deprecated, message: "bad subscript getter") get { return 0 }
@available(*, deprecated, message: "bad subscript setter") set {}
}
@available(*, deprecated, message: "bad subscript!")
subscript(alsoDeprecated _: Int) -> Int {
@available(*, deprecated, message: "bad subscript getter") get { return 0 }
@available(*, deprecated, message: "bad subscript setter") set {}
}
mutating func testAccessors(other: inout DeprecatedAccessors) {
_ = deprecatedMessage // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}}
deprecatedMessage = 0 // expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}}
deprecatedMessage += 1 // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}} expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}}
_ = other.deprecatedMessage // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}}
other.deprecatedMessage = 0 // expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}}
other.deprecatedMessage += 1 // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}} expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}}
_ = other.deprecatedProperty // expected-warning {{'deprecatedProperty' is deprecated: bad property}} {{none}}
other.deprecatedProperty = 0 // expected-warning {{'deprecatedProperty' is deprecated: bad property}} {{none}}
other.deprecatedProperty += 1 // expected-warning {{'deprecatedProperty' is deprecated: bad property}} {{none}}
_ = DeprecatedAccessors.staticDeprecated // expected-warning {{getter for 'staticDeprecated' is deprecated: bad getter}} {{none}}
DeprecatedAccessors.staticDeprecated = 0 // expected-warning {{setter for 'staticDeprecated' is deprecated: bad setter}} {{none}}
DeprecatedAccessors.staticDeprecated += 1 // expected-warning {{getter for 'staticDeprecated' is deprecated: bad getter}} {{none}} expected-warning {{setter for 'staticDeprecated' is deprecated: bad setter}} {{none}}
_ = other[0] // expected-warning {{getter for 'subscript(_:)' is deprecated: bad subscript getter}} {{none}}
other[0] = 0 // expected-warning {{setter for 'subscript(_:)' is deprecated: bad subscript setter}} {{none}}
other[0] += 1 // expected-warning {{getter for 'subscript(_:)' is deprecated: bad subscript getter}} {{none}} expected-warning {{setter for 'subscript(_:)' is deprecated: bad subscript setter}} {{none}}
_ = other[alsoDeprecated: 0] // expected-warning {{'subscript(alsoDeprecated:)' is deprecated: bad subscript!}} {{none}}
other[alsoDeprecated: 0] = 0 // expected-warning {{'subscript(alsoDeprecated:)' is deprecated: bad subscript!}} {{none}}
other[alsoDeprecated: 0] += 1 // expected-warning {{'subscript(alsoDeprecated:)' is deprecated: bad subscript!}} {{none}}
}
}
struct UnavailableAccessors {
var unavailableMessage: Int {
@available(*, unavailable, message: "bad getter") get { return 0 } // expected-note * {{here}}
@available(*, unavailable, message: "bad setter") set {} // expected-note * {{here}}
}
static var staticUnavailable: Int {
@available(*, unavailable, message: "bad getter") get { return 0 } // expected-note * {{here}}
@available(*, unavailable, message: "bad setter") set {} // expected-note * {{here}}
}
@available(*, unavailable, message: "bad property")
var unavailableProperty: Int { // expected-note * {{here}}
@available(*, unavailable, message: "bad getter") get { return 0 }
@available(*, unavailable, message: "bad setter") set {}
}
subscript(_: Int) -> Int {
@available(*, unavailable, message: "bad subscript getter") get { return 0 } // expected-note * {{here}}
@available(*, unavailable, message: "bad subscript setter") set {} // expected-note * {{here}}
}
@available(*, unavailable, message: "bad subscript!")
subscript(alsoUnavailable _: Int) -> Int { // expected-note * {{here}}
@available(*, unavailable, message: "bad subscript getter") get { return 0 }
@available(*, unavailable, message: "bad subscript setter") set {}
}
mutating func testAccessors(other: inout UnavailableAccessors) {
_ = unavailableMessage // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}}
unavailableMessage = 0 // expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}}
unavailableMessage += 1 // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}} expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}}
_ = other.unavailableMessage // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}}
other.unavailableMessage = 0 // expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}}
other.unavailableMessage += 1 // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}} expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}}
_ = other.unavailableProperty // expected-error {{'unavailableProperty' is unavailable: bad property}} {{none}}
other.unavailableProperty = 0 // expected-error {{'unavailableProperty' is unavailable: bad property}} {{none}}
other.unavailableProperty += 1 // expected-error {{'unavailableProperty' is unavailable: bad property}} {{none}}
_ = UnavailableAccessors.staticUnavailable // expected-error {{getter for 'staticUnavailable' is unavailable: bad getter}} {{none}}
UnavailableAccessors.staticUnavailable = 0 // expected-error {{setter for 'staticUnavailable' is unavailable: bad setter}} {{none}}
UnavailableAccessors.staticUnavailable += 1 // expected-error {{getter for 'staticUnavailable' is unavailable: bad getter}} {{none}} expected-error {{setter for 'staticUnavailable' is unavailable: bad setter}} {{none}}
_ = other[0] // expected-error {{getter for 'subscript(_:)' is unavailable: bad subscript getter}} {{none}}
other[0] = 0 // expected-error {{setter for 'subscript(_:)' is unavailable: bad subscript setter}} {{none}}
other[0] += 1 // expected-error {{getter for 'subscript(_:)' is unavailable: bad subscript getter}} {{none}} expected-error {{setter for 'subscript(_:)' is unavailable: bad subscript setter}} {{none}}
_ = other[alsoUnavailable: 0] // expected-error {{'subscript(alsoUnavailable:)' is unavailable: bad subscript!}} {{none}}
other[alsoUnavailable: 0] = 0 // expected-error {{'subscript(alsoUnavailable:)' is unavailable: bad subscript!}} {{none}}
other[alsoUnavailable: 0] += 1 // expected-error {{'subscript(alsoUnavailable:)' is unavailable: bad subscript!}} {{none}}
}
}
class BaseDeprecatedInit {
@available(*, deprecated) init(bad: Int) { }
}
class SubInheritedDeprecatedInit: BaseDeprecatedInit { }
_ = SubInheritedDeprecatedInit(bad: 0) // expected-warning {{'init(bad:)' is deprecated}}
// Should produce no warnings.
enum SR8634_Enum: Int {
case a
@available(*, deprecated, message: "I must not be raised in synthesized code")
case b
case c
}
struct SR8634_Struct: Equatable {
@available(*, deprecated, message: "I must not be raised in synthesized code", renamed: "x")
let a: Int
}
@available(*, deprecated, message: "This is a message", message: "This is another message")
// expected-warning@-1 {{'message' argument has already been specified}}
func rdar46348825_message() {}
@available(*, deprecated, renamed: "rdar46348825_message", renamed: "unavailable_func_with_message")
// expected-warning@-1 {{'renamed' argument has already been specified}}
func rdar46348825_renamed() {}
@available(swift, introduced: 4.0, introduced: 4.0)
// expected-warning@-1 {{'introduced' argument has already been specified}}
func rdar46348825_introduced() {}
@available(swift, deprecated: 4.0, deprecated: 4.0)
// expected-warning@-1 {{'deprecated' argument has already been specified}}
func rdar46348825_deprecated() {}
@available(swift, obsoleted: 4.0, obsoleted: 4.0)
// expected-warning@-1 {{'obsoleted' argument has already been specified}}
func rdar46348825_obsoleted() {}
// Referencing unavailable types in signatures of unavailable functions should be accepted
@available(*, unavailable)
protocol UnavailableProto {
}
@available(*, unavailable)
func unavailableFunc(_ arg: UnavailableProto) -> UnavailableProto {}
@available(*, unavailable)
struct S {
var a: UnavailableProto
}
// Bad rename.
struct BadRename {
@available(*, deprecated, renamed: "init(range:step:)")
init(from: Int, to: Int, step: Int = 1) { }
init(range: Range<Int>, step: Int) { }
}
func testBadRename() {
_ = BadRename(from: 5, to: 17) // expected-warning{{'init(from:to:step:)' is deprecated: replaced by 'init(range:step:)'}}
// expected-note@-1{{use 'init(range:step:)' instead}}
}
struct AvailableGenericParam<@available(*, deprecated) T> {}
// expected-error@-1 {{'@available' attribute cannot be applied to this declaration}}
class UnavailableNoArgsSuperclassInit {
@available(*, unavailable)
init() {} // expected-note {{'init()' has been explicitly marked unavailable here}}
}
class UnavailableNoArgsSubclassInit: UnavailableNoArgsSuperclassInit {
init(marker: ()) {}
// expected-error@-1 {{'init()' is unavailable}}
// expected-note@-2 {{call to unavailable initializer 'init()' from superclass 'UnavailableNoArgsSuperclassInit' occurs implicitly at the end of this initializer}}
}
struct TypeWithTrailingClosures {
func twoTrailingClosures(a: () -> Void, b: () -> Void) {}
func threeTrailingClosures(a: () -> Void, b: () -> Void, c: () -> Void) {}
func threeUnlabeledTrailingClosures(_ a: () -> Void, _ b: () -> Void, _ c: () -> Void) {}
func variadicTrailingClosures(a: (() -> Void)..., b: Int = 0, c: Int = 0) {}
}
@available(*, deprecated, renamed: "TypeWithTrailingClosures.twoTrailingClosures(self:a:b:)")
func twoTrailingClosures(_ x: TypeWithTrailingClosures, a: () -> Void, b: () -> Void) {}
@available(*, deprecated, renamed: "TypeWithTrailingClosures.twoTrailingClosures(self:a:b:)")
func twoTrailingClosuresWithDefaults(x: TypeWithTrailingClosures, y: Int = 0, z: Int = 0, a: () -> Void, b: () -> Void) {}
@available(*, deprecated, renamed: "TypeWithTrailingClosures.threeTrailingClosures(self:a:b:c:)")
func threeTrailingClosures(_ x: TypeWithTrailingClosures, a: () -> Void, b: () -> Void, c: () -> Void) {}
@available(*, deprecated, renamed: "TypeWithTrailingClosures.threeTrailingClosures(self:a:b:c:)")
func threeTrailingClosuresDiffLabels(_: TypeWithTrailingClosures, x: () -> Void, y: () -> Void, z: () -> Void) {}
@available(*, deprecated, renamed: "TypeWithTrailingClosures.threeUnlabeledTrailingClosures(self:_:_:_:)")
func threeTrailingClosuresRemoveLabels(_ x: TypeWithTrailingClosures, a: () -> Void, b: () -> Void, c: () -> Void) {}
@available(*, deprecated, renamed: "TypeWithTrailingClosures.variadicTrailingClosures(self:a:b:c:)")
func variadicTrailingClosures(_ x: TypeWithTrailingClosures, a: (() -> Void)...) {}
func testMultipleTrailingClosures(_ x: TypeWithTrailingClosures) {
twoTrailingClosures(x) {} b: {} // expected-warning {{'twoTrailingClosures(_:a:b:)' is deprecated: replaced by instance method 'TypeWithTrailingClosures.twoTrailingClosures(a:b:)'}}
// expected-note@-1 {{use 'TypeWithTrailingClosures.twoTrailingClosures(a:b:)' instead}} {{3-22=x.twoTrailingClosures}} {{23-24=}} {{none}}
x.twoTrailingClosures() {} b: {}
twoTrailingClosuresWithDefaults(x: x) {} b: {} // expected-warning {{'twoTrailingClosuresWithDefaults(x:y:z:a:b:)' is deprecated: replaced by instance method 'TypeWithTrailingClosures.twoTrailingClosures(a:b:)'}}
// expected-note@-1 {{use 'TypeWithTrailingClosures.twoTrailingClosures(a:b:)' instead}} {{3-34=x.twoTrailingClosures}} {{35-39=}} {{none}}
x.twoTrailingClosures() {} b: {}
threeTrailingClosures(x, a: {}) {} c: {} // expected-warning {{'threeTrailingClosures(_:a:b:c:)' is deprecated: replaced by instance method 'TypeWithTrailingClosures.threeTrailingClosures(a:b:c:)'}}
// expected-note@-1 {{use 'TypeWithTrailingClosures.threeTrailingClosures(a:b:c:)' instead}} {{3-24=x.threeTrailingClosures}} {{25-28=}} {{none}}
x.threeTrailingClosures(a: {}) {} c: {}
threeTrailingClosuresDiffLabels(x, x: {}) {} z: {} // expected-warning {{'threeTrailingClosuresDiffLabels(_:x:y:z:)' is deprecated: replaced by instance method 'TypeWithTrailingClosures.threeTrailingClosures(a:b:c:)'}}
// expected-note@-1 {{use 'TypeWithTrailingClosures.threeTrailingClosures(a:b:c:)' instead}} {{3-34=x.threeTrailingClosures}} {{35-38=}} {{38-39=a}} {{48-49=c}} {{none}}
x.threeTrailingClosures(a: {}) {} c: {}
threeTrailingClosuresRemoveLabels(x, a: {}) {} c: {} // expected-warning {{'threeTrailingClosuresRemoveLabels(_:a:b:c:)' is deprecated: replaced by instance method 'TypeWithTrailingClosures.threeUnlabeledTrailingClosures(_:_:_:)'}}
// expected-note@-1 {{use 'TypeWithTrailingClosures.threeUnlabeledTrailingClosures(_:_:_:)' instead}} {{3-36=x.threeUnlabeledTrailingClosures}} {{37-40=}} {{40-43=}} {{50-51=_}} {{none}}
x.threeUnlabeledTrailingClosures({}) {} _: {}
variadicTrailingClosures(x) {} _: {} _: {} // expected-warning {{'variadicTrailingClosures(_:a:)' is deprecated: replaced by instance method 'TypeWithTrailingClosures.variadicTrailingClosures(a:b:c:)'}}
// expected-note@-1 {{use 'TypeWithTrailingClosures.variadicTrailingClosures(a:b:c:)' instead}} {{3-27=x.variadicTrailingClosures}} {{28-29=}} {{none}}
x.variadicTrailingClosures() {} _: {} _: {}
}
struct UnavailableSubscripts {
@available(*, unavailable, renamed: "subscript(new:)")
subscript(old index: Int) -> Int { 3 } // expected-note * {{'subscript(old:)' has been explicitly marked unavailable here}}
@available(*, unavailable, renamed: "subscript(new:)")
func getValue(old: Int) -> Int { 3 } // expected-note * {{'getValue(old:)' has been explicitly marked unavailable here}}
subscript(new index: Int) -> Int { 3 }
@available(*, unavailable, renamed: "getAValue(new:)")
subscript(getAValue index: Int) -> Int { 3 } // expected-note * {{'subscript(getAValue:)' has been explicitly marked unavailable here}}
func getAValue(new: Int) -> Int { 3 }
@available(*, unavailable, renamed: "subscript(arg1:arg2:arg3:)")
subscript(_ argg1: Int, _ argg2: Int, _ argg3: Int) -> Int { 3 } // expected-note * {{'subscript(_:_:_:)' has been explicitly marked unavailable here}}
@available(*, deprecated, renamed: "subscript(arg1:arg2:arg3:)")
subscript(argg1 argg1: Int, argg2 argg2: Int, argg3 argg3: Int) -> Int { 3 }
@available(*, deprecated, renamed: "subscript(arg1:arg2:arg3:)")
subscript(only1 only1: Int, only2 only2: Int) -> Int { 3 }
subscript(arg1 arg1: Int, arg2 arg2: Int, arg3 arg3: Int) -> Int { 3 }
@available(*, deprecated, renamed: "subscriptTo(_:)")
subscript(to to: Int) -> Int { 3 }
func subscriptTo(_ index: Int) -> Int { 3 }
func testUnavailableSubscripts(_ x: UnavailableSubscripts) {
_ = self[old: 3] // expected-error {{'subscript(old:)' has been renamed to 'subscript(new:)'}} {{14-17=new}}
_ = x[old: 3] // expected-error {{'subscript(old:)' has been renamed to 'subscript(new:)'}} {{11-14=new}}
_ = self.getValue(old: 3) // expected-error {{'getValue(old:)' has been renamed to 'subscript(new:)'}} {{14-22=[}} {{29-30=]}} {{23-26=new}}
_ = getValue(old: 3) // expected-error {{'getValue(old:)' has been renamed to 'subscript(new:)'}} {{9-9=self}} {{9-17=[}} {{24-25=]}} {{18-21=new}}
_ = x.getValue(old: 3) // expected-error {{'getValue(old:)' has been renamed to 'subscript(new:)'}} {{11-19=[}} {{26-27=]}} {{20-23=new}}
_ = self[getAValue: 3] // expected-error {{'subscript(getAValue:)' has been renamed to 'getAValue(new:)'}} {{13-14=.getAValue(}} {{26-27=)}} {{14-23=new}}
_ = x[getAValue: 3] // expected-error {{'subscript(getAValue:)' has been renamed to 'getAValue(new:)'}} {{10-11=.getAValue(}} {{23-24=)}} {{11-20=new}}
_ = self[argg1: 3, argg2: 3, argg3: 3] // expected-warning {{'subscript(argg1:argg2:argg3:)' is deprecated: renamed to 'subscript(arg1:arg2:arg3:)'}} // expected-note {{use 'subscript(arg1:arg2:arg3:)' instead}} {{14-19=arg1}} {{24-29=arg2}} {{34-39=arg3}}
_ = x[argg1: 3, argg2: 3, argg3: 3] // expected-warning {{'subscript(argg1:argg2:argg3:)' is deprecated: renamed to 'subscript(arg1:arg2:arg3:)'}} // expected-note {{use 'subscript(arg1:arg2:arg3:)' instead}} {{11-16=arg1}} {{21-26=arg2}} {{31-36=arg3}}
// Different number of parameters emit no fixit
_ = self[only1: 3, only2: 3] // expected-warning {{'subscript(only1:only2:)' is deprecated: renamed to 'subscript(arg1:arg2:arg3:)'}} // expected-note {{use 'subscript(arg1:arg2:arg3:)' instead}} {{none}}
_ = self[3, 3, 3] // expected-error {{'subscript(_:_:_:)' has been renamed to 'subscript(arg1:arg2:arg3:)'}} {{14-14=arg1: }} {{17-17=arg2: }} {{20-20=arg3: }}
_ = x[3, 3, 3] // expected-error {{'subscript(_:_:_:)' has been renamed to 'subscript(arg1:arg2:arg3:)'}} {{11-11=arg1: }} {{14-14=arg2: }} {{17-17=arg3: }}
_ = self[to: 3] // expected-warning {{'subscript(to:)' is deprecated: renamed to 'subscriptTo(_:)'}} // expected-note {{use 'subscriptTo(_:)' instead}} {{13-14=.subscriptTo(}} {{19-20=)}} {{14-18=}}
_ = x[to: 3] // expected-warning {{'subscript(to:)' is deprecated: renamed to 'subscriptTo(_:)'}} // expected-note {{use 'subscriptTo(_:)' instead}} {{10-11=.subscriptTo(}} {{16-17=)}} {{11-15=}}
}
} | apache-2.0 | fe2fe72dc523f82505a3963c8c424556 | 64.781022 | 338 | 0.693861 | 3.878862 | false | false | false | false |
radex/swift-compiler-crashes | crashes-duplicates/03305-swift-sourcemanager-getmessage.swift | 11 | 2484 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let t: e {
class
protocol A {
protocol A {
{
class
class a {
let t: P
struct S<T : a {
struct S<T>
}
class func a
protocol A : e {
{
return "\() -> (f: a {
{
let t: P
struct S<T>
struct A : a {
func f: e : e
class func g: C {
}
case c,
}
protocol A {
case c<T: e : c,
class
struct A {
return "
class
class c,
}
let i("
typealias e : b: T>: NSObject {
var d where T : c,
return "\(f: a {
case c,
{
struct A : c,
class a<T: P
var d = {
typealias e == {
class
class c,
case c<T>: e {
{
struct A {
var d where g<T>
struct S<T: Int -> U)
func f: T>: NSObject {
protocol A : c,
protocol A : NSObject {
typealias e {
class a {
return "
class
}
let t: C {
}
struct A {
}
protocol P {
protocol P {
return ""
return "
case c<d = "\(f: a {
return "
typealias e == [Void{
class c<T : C {
protocol P {
typealias e : NSObject {
let i() {
let t: e {
let f = [Void{
typealias e {
class b: b: NSObject {
typealias e {
class
let t: T: c {
let i: e
func f: NSObject {
protocol A {
protocol P {
typealias e : e : NSObject {
typealias e == [Void{
class
return "
func a<T : BooleanType, A {
let f = {
let f = [Void{
class
}
let i: c<T: P
class b
return "
}
}
return "
case c<T: T>
protocol A {
class
let i: e == {
class b
protocol P {
struct S<T {
struct S<T: T>: e
class a {
let i("
func i() {
let t: e == {
func f: T>: c {
typealias e {
func i: c<T : a {
return "\("
typealias e {
func g: BooleanType, A : BooleanType, A {
func f: Int -> U))"
func g
typealias e {
class c,
case c,
{
typealias e {
class a {
protocol A {
class
protocol P {
let i: c<T>
func a<T : a {
let t: b
func i: c {
func g<T where g<T : P
struct S<T>: c,
println("
func g<d where T : Int -> U)"[1)))
return "[Void{
protocol P {
class b: b: a {
return "
let t: b: BooleanType, A : a {
case c<T>
protocol P {
let f = [Void{
protocol A : P
println() {
func f: e {
class b
}
struct A {
protocol A : a {
println("
struct A {
protocol P {
}
func g
return "
func i() -> U)"[Void{
struct A {
{
let i: c<T>: b: e : BooleanType, A : P
typealias e {
struct A {
}
{
class c,
let f = "\("
return "
protocol P {
var d where T : C {
typealias e : C {
typealias e : c {
protocol A {
func g
class func g: e == "\() -> () -> U)
func f: a {
let t: c,
class func i() {
{
let i() {
protocol A : a {
struct Q<T : Int -> U)"
class
let f = {
class
case c,
class
struct S<T>: c {
protocol
| mit | e30c5532e2c71a2b22a1678c6cb413ea | 11.9375 | 87 | 0.598631 | 2.53211 | false | false | false | false |
MarvinNazari/ICSPullToRefresh.Swift | ICSPullToRefreshDemo/ViewController.swift | 1 | 2364 | //
// ViewController.swift
// ICSPullToRefreshDemo
//
// Created by LEI on 3/15/15.
// Copyright (c) 2015 TouchingAPP. All rights reserved.
//
import UIKit
import ICSPullToRefresh
class ViewController: UITableViewController {
// lazy var tableView: UITableView = { [unowned self] in
// let tableView = UITableView(frame: self.view.bounds, style: .Plain)
// return tableView
// }()
var k = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// view.addSubview(tableView)
tableView.dataSource = self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
tableView.addPullToRefreshHandler {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
sleep(3)
self.k = 0;
dispatch_async(dispatch_get_main_queue(), { () -> Void in
tableView.pullToRefreshView?.stopAnimating()
})
})
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64) (1 * NSEC_PER_SEC) ), dispatch_get_main_queue()) { () -> Void in
self.tableView.triggerPullToRefresh()
}
tableView.addInfiniteScrollingWithHandler {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
sleep(3)
dispatch_async(dispatch_get_main_queue(), { [unowned self] in
self.k += 1
self.tableView.reloadData()
self.tableView.infiniteScrollingView?.stopAnimating()
})
})
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10 + 4 * k
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = "cell"
var cell = tableView.dequeueReusableCellWithIdentifier(identifier)
if cell == nil{
cell = UITableViewCell(style: .Value1, reuseIdentifier: identifier)
}
cell!.textLabel?.text = "Test"
return cell!
}
}
| mit | 5d195c8d94641e8863210e6351e77c99 | 31.383562 | 128 | 0.586717 | 4.775758 | false | false | false | false |
linchaosheng/CSSwiftWB | SwiftCSWB/SwiftCSWB/Class/Home/C/WBPresentationController.swift | 1 | 1522 | //
// WBPresentationController.swift
// SwiftCSWB
//
// Created by LCS on 16/4/24.
// Copyright © 2016年 Apple. All rights reserved.
//
import UIKit
class WBPresentationController: UIPresentationController {
override init(presentedViewController: UIViewController, presentingViewController: UIViewController) {
super.init(presentedViewController: presentedViewController, presentingViewController: presentingViewController)
}
/*
containerView : 容器视图 (存放被展示的视图)
presentedView : 被展示的视图 (modal出来的控制器view)
*/
override func containerViewWillLayoutSubviews(){
let W = CGFloat(100)
let H = CGFloat(200)
let X = UIScreen.mainScreen().bounds.size.width * 0.5 - W * 0.5
let Y = CGFloat(64)
presentedView()?.frame = CGRect(x: X, y: Y, width: W, height: H)
// 创建蒙板
let maskView = UIView()
maskView.backgroundColor = UIColor.blackColor()
maskView.alpha = 0.1
maskView.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height)
let tap = UITapGestureRecognizer(target: self, action: "maskViewOnClick")
maskView.addGestureRecognizer(tap)
containerView?.insertSubview(maskView, belowSubview: presentedView()!)
}
func maskViewOnClick(){
presentedViewController.dismissViewControllerAnimated(true, completion: nil)
}
}
| apache-2.0 | e427dc79b7ba73c180f349ed873c2b5f | 33.833333 | 131 | 0.671907 | 4.796721 | false | false | false | false |
qutheory/vapor | Sources/Vapor/Utilities/String+IsIPAddress.swift | 2 | 373 | extension String {
func isIPAddress() -> Bool {
// We need some scratch space to let inet_pton write into.
var ipv4Addr = in_addr()
var ipv6Addr = in6_addr()
return self.withCString { ptr in
return inet_pton(AF_INET, ptr, &ipv4Addr) == 1 ||
inet_pton(AF_INET6, ptr, &ipv6Addr) == 1
}
}
}
| mit | a811f5717bc4d3420f86d6629aadf08f | 30.083333 | 66 | 0.530831 | 3.693069 | false | false | false | false |
jverdi/URLQueue | URLQueue/URLListViewController.swift | 1 | 3875 | //
// FirstViewController.swift
// URLQueue
//
// Created by Jared Verdi on 6/9/14.
// Copyright (c) 2014 Eesel LLC. All rights reserved.
//
import Foundation
import UIKit
import URLQueueKit
class URLListViewController: UITableViewController {
var urlQueue : Dictionary<String,String> = [:]
var urlStrings : [String] = []
var titles : [String] = []
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = editButtonItem()
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: "reload", forControlEvents: .ValueChanged)
reload()
}
func reload() {
self.editing = false
urlQueue = URLQueue.urlStrings()
if urlQueue.count > 0 {
urlStrings = Array(urlQueue.keys)
titles = Array(urlQueue.values)
}
self.tableView.reloadData()
refreshControl?.endRefreshing()
}
func canOpenURLInChrome(url:NSURL) -> Bool {
return (url.scheme! == "https" || url.scheme! == "http")
&& UIApplication.sharedApplication().canOpenURL(NSURL(string:"googlechrome://")!)
}
func openURLInChrome(url:NSURL) {
let chromeScheme = url.scheme == "https" ? "googlechromes" : "googlechrome"
if let absoluteString = url.absoluteString {
if let rangeForScheme = absoluteString.rangeOfString(":") {
let urlNoScheme = absoluteString.substringFromIndex(rangeForScheme.startIndex)
let chromeURLString = chromeScheme.stringByAppendingString(urlNoScheme)
if let chromeURL = NSURL(string:chromeURLString) {
UIApplication.sharedApplication().openURL(chromeURL)
}
}
}
}
func openURLInSafari(url:NSURL) {
UIApplication.sharedApplication().openURL(url)
}
func removeByIndexPath(indexPath: NSIndexPath) {
urlQueue.removeValueForKey(urlStrings[indexPath.row])
urlStrings.removeAtIndex(indexPath.row)
titles.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
URLQueue.saveURLs(urlQueue)
}
// MARK: UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return urlStrings.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("URLCellIdentifier", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = titles[indexPath.row]
cell.detailTextLabel?.text = urlStrings[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return editing
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
removeByIndexPath(indexPath)
}
// MARK: UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let url = NSURL(string:urlStrings[indexPath.row])
switch URLQueue.preferredBrowser() {
case "Chrome" where canOpenURLInChrome(url!):
openURLInChrome(url!)
default:
openURLInSafari(url!)
}
// remove from the queue once we open the URL
removeByIndexPath(indexPath)
}
}
| mit | f96192b91635c4e6fdbd36a5371d2c17 | 32.119658 | 157 | 0.641548 | 5.344828 | false | false | false | false |
narner/AudioKit | Examples/macOS/MIDIUtility/MIDIUtility/MIDISendVC.swift | 1 | 4679 | //
// MIDISendVC.swift
// MIDIUtility
//
// Created by Jeff Cooper on 9/13/17.
// Copyright © 2017 AudioKit. All rights reserved.
//
import Foundation
import AudioKit
import Cocoa
class MIDISenderVC: NSViewController {
let midiOut = AKMIDI()
@IBOutlet var noteNumField: NSTextField!
@IBOutlet var noteVelField: NSTextField!
@IBOutlet var noteChanField: NSTextField!
@IBOutlet var ccField: NSTextField!
@IBOutlet var ccValField: NSTextField!
@IBOutlet var ccChanField: NSTextField!
@IBOutlet var sysexField: NSTextView!
var noteToSend: Int? {
return Int(noteNumField.stringValue)
}
var velocityToSend: Int? {
return Int(noteVelField.stringValue)
}
var noteChanToSend: Int {
if Int(noteChanField.stringValue) == nil {
return 1
}
return Int(noteChanField.stringValue)! - 1
}
var ccToSend: Int? {
return Int(ccField.stringValue)
}
var ccValToSend: Int? {
return Int(ccValField.stringValue)
}
var ccChanToSend: Int {
if Int(ccChanField.stringValue) == nil {
return 1
}
return Int(ccChanField.stringValue)! - 1
}
var sysexToSend: [Int]? {
var data = [Int]()
let splitField = sysexField.string.components(separatedBy: " ")
for entry in splitField {
let intVal = Int(entry)
if intVal != nil && intVal! <= 247 && intVal! > -1 {
data.append(intVal!)
}
}
return data
}
override func viewDidLoad() {
midiOut.openOutput()
}
@IBAction func sendNotePressed(_ sender: NSButton) {
if noteToSend != nil && velocityToSend != nil {
Swift.print("sending note: \(noteToSend!) - \(velocityToSend!)")
let event = AKMIDIEvent(noteOn: MIDINoteNumber(noteToSend!), velocity: MIDIVelocity(velocityToSend!), channel: MIDIChannel(noteChanToSend))
midiOut.sendEvent(event)
} else {
print("error w note fields")
}
}
@IBAction func sendCCPressed(_ sender: NSButton) {
if ccToSend != nil && ccValToSend != nil {
Swift.print("sending cc: \(ccToSend!) - \(ccValToSend!)")
let event = AKMIDIEvent(controllerChange: MIDIByte(ccToSend!), value: MIDIByte(ccValToSend!), channel: MIDIChannel(ccChanToSend))
midiOut.sendEvent(event)
} else {
print("error w cc fields")
}
}
@IBAction func sendSysexPressed(_ sender: NSButton) {
if sysexToSend != nil {
var midiBytes = [MIDIByte]()
for byte in sysexToSend! {
midiBytes.append(MIDIByte(byte))
}
if midiBytes[0] != 240 || midiBytes.last != 247 || midiBytes.count < 2 {
Swift.print("bad sysex data - must start with 240 and end with 247")
Swift.print("parsed sysex: \(sysexToSend!)")
return
}
Swift.print("sending sysex \(sysexToSend!)")
let event = AKMIDIEvent(data: midiBytes)
midiOut.sendEvent(event)
} else {
print("error w sysex field")
}
}
}
class MIDIChannelFormatter: NumberFormatter {
override func isPartialStringValid(_ partialStringPtr: AutoreleasingUnsafeMutablePointer<NSString>, proposedSelectedRange proposedSelRangePtr: NSRangePointer?, originalString origString: String, originalSelectedRange origSelRange: NSRange, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
let partialStr = partialStringPtr.pointee
let charset = CharacterSet(charactersIn: "0123456789").inverted
let result = partialStr.rangeOfCharacter(from: charset)
if result.length > 0 || partialStr.intValue > 16 || partialStr == "0" || partialStr.length > 2 {
return false
}
return true
}
}
class MIDINumberFormatter: NumberFormatter {
override func isPartialStringValid(_ partialStringPtr: AutoreleasingUnsafeMutablePointer<NSString>, proposedSelectedRange proposedSelRangePtr: NSRangePointer?, originalString origString: String, originalSelectedRange origSelRange: NSRange, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
let partialStr = partialStringPtr.pointee
let charset = CharacterSet(charactersIn: "0123456789").inverted
let result = partialStr.rangeOfCharacter(from: charset)
if result.length > 0 || partialStr.intValue > 127 || partialStr == "0000" || partialStr.length > 3 {
return false
}
return true
}
}
| mit | 043515772ee1d314828fb28a8e00edfe | 37.344262 | 324 | 0.63339 | 4.654726 | false | false | false | false |
szpnygo/firefox-ios | Utils/WeakList.swift | 23 | 1868 | /* 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
/**
* A list that weakly holds references to its items.
* Note that while the references themselves are cleared, their wrapper objects
* are not (though they are reused). Also note that since slots are reused,
* order is not preserved.
*
* This class crashes at runtime with EXC_BAD_ACCESS if a protocol is given as
* the type T. Make sure to use a class type.
*/
public class WeakList<T: AnyObject>: SequenceType {
private var items = [WeakRef<T>]()
public init() {}
/**
* Adds an item to the list.
* Note that every insertion iterates through the list to find any "holes" (items that have
* been deallocated) to reuse them, so this class may not be appropriate in situations where
* insertion is frequent.
*/
public func insert(item: T) {
for wrapper in items {
// Reuse any existing slots that have been deallocated.
if wrapper.value == nil {
wrapper.value = item
return
}
}
items.append(WeakRef(item))
}
public func generate() -> GeneratorOf<T> {
var index = 0
return GeneratorOf<T> {
if index >= self.items.count {
return nil
}
for i in index..<self.items.count {
if let value = self.items[i].value {
index = i + 1
return value
}
}
index = self.items.count
return nil
}
}
}
private class WeakRef<T: AnyObject> {
weak var value: T?
init(_ value: T) {
self.value = value
}
} | mpl-2.0 | b94b105a2ff41ec26bb706ebf35a0755 | 27.318182 | 96 | 0.578694 | 4.395294 | false | false | false | false |
mfekadu/TabBarIGListKitMagic | TabBarIGListKitMagic/List/ListRouter.swift | 1 | 2043 | //
// ListRouter.swift
// TabBarIGListKitMagic
//
// Created by Michael Fekadu on 6/21/17.
// Copyright (c) 2017 mikes. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import UIKit
protocol ListRouterInput
{
func navigateToSomewhere()
}
class ListRouter: ListRouterInput
{
weak var viewController: ListViewController!
// MARK: - Navigation
func navigateToSomewhere()
{
// NOTE: Teach the router how to navigate to another scene. Some examples follow:
// 1. Trigger a storyboard segue
// viewController.performSegueWithIdentifier("ShowSomewhereScene", sender: nil)
// 2. Present another view controller programmatically
// viewController.presentViewController(someWhereViewController, animated: true, completion: nil)
// 3. Ask the navigation controller to push another view controller onto the stack
// viewController.navigationController?.pushViewController(someWhereViewController, animated: true)
// 4. Present a view controller from a different storyboard
// let storyboard = UIStoryboard(name: "OtherThanMain", bundle: nil)
// let someWhereViewController = storyboard.instantiateInitialViewController() as! SomeWhereViewController
// viewController.navigationController?.pushViewController(someWhereViewController, animated: true)
}
// MARK: - Communication
func passDataToNextScene(segue: UIStoryboardSegue)
{
// NOTE: Teach the router which scenes it can communicate with
if segue.identifier == "ShowSomewhereScene" {
passDataToSomewhereScene(segue: segue)
}
}
func passDataToSomewhereScene(segue: UIStoryboardSegue)
{
// NOTE: Teach the router how to pass data to the next scene
// let someWhereViewController = segue.destinationViewController as! SomeWhereViewController
// someWhereViewController.output.name = viewController.output.name
}
}
| mit | 35826d62c468bc9fcf757a93e0d72691 | 31.951613 | 110 | 0.739599 | 5.238462 | false | false | false | false |
hughbe/swift | test/SourceKit/SyntaxMapData/syntaxmap-partial-delete.swift | 1 | 1769 | // RUN: %sourcekitd-test -req=open -print-raw-response %S/Inputs/syntaxmap-partial-delete.swift == -req=edit -print-raw-response -pos=2:10 -length=2 -replace='' %S/Inputs/syntaxmap-partial-delete.swift | %sed_clean > %t.response
// RUN: %FileCheck -input-file=%t.response %s
// CHECK: {{^}}{
// CHECK-NEXT: key.offset: 0,
// CHECK-NEXT: key.length: 13,
// CHECK-NEXT: key.diagnostic_stage: source.diagnostic.stage.swift.parse,
// CHECK-NEXT: key.syntaxmap: [
// CHECK-NEXT: {
// CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.keyword,
// CHECK-NEXT: key.offset: 1,
// CHECK-NEXT: key.length: 3
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier,
// CHECK-NEXT: key.offset: 5,
// CHECK-NEXT: key.length: 1
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.number,
// CHECK-NEXT: key.offset: 9,
// CHECK-NEXT: key.length: 3
// CHECK-NEXT: }
// CHECK-NEXT: ],
// After removing 2 chars from number literal
// CHECK: {{^}}{
// CHECK-NEXT: key.offset: 1,
// CHECK-NEXT: key.length: 10,
// CHECK-NEXT: key.diagnostic_stage: source.diagnostic.stage.swift.parse,
// CHECK-NEXT: key.syntaxmap: [
// CHECK-NEXT: {
// CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.keyword,
// CHECK-NEXT: key.offset: 1,
// CHECK-NEXT: key.length: 3
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier,
// CHECK-NEXT: key.offset: 5,
// CHECK-NEXT: key.length: 1
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.number,
// CHECK-NEXT: key.offset: 9,
// CHECK-NEXT: key.length: 1
// CHECK-NEXT: }
// CHECK-NEXT: ],
| apache-2.0 | d558c0796e42bd342d81cbcdb1b76360 | 35.102041 | 228 | 0.637083 | 2.871753 | false | false | true | false |
matthewpurcell/firefox-ios | Client/Frontend/Home/ReaderPanel.swift | 1 | 22587 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import SnapKit
import Storage
import ReadingList
import Shared
import XCGLogger
private let log = Logger.browserLogger
private struct ReadingListTableViewCellUX {
static let RowHeight: CGFloat = 86
static let ActiveTextColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0)
static let DimmedTextColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.44)
static let ReadIndicatorWidth: CGFloat = 12 // image width
static let ReadIndicatorHeight: CGFloat = 12 // image height
static let ReadIndicatorTopOffset: CGFloat = 36.75 // half of the cell - half of the height of the asset
static let ReadIndicatorLeftOffset: CGFloat = 18
static let ReadAccessibilitySpeechPitch: Float = 0.7 // 1.0 default, 0.0 lowest, 2.0 highest
static let TitleLabelTopOffset: CGFloat = 14 - 4
static let TitleLabelLeftOffset: CGFloat = 16 + 16 + 16
static let TitleLabelRightOffset: CGFloat = -40
static let HostnameLabelBottomOffset: CGFloat = 11
static let DeleteButtonBackgroundColor = UIColor(rgb: 0xef4035)
static let DeleteButtonTitleColor = UIColor.whiteColor()
static let DeleteButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4)
static let MarkAsReadButtonBackgroundColor = UIColor(rgb: 0x2193d1)
static let MarkAsReadButtonTitleColor = UIColor.whiteColor()
static let MarkAsReadButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4)
// Localizable strings
static let DeleteButtonTitleText = NSLocalizedString("Remove", comment: "Title for the button that removes a reading list item")
static let MarkAsReadButtonTitleText = NSLocalizedString("Mark as Read", comment: "Title for the button that marks a reading list item as read")
static let MarkAsUnreadButtonTitleText = NSLocalizedString("Mark as Unread", comment: "Title for the button that marks a reading list item as unread")
}
private struct ReadingListPanelUX {
// Welcome Screen
static let WelcomeScreenTopPadding: CGFloat = 16
static let WelcomeScreenPadding: CGFloat = 15
static let WelcomeScreenHeaderTextColor = UIColor.darkGrayColor()
static let WelcomeScreenItemTextColor = UIColor.grayColor()
static let WelcomeScreenItemWidth = 220
static let WelcomeScreenItemOffset = -20
static let WelcomeScreenCircleWidth = 40
static let WelcomeScreenCircleOffset = 20
static let WelcomeScreenCircleSpacer = 10
}
class ReadingListTableViewCell: SWTableViewCell {
var title: String = "Example" {
didSet {
titleLabel.text = title
updateAccessibilityLabel()
}
}
var url: NSURL = NSURL(string: "http://www.example.com")! {
didSet {
hostnameLabel.text = simplifiedHostnameFromURL(url)
updateAccessibilityLabel()
}
}
var unread: Bool = true {
didSet {
readStatusImageView.image = UIImage(named: unread ? "MarkAsRead" : "MarkAsUnread")
titleLabel.textColor = unread ? ReadingListTableViewCellUX.ActiveTextColor : ReadingListTableViewCellUX.DimmedTextColor
hostnameLabel.textColor = unread ? ReadingListTableViewCellUX.ActiveTextColor : ReadingListTableViewCellUX.DimmedTextColor
markAsReadButton.setTitle(unread ? ReadingListTableViewCellUX.MarkAsReadButtonTitleText : ReadingListTableViewCellUX.MarkAsUnreadButtonTitleText, forState: UIControlState.Normal)
if let text = markAsReadButton.titleLabel?.text {
markAsReadAction.name = text
}
updateAccessibilityLabel()
}
}
private var deleteAction: UIAccessibilityCustomAction!
private var markAsReadAction: UIAccessibilityCustomAction!
let readStatusImageView: UIImageView!
let titleLabel: UILabel!
let hostnameLabel: UILabel!
let deleteButton: UIButton!
let markAsReadButton: UIButton!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
readStatusImageView = UIImageView()
titleLabel = UILabel()
hostnameLabel = UILabel()
deleteButton = UIButton()
markAsReadButton = UIButton()
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = UIColor.clearColor()
separatorInset = UIEdgeInsets(top: 0, left: 48, bottom: 0, right: 0)
layoutMargins = UIEdgeInsetsZero
preservesSuperviewLayoutMargins = false
contentView.addSubview(readStatusImageView)
readStatusImageView.contentMode = UIViewContentMode.ScaleAspectFit
readStatusImageView.snp_makeConstraints { (make) -> () in
make.width.equalTo(ReadingListTableViewCellUX.ReadIndicatorWidth)
make.height.equalTo(ReadingListTableViewCellUX.ReadIndicatorHeight)
make.top.equalTo(self.contentView).offset(ReadingListTableViewCellUX.ReadIndicatorTopOffset)
make.left.equalTo(self.contentView).offset(ReadingListTableViewCellUX.ReadIndicatorLeftOffset)
}
contentView.addSubview(titleLabel)
contentView.addSubview(hostnameLabel)
titleLabel.textColor = ReadingListTableViewCellUX.ActiveTextColor
titleLabel.numberOfLines = 2
titleLabel.snp_makeConstraints { (make) -> () in
make.top.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelTopOffset)
make.left.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelLeftOffset)
make.right.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelRightOffset) // TODO Not clear from ux spec
make.bottom.lessThanOrEqualTo(hostnameLabel.snp_top).priorityHigh()
}
hostnameLabel.textColor = ReadingListTableViewCellUX.ActiveTextColor
hostnameLabel.numberOfLines = 1
hostnameLabel.snp_makeConstraints { (make) -> () in
make.bottom.equalTo(self.contentView).offset(-ReadingListTableViewCellUX.HostnameLabelBottomOffset)
make.left.right.equalTo(self.titleLabel)
}
deleteButton.backgroundColor = ReadingListTableViewCellUX.DeleteButtonBackgroundColor
deleteButton.titleLabel?.textColor = ReadingListTableViewCellUX.DeleteButtonTitleColor
deleteButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
deleteButton.titleLabel?.textAlignment = NSTextAlignment.Center
deleteButton.setTitle(ReadingListTableViewCellUX.DeleteButtonTitleText, forState: UIControlState.Normal)
deleteButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
deleteButton.titleEdgeInsets = ReadingListTableViewCellUX.DeleteButtonTitleEdgeInsets
deleteAction = UIAccessibilityCustomAction(name: ReadingListTableViewCellUX.DeleteButtonTitleText, target: self, selector: "deleteActionActivated")
rightUtilityButtons = [deleteButton]
markAsReadButton.backgroundColor = ReadingListTableViewCellUX.MarkAsReadButtonBackgroundColor
markAsReadButton.titleLabel?.textColor = ReadingListTableViewCellUX.MarkAsReadButtonTitleColor
markAsReadButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
markAsReadButton.titleLabel?.textAlignment = NSTextAlignment.Center
markAsReadButton.setTitle(ReadingListTableViewCellUX.MarkAsReadButtonTitleText, forState: UIControlState.Normal)
markAsReadButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
markAsReadButton.titleEdgeInsets = ReadingListTableViewCellUX.MarkAsReadButtonTitleEdgeInsets
markAsReadAction = UIAccessibilityCustomAction(name: ReadingListTableViewCellUX.MarkAsReadButtonTitleText, target: self, selector: "markAsReadActionActivated")
leftUtilityButtons = [markAsReadButton]
accessibilityCustomActions = [deleteAction, markAsReadAction]
setupDynamicFonts()
}
func setupDynamicFonts() {
titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFont
hostnameLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight
deleteButton.titleLabel?.font = DynamicFontHelper.defaultHelper.DeviceFontLight
markAsReadButton.titleLabel?.font = DynamicFontHelper.defaultHelper.DeviceFontLight
}
override func prepareForReuse() {
super.prepareForReuse()
setupDynamicFonts()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let prefixesToSimplify = ["www.", "mobile.", "m.", "blog."]
private func simplifiedHostnameFromURL(url: NSURL) -> String {
let hostname = url.host ?? ""
for prefix in prefixesToSimplify {
if hostname.hasPrefix(prefix) {
return hostname.substringFromIndex(hostname.startIndex.advancedBy(prefix.characters.count))
}
}
return hostname
}
@objc private func markAsReadActionActivated() -> Bool {
self.delegate?.swipeableTableViewCell?(self, didTriggerLeftUtilityButtonWithIndex: 0)
return true
}
@objc private func deleteActionActivated() -> Bool {
self.delegate?.swipeableTableViewCell?(self, didTriggerRightUtilityButtonWithIndex: 0)
return true
}
private func updateAccessibilityLabel() {
if let hostname = hostnameLabel.text,
title = titleLabel.text {
let unreadStatus = unread ? NSLocalizedString("unread", comment: "Accessibility label for unread article in reading list. It's a past participle - functions as an adjective.") : NSLocalizedString("read", comment: "Accessibility label for read article in reading list. It's a past participle - functions as an adjective.")
let string = "\(title), \(unreadStatus), \(hostname)"
var label: AnyObject
if !unread {
// mimic light gray visual dimming by "dimming" the speech by reducing pitch
let lowerPitchString = NSMutableAttributedString(string: string as String)
lowerPitchString.addAttribute(UIAccessibilitySpeechAttributePitch, value: NSNumber(float: ReadingListTableViewCellUX.ReadAccessibilitySpeechPitch), range: NSMakeRange(0, lowerPitchString.length))
label = NSAttributedString(attributedString: lowerPitchString)
} else {
label = string
}
// need to use KVC as accessibilityLabel is of type String! and cannot be set to NSAttributedString other way than this
// see bottom of page 121 of the PDF slides of WWDC 2012 "Accessibility for iOS" session for indication that this is OK by Apple
// also this combined with Swift's strictness is why we cannot simply override accessibilityLabel and return the label directly...
setValue(label, forKey: "accessibilityLabel")
}
}
}
class ReadingListPanel: UITableViewController, HomePanel, SWTableViewCellDelegate {
weak var homePanelDelegate: HomePanelDelegate? = nil
var profile: Profile!
private lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverview()
private var records: [ReadingListClientRecord]?
init() {
super.init(nibName: nil, bundle: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationFirefoxAccountChanged, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationDynamicFontChanged, object: nil)
}
required init!(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.accessibilityIdentifier = "ReadingTable"
tableView.rowHeight = ReadingListTableViewCellUX.RowHeight
tableView.separatorInset = UIEdgeInsetsZero
tableView.layoutMargins = UIEdgeInsetsZero
tableView.separatorColor = UIConstants.SeparatorColor
tableView.registerClass(ReadingListTableViewCell.self, forCellReuseIdentifier: "ReadingListTableViewCell")
// Set an empty footer to prevent empty cells from appearing in the list.
tableView.tableFooterView = UIView()
view.backgroundColor = UIConstants.PanelBackgroundColor
if let result = profile.readingList?.getAvailableRecords() where result.isSuccess {
records = result.successValue
// If no records have been added yet, we display the empty state
if records?.count == 0 {
tableView.scrollEnabled = false
view.addSubview(emptyStateOverlayView)
}
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationDynamicFontChanged, object: nil)
}
func notificationReceived(notification: NSNotification) {
switch notification.name {
case NotificationFirefoxAccountChanged:
refreshReadingList()
break
case NotificationDynamicFontChanged:
if emptyStateOverlayView.superview != nil {
emptyStateOverlayView.removeFromSuperview()
}
emptyStateOverlayView = createEmptyStateOverview()
refreshReadingList()
break
default:
// no need to do anything at all
log.warning("Received unexpected notification \(notification.name)")
break
}
}
func refreshReadingList() {
let prevNumberOfRecords = records?.count
if let result = profile.readingList?.getAvailableRecords() where result.isSuccess {
records = result.successValue
if records?.count == 0 {
tableView.scrollEnabled = false
if emptyStateOverlayView.superview == nil {
view.addSubview(emptyStateOverlayView)
}
} else {
if prevNumberOfRecords == 0 {
tableView.scrollEnabled = true
emptyStateOverlayView.removeFromSuperview()
}
}
self.tableView.reloadData()
}
}
private func createEmptyStateOverview() -> UIView {
let overlayView = UIScrollView(frame: tableView.bounds)
overlayView.backgroundColor = UIColor.whiteColor()
// Unknown why this does not work with autolayout
overlayView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth]
let containerView = UIView()
overlayView.addSubview(containerView)
let logoImageView = UIImageView(image: UIImage(named: "ReadingListEmptyPanel"))
containerView.addSubview(logoImageView)
logoImageView.snp_makeConstraints { make in
make.centerX.equalTo(containerView)
make.centerY.lessThanOrEqualTo(overlayView.snp_centerY).priorityHigh()
// Sets proper top constraint for iPhone 6 in portait and iPads.
make.centerY.equalTo(overlayView.snp_centerY).offset(HomePanelUX.EmptyTabContentOffset).priorityMedium()
// Sets proper top constraint for iPhone 4, 5 in portrait.
make.top.greaterThanOrEqualTo(overlayView.snp_top).offset(50).priorityHigh()
}
let welcomeLabel = UILabel()
containerView.addSubview(welcomeLabel)
welcomeLabel.text = NSLocalizedString("Welcome to your Reading List", comment: "See http://mzl.la/1LXbDOL")
welcomeLabel.textAlignment = NSTextAlignment.Center
welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallBold
welcomeLabel.textColor = ReadingListPanelUX.WelcomeScreenHeaderTextColor
welcomeLabel.adjustsFontSizeToFitWidth = true
welcomeLabel.snp_makeConstraints { make in
make.centerX.equalTo(containerView)
make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth + ReadingListPanelUX.WelcomeScreenCircleSpacer + ReadingListPanelUX.WelcomeScreenCircleWidth)
make.top.equalTo(logoImageView.snp_bottom).offset(ReadingListPanelUX.WelcomeScreenPadding)
// Sets proper center constraint for iPhones in landscape.
make.centerY.lessThanOrEqualTo(overlayView.snp_centerY).offset(-40).priorityHigh()
}
let readerModeLabel = UILabel()
containerView.addSubview(readerModeLabel)
readerModeLabel.text = NSLocalizedString("Open articles in Reader View by tapping the book icon when it appears in the title bar.", comment: "See http://mzl.la/1LXbDOL")
readerModeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight
readerModeLabel.textColor = ReadingListPanelUX.WelcomeScreenItemTextColor
readerModeLabel.numberOfLines = 0
readerModeLabel.snp_makeConstraints { make in
make.top.equalTo(welcomeLabel.snp_bottom).offset(ReadingListPanelUX.WelcomeScreenPadding)
make.left.equalTo(welcomeLabel.snp_left)
make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth)
}
let readerModeImageView = UIImageView(image: UIImage(named: "ReaderModeCircle"))
containerView.addSubview(readerModeImageView)
readerModeImageView.snp_makeConstraints { make in
make.centerY.equalTo(readerModeLabel)
make.right.equalTo(welcomeLabel.snp_right)
}
let readingListLabel = UILabel()
containerView.addSubview(readingListLabel)
readingListLabel.text = NSLocalizedString("Save pages to your Reading List by tapping the book plus icon in the Reader View controls.", comment: "See http://mzl.la/1LXbDOL")
readingListLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight
readingListLabel.textColor = ReadingListPanelUX.WelcomeScreenItemTextColor
readingListLabel.numberOfLines = 0
readingListLabel.snp_makeConstraints { make in
make.top.equalTo(readerModeLabel.snp_bottom).offset(ReadingListPanelUX.WelcomeScreenPadding)
make.left.equalTo(welcomeLabel.snp_left)
make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth)
make.bottom.equalTo(overlayView).offset(-20) // making AutoLayout compute the overlayView's contentSize
}
let readingListImageView = UIImageView(image: UIImage(named: "AddToReadingListCircle"))
containerView.addSubview(readingListImageView)
readingListImageView.snp_makeConstraints { make in
make.centerY.equalTo(readingListLabel)
make.right.equalTo(welcomeLabel.snp_right)
}
containerView.snp_makeConstraints { make in
// Let the container wrap around the content
make.top.equalTo(logoImageView.snp_top)
make.left.equalTo(welcomeLabel).offset(ReadingListPanelUX.WelcomeScreenItemOffset)
make.right.equalTo(welcomeLabel).offset(ReadingListPanelUX.WelcomeScreenCircleOffset)
// And then center it in the overlay view that sits on top of the UITableView
make.centerX.equalTo(overlayView)
}
return overlayView
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return records?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ReadingListTableViewCell", forIndexPath: indexPath) as! ReadingListTableViewCell
cell.delegate = self
if let record = records?[indexPath.row] {
cell.title = record.title
cell.url = NSURL(string: record.url)!
cell.unread = record.unread
}
return cell
}
func swipeableTableViewCell(cell: SWTableViewCell!, didTriggerLeftUtilityButtonWithIndex index: Int) {
if let cell = cell as? ReadingListTableViewCell {
cell.hideUtilityButtonsAnimated(true)
if let indexPath = tableView.indexPathForCell(cell), record = records?[indexPath.row] {
if let result = profile.readingList?.updateRecord(record, unread: !record.unread) where result.isSuccess {
// TODO This is a bit odd because the success value of the update is an optional optional Record
if let successValue = result.successValue, updatedRecord = successValue {
records?[indexPath.row] = updatedRecord
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
}
}
}
func swipeableTableViewCell(cell: SWTableViewCell!, didTriggerRightUtilityButtonWithIndex index: Int) {
if let cell = cell as? ReadingListTableViewCell, indexPath = tableView.indexPathForCell(cell), record = records?[indexPath.row] {
if let result = profile.readingList?.deleteRecord(record) where result.isSuccess {
records?.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
// reshow empty state if no records left
if records?.count == 0 {
view.addSubview(emptyStateOverlayView)
}
}
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
if let record = records?[indexPath.row], encodedURL = ReaderModeUtils.encodeURL(NSURL(string: record.url)!) {
// Mark the item as read
profile.readingList?.updateRecord(record, unread: false)
// Reading list items are closest in concept to bookmarks.
let visitType = VisitType.Bookmark
homePanelDelegate?.homePanel(self, didSelectURL: encodedURL, visitType: visitType)
}
}
}
| mpl-2.0 | 044bcab4c969324781cc75f3caba34c2 | 47.678879 | 333 | 0.70607 | 5.920577 | false | false | false | false |
emilgras/EGMenuBar | Example/Pods/EGMenuBar/EGMenuBar/Classes/EGMenuBar.swift | 1 | 12146 | //
// EGMenuBar.swift
// EGMenuBarExample
//
// Created by Emil Gräs on 21/10/2016.
// Copyright © 2016 Emil Gräs. All rights reserved.
//
import UIKit
public protocol EGMenuBarDatasource: class {
func numberOfItems() -> Int
func itemImages() -> [UIImage]
func itemTitles() -> [String]
}
public protocol EGMenuBarDelegate: class {
func didSelectItemAtIndex(_ menuView: EGMenuBar, index: Int)
func interItemSpacing(_ menuView: EGMenuBar) -> Double // TODO: Make this optional
func itemHeight(_ menuView: EGMenuBar) -> Double
}
open class EGMenuBar: UIView {
// MARK: - Public Properties
var itemHeight: CGFloat = 30
var interItemSpacing: CGFloat = 10
var menuHeight: CGFloat!
var menuWidth: CGFloat!
var menuBackgroundColor: UIColor = .white // TODO: Should be read/write
// MARK: - Public Methods
open func show() {
UIView.animate(withDuration: 0.4, animations: {
self.alpha = 1
self.transform = CGAffineTransform.identity
})
UIView.animate(withDuration: 0.7, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.9, options: UIViewAnimationOptions(), animations: {
let item = self.items[0]
let constraint = self.itemCenterYConstraints[0]
constraint.constant = 0
item?.alpha = 1
item?.transform = CGAffineTransform.identity
self.layoutIfNeeded()
}, completion: nil)
UIView.animate(withDuration: 0.7, delay: 0.1, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.9, options: UIViewAnimationOptions(), animations: {
let item = self.items[1]
let constraint = self.itemCenterYConstraints[1]
constraint.constant = 0
item?.alpha = 1
item?.transform = CGAffineTransform.identity
self.layoutIfNeeded()
}, completion: nil)
UIView.animate(withDuration: 0.7, delay: 0.2, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.9, options: UIViewAnimationOptions(), animations: {
let item = self.items[2]
let constraint = self.itemCenterYConstraints[2]
constraint.constant = 0
item?.alpha = 1
item?.transform = CGAffineTransform.identity
self.layoutIfNeeded()
}, completion: nil)
UIView.animate(withDuration: 0.7, delay: 0.3, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.9, options: UIViewAnimationOptions(), animations: {
let item = self.items[3]
let constraint = self.itemCenterYConstraints[3]
constraint.constant = 0
item?.alpha = 1
item?.transform = CGAffineTransform.identity
self.layoutIfNeeded()
}, completion: nil)
}
open func hide() {
UIView.animate(withDuration: 0.3, delay: 0.1, options: UIViewAnimationOptions(), animations: {
self.alpha = 0
}, completion: nil)
UIView.animate(withDuration: 0.4, delay: 0.0, options: UIViewAnimationOptions(), animations: {
let scale = CGAffineTransform(scaleX: 0.9, y: 0.9)
let transform = scale.translatedBy(x: 0, y: 15)
self.transform = transform
}, completion: nil)
UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.9, options: UIViewAnimationOptions(), animations: {
let item = self.items[3]
let constraint = self.itemCenterYConstraints[3]
constraint.constant = 100
item?.alpha = 0
item?.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
self.layoutIfNeeded()
}, completion: nil)
UIView.animate(withDuration: 0.7, delay: 0.05, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.9, options: UIViewAnimationOptions(), animations: {
let item = self.items[2]
let constraint = self.itemCenterYConstraints[2]
constraint.constant = 100
item?.alpha = 0
item?.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
self.layoutIfNeeded()
}, completion: nil)
UIView.animate(withDuration: 0.6, delay: 0.1, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.9, options: UIViewAnimationOptions(), animations: {
let item = self.items[1]
let constraint = self.itemCenterYConstraints[1]
constraint.constant = 100
item?.alpha = 0
item?.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
self.layoutIfNeeded()
}, completion: nil)
UIView.animate(withDuration: 0.5, delay: 0.15, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.9, options: UIViewAnimationOptions(), animations: {
let item = self.items[0]
let constraint = self.itemCenterYConstraints[0]
constraint.constant = 100
item?.alpha = 0
item?.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
self.layoutIfNeeded()
}, completion: nil)
}
/// not used yet
func itemSelected(_ completion: @escaping (_ finished: Bool) -> Void) {
UIView.animate(withDuration: 0.15, delay: 0, options: UIViewAnimationOptions(), animations: {
self.alpha = 0
}, completion: nil)
UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.9, options: UIViewAnimationOptions(), animations: {
let scale = CGAffineTransform(scaleX: 0.9, y: 0.9)
let transform = scale.translatedBy(x: 0, y: 100)
self.transform = transform
for (index, item) in self.items {
let constraint = self.itemCenterYConstraints[index]
constraint.constant = 100
item.alpha = 0
item.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
self.layoutIfNeeded()
}
}, completion: {(finsihed) in
completion(true)
})
}
// MARK: - Datasource & Delegate
open weak var datasource: EGMenuBarDatasource? {
didSet {
}
}
open weak var delegate: EGMenuBarDelegate? {
didSet {
setupMenuView()
setupMenuItems()
setupMenuItemImages()
setupMenuItemTitles()
}
}
// MARK: - Private
fileprivate var items: [Int: EGMenuBarItem] = [:]
fileprivate var itemCenterYConstraints: [NSLayoutConstraint] = []
// MARK: - Life Cycle
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
fileprivate func commonInit() {
}
// MARK: - Helper Methods
fileprivate func setupMenuView() {
print("setup")
if let height = delegate?.itemHeight(self) {
print("height: \(height)")
itemHeight = CGFloat(height)
}
if let spacing = delegate?.interItemSpacing(self) {
print("spacing: \(spacing)")
interItemSpacing = CGFloat(spacing)
}
if let numberOfItems = datasource?.numberOfItems() {
menuHeight = itemHeight + (interItemSpacing * 2)
menuWidth = (CGFloat(numberOfItems) * itemHeight) + ((CGFloat(numberOfItems) + 1) * interItemSpacing)
frame = CGRect(x: 0, y: 0, width: menuWidth, height: menuHeight)
}
alpha = 0
backgroundColor = menuBackgroundColor
layer.cornerRadius = menuHeight / 2
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowColor = UIColor.black.cgColor
layer.shadowRadius = 6.0
layer.shadowOpacity = 0.4
layer.borderWidth = 0.4
layer.borderColor = UIColor.darkGray.cgColor
let scale = CGAffineTransform(scaleX: 1, y: 1) // CGAffineTransformMakeScale(1, 1)
let transform = scale.translatedBy(x: 0, y: 10)
self.transform = transform
}
fileprivate func setupMenuItems() {
if let numberOfItems = datasource?.numberOfItems() {
var previosItem: EGMenuBarItem? = nil
for index in 0...numberOfItems-1 {
let item = EGMenuBarItem()
item.translatesAutoresizingMaskIntoConstraints = false
item.delegate = self
item.layer.cornerRadius = itemHeight / 2
item.layer.masksToBounds = true
item.alpha = 0
item.index = index
items[index] = item
addSubview(item)
setupContraintForItem(item, withIndex: index, previousItem: previosItem, lastItem: index == numberOfItems - 1 ? true : false)
previosItem = item
setupInitialTransformForItem(item)
}
}
}
fileprivate func setupContraintForItem(_ item: EGMenuBarItem, withIndex index: Int, previousItem prevItem: EGMenuBarItem?, lastItem: Bool) {
if let prevItem = prevItem, !lastItem {
// middle items
item.leadingAnchor.constraint(equalTo: prevItem.trailingAnchor, constant: interItemSpacing).isActive = true
let centerYConstraint = item.centerYAnchor.constraint(equalTo: centerYAnchor)
centerYConstraint.constant = 100
centerYConstraint.isActive = true
self.itemCenterYConstraints.append(centerYConstraint)
item.widthAnchor.constraint(equalToConstant: itemHeight).isActive = true
item.heightAnchor.constraint(equalToConstant: itemHeight).isActive = true
} else if let prevItem = prevItem, lastItem {
// last item
item.leadingAnchor.constraint(equalTo: prevItem.trailingAnchor, constant: interItemSpacing).isActive = true
item.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -interItemSpacing).isActive = true
let centerYConstraint = item.centerYAnchor.constraint(equalTo: centerYAnchor)
centerYConstraint.constant = 100
centerYConstraint.isActive = true
self.itemCenterYConstraints.append(centerYConstraint)
item.widthAnchor.constraint(equalToConstant: itemHeight).isActive = true
item.heightAnchor.constraint(equalToConstant: itemHeight).isActive = true
} else {
// first item
item.leadingAnchor.constraint(equalTo: leadingAnchor, constant: interItemSpacing).isActive = true
let centerYConstraint = item.centerYAnchor.constraint(equalTo: centerYAnchor)
centerYConstraint.constant = 100
centerYConstraint.isActive = true
self.itemCenterYConstraints.append(centerYConstraint)
item.widthAnchor.constraint(equalToConstant: itemHeight).isActive = true
item.heightAnchor.constraint(equalToConstant: itemHeight).isActive = true
}
}
fileprivate func setupInitialTransformForItem(_ item: EGMenuBarItem) {
let scale = CGAffineTransform(scaleX: 0.5, y: 0.5)
item.transform = scale
}
fileprivate func setupMenuItemImages() {
if let images = datasource?.itemImages() {
for (index, image) in images.enumerated() {
items[index]?.image = image
}
}
}
fileprivate func setupMenuItemTitles() {
if let titles = datasource?.itemTitles() {
for (index, title) in titles.enumerated() {
items[index]?.title = title
}
}
}
}
extension EGMenuBar: EGMenuBarItemDelegate {
func didSelectItemAtIndex(_ index: Int) {
delegate?.didSelectItemAtIndex(self, index: index)
}
}
| mit | 808ddeafc7f90feb6c87ec6de61b0739 | 37.919872 | 160 | 0.604711 | 5.011556 | false | false | false | false |
LoganWright/Genome | Tests/GenomeTests/SettableOperatorTest.swift | 2 | 13930 | //
// SettableOperatorTest.swift
// Genome
//
// Created by Logan Wright on 9/22/15.
// Copyright © 2015 lowriDevs. All rights reserved.
//
import XCTest
@testable import Genome
class SettableOperatorTest: XCTestCase {
static let allTests = [
("testBasicTypes", testBasicTypes),
("testMappableObject", testMappableObject),
("testMappableArray", testMappableArray),
("testMappableArrayOfArrays", testMappableArrayOfArrays),
("testMappableDictionary", testMappableDictionary),
("testMappableDictionaryOfArrays", testMappableDictionaryOfArrays),
("testMappableSet", testMappableSet),
("testDictionaryUnableToConvert", testDictionaryUnableToConvert),
("testDictArrayUnableToConvert", testDictArrayUnableToConvert),
("testThatValueExistsButIsNotTheTypeExpectedNonOptional", testThatValueExistsButIsNotTheTypeExpectedNonOptional),
("testThatValueExistsButIsNotTheTypeExpectedOptional", testThatValueExistsButIsNotTheTypeExpectedOptional),
("testThatValueDoesNotExistNonOptional", testThatValueDoesNotExistNonOptional),
("testMapType", testMapType),
]
var map = makeTestMap()
override func setUp() {
super.setUp()
map = makeTestMap()
}
func testBasicTypes() throws {
let int: Int = try map.extract("int")
XCTAssert(int == 272)
let optionalInt: Int? = try map.extract("int")
XCTAssert(optionalInt! == 272)
let strings: [String] = try map.extract("strings")
XCTAssert(strings == ["one", "two", "three"])
let optionalStrings: [String]? = try map.extract("strings")
XCTAssert(optionalStrings ?? [] == ["one", "two", "three"])
let stringInt: String = try map.extract("int") { (nodeValue: Int) in
return "\(nodeValue)"
}
XCTAssert(stringInt == "272")
let emptyInt: Int? = try map.extract("i_dont_exist")
XCTAssert(emptyInt == nil)
let emptyStrings: [String]? = try map.extract("i_dont_exist")
XCTAssert(emptyStrings == nil)
}
func testMappableObject() throws {
let person: Person = try map.extract("person")
XCTAssert(person == joeObject)
let optionalPerson: Person? = try map.extract("person")
XCTAssert(optionalPerson == joeObject)
let emptyPerson: Person? = try map.extract("i_dont_exist")
XCTAssert(emptyPerson == nil)
}
func testMappableArray() throws {
let people: [Person] = try map.extract("people")
XCTAssert(people == [joeObject, janeObject])
let optionalPeople: [Person]? = try map.extract("people")
XCTAssert(optionalPeople! == [joeObject, janeObject])
let singleValueToArray: [Person] = try map.extract("person")
XCTAssert(singleValueToArray == [joeObject])
let emptyPersons: [Person]? = try map.extract("i_dont_exist")
XCTAssert(emptyPersons == nil)
}
func testMappableArrayOfArrays() throws {
let orderedGroups: [[Person]] = try map.extract("ordered_groups")
let optionalOrderedGroups: [[Person]]? = try map.extract("ordered_groups")
for orderGroupsArray in [orderedGroups, optionalOrderedGroups!] {
XCTAssert(orderGroupsArray.count == 2)
let firstGroup = orderGroupsArray[0]
XCTAssert(firstGroup == [joeObject, justinObject, philObject])
let secondGroup = orderGroupsArray[1]
XCTAssert(secondGroup == [janeObject])
}
let arrayValueToArrayOfArrays: [[Person]] = try map.extract("people")
XCTAssert(arrayValueToArrayOfArrays.count == 2)
XCTAssert(arrayValueToArrayOfArrays.first! == [joeObject])
let emptyArrayOfArrays: [[Person]]? = try map.extract("i_dont_exist")
XCTAssert(emptyArrayOfArrays == nil)
}
func testMappableDictionary() throws {
let expectedRelationships = [
"best_friend": philObject,
"cousin": justinObject
]
let relationships: [String : Person] = try map.extract("relationships")
XCTAssert(relationships == expectedRelationships)
let optionalRelationships: [String : Person]? = try map.extract("relationships")
XCTAssert(optionalRelationships! == expectedRelationships)
let emptyDictionary: [String : Person]? = try map.extract("i_dont_exist")
XCTAssert(emptyDictionary == nil)
}
func testMappableDictionaryOfArrays() throws {
let groups: [String : [Person]] = try map.extract("groups")
let optionalGroups: [String : [Person]]? = try map.extract("groups")
for groupsArray in [groups, optionalGroups!] {
XCTAssert(groupsArray.count == 2)
let boys = groupsArray["boys"]!
XCTAssert(boys == [joeObject, justinObject, philObject])
let girls = groupsArray["girls"]!
XCTAssert(girls == [janeObject])
}
let emptyDictionaryOfArrays: [String : [Person]]? = try map.extract("i_dont_exist")
XCTAssert(emptyDictionaryOfArrays == nil)
}
func testMappableSet() throws {
let people: Set<Person> = try map.extract("duplicated_people")
let optionalPeople: Set<Person>? = try map.extract("duplicated_people")
for peopleSet in [people, optionalPeople!] {
XCTAssert(peopleSet.count == 2)
XCTAssert(peopleSet.contains(joeObject))
XCTAssert(peopleSet.contains(janeObject))
}
let singleValueToSet: Set<Person> = try map.extract("person")
XCTAssert(singleValueToSet.count == 1)
XCTAssert(singleValueToSet.contains(joeObject))
let emptyPersons: [Person]? = try map.extract("i_dont_exist")
XCTAssert(emptyPersons == nil)
}
func testDictionaryUnableToConvert() {
do {
let _: [String : Person] = try map.extract("int")
XCTFail("Incorrect type should throw error")
} catch NodeError.unableToConvert {
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
}
func testDictArrayUnableToConvert() {
// Unexpected Type - Mappable Dictionary of Arrays
do {
let _: [String : [Person]] = try map.extract("int")
XCTFail("Incorrect type should throw error")
} catch NodeError.unableToConvert {
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
}
func testThatValueExistsButIsNotTheTypeExpectedNonOptional() {
// Unexpected Type - Basic
do {
let _: Bool = try map.extract("int")
XCTFail("Incorrect type should throw error")
} catch let NodeError.unableToConvert(node: node, expected: expected) {
XCTAssert(node == 272)
XCTAssert(expected == "Bool")
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
// Unexpected Type - Mappable Object
do {
let _: Person = try map.extract("int")
XCTFail("Incorrect type should throw error")
} catch NodeError.unableToConvert {
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
// Unexpected Type - Mappable Array
do {
let _: [Person] = try map.extract("int")
XCTFail("Incorrect type should throw error")
} catch NodeError.unableToConvert {
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
// Unexpected Type - Mappable Array of Arrays
do {
let _: [[Person]] = try map.extract("int")
XCTFail("Incorrect type should throw error")
} catch NodeError.unableToConvert {
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
// Unexpected Type - Transformable
do {
// Transformer expects string, but is passed an int
let _: String = try map.extract("int") { (input: Bool) in
return "Hello: \(input)"
}
XCTFail("Incorrect type should throw error")
} catch let NodeError.unableToConvert(node: node, expected: expected) {
XCTAssert(node == 272)
XCTAssert(expected == "Bool")
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
}
// If a value exists, but is the wrong type, it should throw error
func testThatValueExistsButIsNotTheTypeExpectedOptional() {
// Unexpected Value - Mappable Object
do {
let _: Person? = try map.extract("int")
XCTFail("Incorrect type should throw error")
} catch NodeError.unableToConvert {
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
// Unexpected Value - Mappable Array
do {
let _: [Person]? = try map.extract("int")
XCTFail("Incorrect type should throw error")
} catch NodeError.unableToConvert {
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
// Unexpected Value - Mappable Array of Arrays
do {
let _: [[Person]]? = try map.extract("int")
XCTFail("Incorrect type should throw error")
} catch NodeError.unableToConvert {
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
// Unexpected Value - Mappable Dictionary
do {
let _: [String : Person]? = try map.extract("int")
XCTFail("Incorrect type should throw error")
} catch NodeError.unableToConvert {
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
// Unexpected Value - Mappable Dictionary of Arrays
do {
let _: [String : [Person]]? = try map.extract("int")
XCTFail("Incorrect type should throw error")
} catch NodeError.unableToConvert {
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
}
// Expected Something, Got Nothing
func testThatValueDoesNotExistNonOptional() {
// Expected Non-Nil - Basic
do {
let _: String = try map.extract("asdf")
XCTFail("nil value should throw error")
} catch NodeError.unableToConvert {
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
// Expected Non-Nil - Mappable
do {
let _: Person = try map.extract("asdf")
XCTFail("nil value should throw error")
} catch NodeError.unableToConvert {
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
// Expected Non-Nil - Mappable Array
do {
let _: [Person] = try map.extract("asdf")
XCTFail("nil value should throw error")
} catch NodeError.unableToConvert {
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
// Expected Non-Nil - Mappable Array of Arrays
do {
let _: [[Person]] = try map.extract("asdf")
XCTFail("nil value should throw error")
} catch NodeError.unableToConvert {
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
// Expected Non-Nil - Mappable Dictionary
do {
let _: [String : Person] = try map.extract("asdf")
XCTFail("nil value should throw error")
} catch NodeError.unableToConvert {
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
// Expected Non-Nil - Mappable Dictionary of Arrays
do {
let _: [String : [Person]] = try map.extract("asdf")
XCTFail("nil value should throw error")
} catch NodeError.unableToConvert {
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
// Expected Non-Nil - Transformable
do {
// Transformer expects string, but is passed an int
let _: String = try map.extract("asdf") { (input: String) in
return "Hello: \(input)"
}
XCTFail("nil value should throw error")
} catch NodeError.unableToConvert {
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
}
func testMapType() {
do {
let map = Map()
let _: String = try map.extract("a")
XCTFail("Inproper map type should throw error")
} catch NodeError.unableToConvert {
} catch {
XCTFail("Incorrect Error: \(error) Expected: \(NodeError.unableToConvert)")
}
}
}
| mit | 65cbc643760715be09d460f57d1f7b03 | 35.655263 | 121 | 0.574844 | 5.001436 | false | true | false | false |
theeternalsw0rd/digital-signage-tvos | Digital Signage/SlideshowItem.swift | 1 | 574 | //
// SlideshowItem.swift
// Digital Signage
//
// Created by Micah Bucy on 12/17/15.
// Copyright © 2015 Micah Bucy. All rights reserved.
//
// The MIT License (MIT)
// This file is subject to the terms and conditions defined in LICENSE.md
import Foundation
import UIKit
import FileKit
class SlideshowItem: NSOperation {
var url = NSURL()
var type = "image"
var image = UIImage()
var path: Path
var status = 0
init(url: NSURL, type: String, path: Path) {
self.url = url
self.type = type
self.path = path
}
} | mit | 0e31e6e87f19f655c3e5214c277baa18 | 20.259259 | 74 | 0.633508 | 3.537037 | false | false | false | false |
noppoMan/Prorsum | Sources/Prorsum/WebSocket/Response+Websocket.swift | 1 | 960 | //
// Response+Websocket.swift
// Prorsum
//
// Created by Yuki Takei on 2016/12/28.
//
//
extension Response {
public typealias UpgradeConnection = (Request, DuplexStream) throws -> Void
public var upgradeConnection: UpgradeConnection? {
return storage["response-connection-upgrade"] as? UpgradeConnection
}
public mutating func upgradeConnection(_ upgrade: @escaping UpgradeConnection) {
storage["response-connection-upgrade"] = upgrade
}
}
extension Response {
public var webSocketVersion: String? {
return headers["Sec-Websocket-Version"]
}
public var webSocketKey: String? {
return headers["Sec-Websocket-Key"]
}
public var webSocketAccept: String? {
return headers["Sec-WebSocket-Accept"]
}
public var isWebSocket: Bool {
return connection?.lowercased() == "upgrade"
&& upgrade?.lowercased() == "websocket"
}
}
| mit | a2229c534f59e2081835553c0df123da | 24.263158 | 85 | 0.645833 | 4.485981 | false | false | false | false |
2345Team/Swifter-Tips | 2.将protocol的方法声明为mutating/ProtocolWithMutating.playground/Contents.swift | 1 | 888 | //: Playground - noun: a place where people can play
import UIKit
protocol Vehicle //swift 协议不仅可以被class实现,也适用于 struct 和 enum 有别于oc
{
var numberOfWheels: Int {get}
var color: UIColor {get set}
mutating func changeColor() /*mutating 关键字修饰方法是为了能在该方法中修改 struct 或是 enum 的变量,所以如果你没在接口方法里写 mutating 的话,别人如果用 struct 或者 enum 来实现这个接口的话,就不能在方法里改变自己的变量了
*/
}
struct MyCar: Vehicle {
let numberOfWheels = 4
var color = UIColor.blueColor()
mutating func changeColor() {
color = UIColor.redColor()
}
}
class TestCar: Vehicle {
let numberOfWheels = 4
var color = UIColor.cyanColor()
func changeColor() {
color = UIColor.redColor()
}
} | mit | 38b0cf67c5cd396765db36f14b08e79c | 21.870968 | 155 | 0.669492 | 3.649485 | false | false | false | false |
roambotics/swift | benchmark/single-source/SimpleArraySpecialization.swift | 2 | 2696 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This benchmark tests prespecialization of a simplified array type
import TestsUtils
import SimpleArray
public let benchmarks = [
BenchmarkInfo(
name: "SimpleArraySpecialization",
runFunction: run_SimpleArraySpecializationBenchmarks,
tags: [.abstraction, .runtime, .cpubench]
),
BenchmarkInfo(
name: "SimpleArraySpecialization2",
runFunction: run_SimpleArraySpecializationBenchmarks2,
tags: [.abstraction, .runtime, .cpubench]
),
BenchmarkInfo(
name: "SimpleArraySpecialization3",
runFunction: run_SimpleArraySpecializationBenchmarks3,
tags: [.abstraction, .runtime, .cpubench]
),
BenchmarkInfo(
name: "SimpleArraySpecialization4",
runFunction: run_SimpleArraySpecializationBenchmarks4,
tags: [.abstraction, .runtime, .cpubench]
),
]
let xs = SimpleArray<MyClass>(capacity: 100_000)
@_silgen_name("_swift_stdlib_immortalize")
func _stdlib_immortalize(_ obj: AnyObject)
import Foundation
public final class MyClass {
public var x: Int = 23
}
@inline(never)
public func run_SimpleArraySpecializationBenchmarks(_ n: Int) {
let myObject = MyClass()
// prevent refcount overflow
_stdlib_immortalize(myObject)
for _ in 0..<n {
for i in 0..<100_000 {
xs.append(myObject)
}
xs.clear()
}
blackHole(xs)
}
@inline(never)
public func run_SimpleArraySpecializationBenchmarks2(_ n: Int) {
let myObject = MyClass()
// prevent refcount overflow
_stdlib_immortalize(myObject)
for _ in 0..<n {
for i in 0..<100_000 {
xs.append2(myObject)
}
xs.clear()
}
blackHole(xs)
}
@inline(never)
public func run_SimpleArraySpecializationBenchmarks3(_ n: Int) {
let myObject = MyClass()
// prevent refcount overflow
_stdlib_immortalize(myObject)
for _ in 0..<n {
for i in 0..<100_000 {
xs.append3(myObject)
}
xs.clear()
}
blackHole(xs)
}
@inline(never)
public func run_SimpleArraySpecializationBenchmarks4(_ n: Int) {
let myObject = MyClass()
// prevent refcount overflow
_stdlib_immortalize(myObject)
for _ in 0..<n {
for i in 0..<100_000 {
xs.append4(myObject)
}
xs.clear()
}
blackHole(xs)
}
| apache-2.0 | 2d6f1d736d37cf9ba9d3748d13cc11b5 | 21.466667 | 80 | 0.650964 | 4.005944 | false | false | false | false |
haawa799/WaniKani-Kanji-Strokes | WaniKani-Kanji-Strokes/ViewController.swift | 1 | 1419 | //
// ViewController.swift
// WaniKani-Kanji-Strokes
//
// Created by Andriy K. on 12/27/15.
// Copyright © 2015 Andriy K. All rights reserved.
//
import UIKit
import StrokeDrawingView
import WaniKit
class ViewController: UIViewController {
var kanjiViewController: KanjiViewController?
override func viewDidLoad() {
super.viewDidLoad()
let manager = WaniApiManager()
manager.setApiKey("")
manager.fetchKanjiList(11) { (result) -> Void in
switch result {
case .Error(let error) : print(error())
case .Response(let response) :
let resp = response()
self.kanjiArray = resp.kanji
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
super.prepareForSegue(segue, sender: sender)
if let kanjiVC = segue.destinationViewController as? KanjiViewController {
kanjiViewController = kanjiVC
}
}
var kanjiArray: [KanjiInfo]?
@IBOutlet weak var levelButton: UIBarButtonItem!
var kanji: Kanji?
@IBAction func levelPickerButtonPressed(sender: AnyObject) {
guard let title = (sender as? UIBarButtonItem)?.title, let index = Int(title) else { return }
guard (index < kanjiArray?.count), let kanjiName = kanjiArray?[index].character else { return }
kanji = Kanji(kanji: kanjiName)
kanjiViewController?.kanji = kanji
}
}
| mit | 3dc190ce66f1dac9da0627f988587211 | 22.633333 | 99 | 0.666432 | 4.459119 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureKYC/Sources/FeatureKYCUI/Search/Views/Cells/LocationSuggestionCell.swift | 1 | 2385 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import UIKit
class LocationSuggestionCell: UITableViewCell {
func configure(with suggestion: LocationSuggestion) {
let titleAttributes = [
NSAttributedString.Key.font: LocationSuggestionCell.titleFont(),
NSAttributedString.Key.foregroundColor: UIColor.gray5
]
let titleHighlightedAttributes = [
NSAttributedString.Key.font: LocationSuggestionCell.highlightedTitleFont(),
NSAttributedString.Key.foregroundColor: UIColor.gray5
]
let subtitleAttributes = [
NSAttributedString.Key.font: LocationSuggestionCell.subtitleFont(),
NSAttributedString.Key.foregroundColor: UIColor.gray5
]
let subtitleHighlightedAttributes = [
NSAttributedString.Key.font: LocationSuggestionCell.highlightedSubtitleFont(),
NSAttributedString.Key.foregroundColor: UIColor.gray5
]
let attributedTitle = NSMutableAttributedString(string: suggestion.title, attributes: titleAttributes)
let attributedSubtitle = NSMutableAttributedString(string: suggestion.subtitle, attributes: subtitleAttributes)
suggestion.titleHighlights.forEach {
attributedTitle.addAttributes(titleHighlightedAttributes, range: $0)
}
suggestion.subtitleHighlights.forEach {
attributedSubtitle.addAttributes(subtitleHighlightedAttributes, range: $0)
}
textLabel?.attributedText = attributedTitle
detailTextLabel?.attributedText = attributedSubtitle
}
static func titleFont() -> UIFont {
UIFont(name: Constants.FontNames.montserratRegular, size: Constants.FontSizes.SmallMedium) ?? UIFont.systemFont(ofSize: 17)
}
static func highlightedTitleFont() -> UIFont {
UIFont(name: Constants.FontNames.montserratSemiBold, size: Constants.FontSizes.SmallMedium) ?? UIFont.systemFont(ofSize: 17)
}
static func subtitleFont() -> UIFont {
UIFont(name: Constants.FontNames.montserratRegular, size: Constants.FontSizes.ExtraExtraExtraSmall) ?? UIFont.systemFont(ofSize: 13)
}
static func highlightedSubtitleFont() -> UIFont {
UIFont(name: Constants.FontNames.montserratSemiBold, size: Constants.FontSizes.ExtraExtraExtraSmall) ?? UIFont.systemFont(ofSize: 13)
}
}
| lgpl-3.0 | ff1ec25e5ad720713baa8d51b6114473 | 40.824561 | 141 | 0.717701 | 5.405896 | false | false | false | false |
vamsirajendra/firefox-ios | Client/Frontend/Browser/URLBarView.swift | 3 | 33887 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import Shared
import SnapKit
struct URLBarViewUX {
static let TextFieldBorderColor = UIColor(rgb: 0xBBBBBB)
static let TextFieldActiveBorderColor = UIColor(rgb: 0x4A90E2)
static let TextFieldContentInset = UIOffsetMake(9, 5)
static let LocationLeftPadding = 5
static let LocationHeight = 28
static let LocationContentOffset: CGFloat = 8
static let TextFieldCornerRadius: CGFloat = 3
static let TextFieldBorderWidth: CGFloat = 1
// offset from edge of tabs button
static let URLBarCurveOffset: CGFloat = 14
static let URLBarCurveOffsetLeft: CGFloat = -10
// buffer so we dont see edges when animation overshoots with spring
static let URLBarCurveBounceBuffer: CGFloat = 8
static let ProgressTintColor = UIColor(red:1, green:0.32, blue:0, alpha:1)
static let TabsButtonRotationOffset: CGFloat = 1.5
static let TabsButtonHeight: CGFloat = 18.0
static let ToolbarButtonInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
static func backgroundColorWithAlpha(alpha: CGFloat) -> UIColor {
return UIConstants.AppBackgroundColor.colorWithAlphaComponent(alpha)
}
}
protocol URLBarDelegate: class {
func urlBarDidPressTabs(urlBar: URLBarView)
func urlBarDidPressReaderMode(urlBar: URLBarView)
/// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied
func urlBarDidLongPressReaderMode(urlBar: URLBarView) -> Bool
func urlBarDidPressStop(urlBar: URLBarView)
func urlBarDidPressReload(urlBar: URLBarView)
func urlBarDidEnterOverlayMode(urlBar: URLBarView)
func urlBarDidLeaveOverlayMode(urlBar: URLBarView)
func urlBarDidLongPressLocation(urlBar: URLBarView)
func urlBarLocationAccessibilityActions(urlBar: URLBarView) -> [UIAccessibilityCustomAction]?
func urlBarDidPressScrollToTop(urlBar: URLBarView)
func urlBar(urlBar: URLBarView, didEnterText text: String)
func urlBar(urlBar: URLBarView, didSubmitText text: String)
}
class URLBarView: UIView {
// Additional UIAppearance-configurable properties
dynamic var locationBorderColor: UIColor = URLBarViewUX.TextFieldBorderColor {
didSet {
if !inOverlayMode {
locationContainer.layer.borderColor = locationBorderColor.CGColor
}
}
}
dynamic var locationActiveBorderColor: UIColor = URLBarViewUX.TextFieldActiveBorderColor {
didSet {
if inOverlayMode {
locationContainer.layer.borderColor = locationActiveBorderColor.CGColor
}
}
}
weak var delegate: URLBarDelegate?
weak var browserToolbarDelegate: BrowserToolbarDelegate?
var helper: BrowserToolbarHelper?
var isTransitioning: Bool = false {
didSet {
if isTransitioning {
// Cancel any pending/in-progress animations related to the progress bar
self.progressBar.setProgress(1, animated: false)
self.progressBar.alpha = 0.0
}
}
}
var toolbarIsShowing = false
/// Overlay mode is the state where the lock/reader icons are hidden, the home panels are shown,
/// and the Cancel button is visible (allowing the user to leave overlay mode). Overlay mode
/// is *not* tied to the location text field's editing state; for instance, when selecting
/// a panel, the first responder will be resigned, yet the overlay mode UI is still active.
var inOverlayMode = false
lazy var locationView: BrowserLocationView = {
let locationView = BrowserLocationView()
locationView.translatesAutoresizingMaskIntoConstraints = false
locationView.readerModeState = ReaderModeState.Unavailable
locationView.delegate = self
return locationView
}()
private lazy var locationTextField: ToolbarTextField = {
let locationTextField = ToolbarTextField()
locationTextField.translatesAutoresizingMaskIntoConstraints = false
locationTextField.autocompleteDelegate = self
locationTextField.keyboardType = UIKeyboardType.WebSearch
locationTextField.autocorrectionType = UITextAutocorrectionType.No
locationTextField.autocapitalizationType = UITextAutocapitalizationType.None
locationTextField.returnKeyType = UIReturnKeyType.Go
locationTextField.clearButtonMode = UITextFieldViewMode.WhileEditing
locationTextField.backgroundColor = UIColor.whiteColor()
locationTextField.font = UIConstants.DefaultMediumFont
locationTextField.accessibilityIdentifier = "address"
locationTextField.accessibilityLabel = NSLocalizedString("Address and Search", comment: "Accessibility label for address and search field, both words (Address, Search) are therefore nouns.")
locationTextField.attributedPlaceholder = self.locationView.placeholder
return locationTextField
}()
private lazy var locationContainer: UIView = {
let locationContainer = UIView()
locationContainer.translatesAutoresizingMaskIntoConstraints = false
// Enable clipping to apply the rounded edges to subviews.
locationContainer.clipsToBounds = true
locationContainer.layer.borderColor = self.locationBorderColor.CGColor
locationContainer.layer.cornerRadius = URLBarViewUX.TextFieldCornerRadius
locationContainer.layer.borderWidth = URLBarViewUX.TextFieldBorderWidth
return locationContainer
}()
private lazy var tabsButton: TabsButton = {
let tabsButton = TabsButton()
tabsButton.titleLabel.text = "0"
tabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside)
tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility Label for the tabs button in the browser toolbar")
return tabsButton
}()
private lazy var progressBar: UIProgressView = {
let progressBar = UIProgressView()
progressBar.progressTintColor = URLBarViewUX.ProgressTintColor
progressBar.alpha = 0
progressBar.hidden = true
return progressBar
}()
private lazy var cancelButton: UIButton = {
let cancelButton = InsetButton()
cancelButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
let cancelTitle = NSLocalizedString("Cancel", comment: "Button label to cancel entering a URL or search query")
cancelButton.setTitle(cancelTitle, forState: UIControlState.Normal)
cancelButton.titleLabel?.font = UIConstants.DefaultMediumFont
cancelButton.addTarget(self, action: "SELdidClickCancel", forControlEvents: UIControlEvents.TouchUpInside)
cancelButton.titleEdgeInsets = UIEdgeInsetsMake(10, 12, 10, 12)
cancelButton.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
cancelButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
return cancelButton
}()
private lazy var curveShape: CurveView = { return CurveView() }()
private lazy var scrollToTopButton: UIButton = {
let button = UIButton()
button.addTarget(self, action: "SELtappedScrollToTopArea", forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
lazy var shareButton: UIButton = { return UIButton() }()
lazy var bookmarkButton: UIButton = { return UIButton() }()
lazy var forwardButton: UIButton = { return UIButton() }()
lazy var backButton: UIButton = { return UIButton() }()
lazy var stopReloadButton: UIButton = { return UIButton() }()
lazy var actionButtons: [UIButton] = {
return [self.shareButton, self.bookmarkButton, self.forwardButton, self.backButton, self.stopReloadButton]
}()
// Used to temporarily store the cloned button so we can respond to layout changes during animation
private weak var clonedTabsButton: TabsButton?
private var rightBarConstraint: Constraint?
private let defaultRightOffset: CGFloat = URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer
var currentURL: NSURL? {
get {
return locationView.url
}
set(newURL) {
locationView.url = newURL
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
backgroundColor = URLBarViewUX.backgroundColorWithAlpha(0)
addSubview(curveShape)
addSubview(scrollToTopButton)
addSubview(progressBar)
addSubview(tabsButton)
addSubview(cancelButton)
addSubview(shareButton)
addSubview(bookmarkButton)
addSubview(forwardButton)
addSubview(backButton)
addSubview(stopReloadButton)
locationContainer.addSubview(locationView)
locationContainer.addSubview(locationTextField)
addSubview(locationContainer)
helper = BrowserToolbarHelper(toolbar: self)
setupConstraints()
// Make sure we hide any views that shouldn't be showing in non-overlay mode.
updateViewsForOverlayModeAndToolbarChanges()
self.locationTextField.hidden = !inOverlayMode
}
private func setupConstraints() {
scrollToTopButton.snp_makeConstraints { make in
make.top.equalTo(self)
make.left.right.equalTo(self.locationContainer)
}
progressBar.snp_makeConstraints { make in
make.top.equalTo(self.snp_bottom)
make.width.equalTo(self)
}
locationView.snp_makeConstraints { make in
make.edges.equalTo(self.locationContainer)
}
cancelButton.snp_makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
}
tabsButton.snp_makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
curveShape.snp_makeConstraints { make in
make.top.left.bottom.equalTo(self)
self.rightBarConstraint = make.right.equalTo(self).constraint
self.rightBarConstraint?.updateOffset(defaultRightOffset)
}
locationTextField.snp_makeConstraints { make in
make.edges.equalTo(self.locationView.urlTextField)
}
backButton.snp_makeConstraints { make in
make.left.centerY.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
forwardButton.snp_makeConstraints { make in
make.left.equalTo(self.backButton.snp_right)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
stopReloadButton.snp_makeConstraints { make in
make.left.equalTo(self.forwardButton.snp_right)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
shareButton.snp_makeConstraints { make in
make.right.equalTo(self.bookmarkButton.snp_left)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
bookmarkButton.snp_makeConstraints { make in
make.right.equalTo(self.tabsButton.snp_left).offset(URLBarViewUX.URLBarCurveOffsetLeft)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
}
override func updateConstraints() {
super.updateConstraints()
if inOverlayMode {
// In overlay mode, we always show the location view full width
self.locationContainer.snp_remakeConstraints { make in
make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding)
make.trailing.equalTo(self.cancelButton.snp_leading)
make.height.equalTo(URLBarViewUX.LocationHeight)
make.centerY.equalTo(self)
}
} else {
self.locationContainer.snp_remakeConstraints { make in
if self.toolbarIsShowing {
// If we are showing a toolbar, show the text field next to the forward button
make.leading.equalTo(self.stopReloadButton.snp_trailing)
make.trailing.equalTo(self.shareButton.snp_leading)
} else {
// Otherwise, left align the location view
make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding)
make.trailing.equalTo(self.tabsButton.snp_leading).offset(-14)
}
make.height.equalTo(URLBarViewUX.LocationHeight)
make.centerY.equalTo(self)
}
}
}
// Ideally we'd split this implementation in two, one URLBarView with a toolbar and one without
// However, switching views dynamically at runtime is a difficult. For now, we just use one view
// that can show in either mode.
func setShowToolbar(shouldShow: Bool) {
toolbarIsShowing = shouldShow
setNeedsUpdateConstraints()
// when we transition from portrait to landscape, calling this here causes
// the constraints to be calculated too early and there are constraint errors
if !toolbarIsShowing {
updateConstraintsIfNeeded()
}
updateViewsForOverlayModeAndToolbarChanges()
}
func updateAlphaForSubviews(alpha: CGFloat) {
self.tabsButton.alpha = alpha
self.locationContainer.alpha = alpha
self.backgroundColor = URLBarViewUX.backgroundColorWithAlpha(1 - alpha)
self.actionButtons.forEach { $0.alpha = alpha }
}
func updateTabCount(count: Int, animated: Bool = true) {
let currentCount = self.tabsButton.titleLabel.text
// only animate a tab count change if the tab count has actually changed
if currentCount != count.description {
if let _ = self.clonedTabsButton {
self.clonedTabsButton?.layer.removeAllAnimations()
self.clonedTabsButton?.removeFromSuperview()
self.tabsButton.layer.removeAllAnimations()
}
// make a 'clone' of the tabs button
let newTabsButton = self.tabsButton.clone() as! TabsButton
self.clonedTabsButton = newTabsButton
newTabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside)
newTabsButton.titleLabel.text = count.description
newTabsButton.accessibilityValue = count.description
addSubview(newTabsButton)
newTabsButton.snp_makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
newTabsButton.frame = tabsButton.frame
// Instead of changing the anchorPoint of the CALayer, lets alter the rotation matrix math to be
// a rotation around a non-origin point
let frame = tabsButton.insideButton.frame
let halfTitleHeight = CGRectGetHeight(frame) / 2
var newFlipTransform = CATransform3DIdentity
newFlipTransform = CATransform3DTranslate(newFlipTransform, 0, halfTitleHeight, 0)
newFlipTransform.m34 = -1.0 / 200.0 // add some perspective
newFlipTransform = CATransform3DRotate(newFlipTransform, CGFloat(-M_PI_2), 1.0, 0.0, 0.0)
newTabsButton.insideButton.layer.transform = newFlipTransform
var oldFlipTransform = CATransform3DIdentity
oldFlipTransform = CATransform3DTranslate(oldFlipTransform, 0, halfTitleHeight, 0)
oldFlipTransform.m34 = -1.0 / 200.0 // add some perspective
oldFlipTransform = CATransform3DRotate(oldFlipTransform, CGFloat(M_PI_2), 1.0, 0.0, 0.0)
let animate = {
newTabsButton.insideButton.layer.transform = CATransform3DIdentity
self.tabsButton.insideButton.layer.transform = oldFlipTransform
self.tabsButton.insideButton.layer.opacity = 0
}
let completion: (Bool) -> Void = { finished in
// remove the clone and setup the actual tab button
newTabsButton.removeFromSuperview()
self.tabsButton.insideButton.layer.opacity = 1
self.tabsButton.insideButton.layer.transform = CATransform3DIdentity
self.tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility label for the tabs button in the (top) browser toolbar")
if finished {
self.tabsButton.titleLabel.text = count.description
self.tabsButton.accessibilityValue = count.description
}
}
if animated {
UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: animate, completion: completion)
} else {
completion(true)
}
}
}
func updateProgressBar(progress: Float) {
if progress == 1.0 {
self.progressBar.setProgress(progress, animated: !isTransitioning)
UIView.animateWithDuration(1.5, animations: {
self.progressBar.alpha = 0.0
}, completion: { finished in
if finished {
self.progressBar.setProgress(0.0, animated: false)
}
})
} else {
if self.progressBar.alpha < 1.0 {
self.progressBar.alpha = 1.0
}
self.progressBar.setProgress(progress, animated: (progress > progressBar.progress) && !isTransitioning)
}
}
func updateReaderModeState(state: ReaderModeState) {
locationView.readerModeState = state
}
func setAutocompleteSuggestion(suggestion: String?) {
locationTextField.setAutocompleteSuggestion(suggestion)
}
func enterOverlayMode(locationText: String?, pasted: Bool) {
// Show the overlay mode UI, which includes hiding the locationView and replacing it
// with the editable locationTextField.
animateToOverlayState(overlayMode: true)
delegate?.urlBarDidEnterOverlayMode(self)
// Bug 1193755 Workaround - Calling becomeFirstResponder before the animation happens
// won't take the initial frame of the label into consideration, which makes the label
// look squished at the start of the animation and expand to be correct. As a workaround,
// we becomeFirstResponder as the next event on UI thread, so the animation starts before we
// set a first responder.
if pasted {
// Clear any existing text, focus the field, then set the actual pasted text.
// This avoids highlighting all of the text.
self.locationTextField.text = ""
dispatch_async(dispatch_get_main_queue()) {
self.locationTextField.becomeFirstResponder()
self.locationTextField.text = locationText
}
} else {
// Copy the current URL to the editable text field, then activate it.
self.locationTextField.text = locationText
dispatch_async(dispatch_get_main_queue()) {
self.locationTextField.becomeFirstResponder()
}
}
}
func leaveOverlayMode(didCancel cancel: Bool = false) {
locationTextField.resignFirstResponder()
animateToOverlayState(overlayMode: false, didCancel: cancel)
delegate?.urlBarDidLeaveOverlayMode(self)
}
func prepareOverlayAnimation() {
// Make sure everything is showing during the transition (we'll hide it afterwards).
self.bringSubviewToFront(self.locationContainer)
self.cancelButton.hidden = false
self.progressBar.hidden = false
self.shareButton.hidden = !self.toolbarIsShowing
self.bookmarkButton.hidden = !self.toolbarIsShowing
self.forwardButton.hidden = !self.toolbarIsShowing
self.backButton.hidden = !self.toolbarIsShowing
self.stopReloadButton.hidden = !self.toolbarIsShowing
}
func transitionToOverlay(didCancel: Bool = false) {
self.cancelButton.alpha = inOverlayMode ? 1 : 0
self.progressBar.alpha = inOverlayMode || didCancel ? 0 : 1
self.shareButton.alpha = inOverlayMode ? 0 : 1
self.bookmarkButton.alpha = inOverlayMode ? 0 : 1
self.forwardButton.alpha = inOverlayMode ? 0 : 1
self.backButton.alpha = inOverlayMode ? 0 : 1
self.stopReloadButton.alpha = inOverlayMode ? 0 : 1
let borderColor = inOverlayMode ? locationActiveBorderColor : locationBorderColor
locationContainer.layer.borderColor = borderColor.CGColor
if inOverlayMode {
self.cancelButton.transform = CGAffineTransformIdentity
let tabsButtonTransform = CGAffineTransformMakeTranslation(self.tabsButton.frame.width + URLBarViewUX.URLBarCurveOffset, 0)
self.tabsButton.transform = tabsButtonTransform
self.clonedTabsButton?.transform = tabsButtonTransform
self.rightBarConstraint?.updateOffset(URLBarViewUX.URLBarCurveOffset + URLBarViewUX.URLBarCurveBounceBuffer + tabsButton.frame.width)
// Make the editable text field span the entire URL bar, covering the lock and reader icons.
self.locationTextField.snp_remakeConstraints { make in
make.leading.equalTo(self.locationContainer).offset(URLBarViewUX.LocationContentOffset)
make.top.bottom.trailing.equalTo(self.locationContainer)
}
} else {
self.tabsButton.transform = CGAffineTransformIdentity
self.clonedTabsButton?.transform = CGAffineTransformIdentity
self.cancelButton.transform = CGAffineTransformMakeTranslation(self.cancelButton.frame.width, 0)
self.rightBarConstraint?.updateOffset(defaultRightOffset)
// Shrink the editable text field back to the size of the location view before hiding it.
self.locationTextField.snp_remakeConstraints { make in
make.edges.equalTo(self.locationView.urlTextField)
}
}
}
func updateViewsForOverlayModeAndToolbarChanges() {
self.cancelButton.hidden = !inOverlayMode
self.progressBar.hidden = inOverlayMode
self.shareButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.bookmarkButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.forwardButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.backButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.stopReloadButton.hidden = !self.toolbarIsShowing || inOverlayMode
}
func animateToOverlayState(overlayMode overlay: Bool, didCancel cancel: Bool = false) {
prepareOverlayAnimation()
layoutIfNeeded()
inOverlayMode = overlay
locationView.urlTextField.hidden = inOverlayMode
locationTextField.hidden = !inOverlayMode
UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: [], animations: { _ in
self.transitionToOverlay(cancel)
self.setNeedsUpdateConstraints()
self.layoutIfNeeded()
}, completion: { _ in
self.updateViewsForOverlayModeAndToolbarChanges()
})
}
func SELdidClickAddTab() {
delegate?.urlBarDidPressTabs(self)
}
func SELdidClickCancel() {
leaveOverlayMode(didCancel: true)
}
func SELtappedScrollToTopArea() {
delegate?.urlBarDidPressScrollToTop(self)
}
}
extension URLBarView: BrowserToolbarProtocol {
func updateBackStatus(canGoBack: Bool) {
backButton.enabled = canGoBack
}
func updateForwardStatus(canGoForward: Bool) {
forwardButton.enabled = canGoForward
}
func updateBookmarkStatus(isBookmarked: Bool) {
bookmarkButton.selected = isBookmarked
}
func updateReloadStatus(isLoading: Bool) {
if isLoading {
stopReloadButton.setImage(helper?.ImageStop, forState: .Normal)
stopReloadButton.setImage(helper?.ImageStopPressed, forState: .Highlighted)
} else {
stopReloadButton.setImage(helper?.ImageReload, forState: .Normal)
stopReloadButton.setImage(helper?.ImageReloadPressed, forState: .Highlighted)
}
}
func updatePageStatus(isWebPage isWebPage: Bool) {
bookmarkButton.enabled = isWebPage
stopReloadButton.enabled = isWebPage
shareButton.enabled = isWebPage
}
override var accessibilityElements: [AnyObject]? {
get {
if inOverlayMode {
return [locationTextField, cancelButton]
} else {
if toolbarIsShowing {
return [backButton, forwardButton, stopReloadButton, locationView, shareButton, bookmarkButton, tabsButton, progressBar]
} else {
return [locationView, tabsButton, progressBar]
}
}
}
set {
super.accessibilityElements = newValue
}
}
}
extension URLBarView: BrowserLocationViewDelegate {
func browserLocationViewDidLongPressReaderMode(browserLocationView: BrowserLocationView) -> Bool {
return delegate?.urlBarDidLongPressReaderMode(self) ?? false
}
func browserLocationViewDidTapLocation(browserLocationView: BrowserLocationView) {
enterOverlayMode(locationView.url?.absoluteString, pasted: false)
}
func browserLocationViewDidLongPressLocation(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidLongPressLocation(self)
}
func browserLocationViewDidTapReload(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressReload(self)
}
func browserLocationViewDidTapStop(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressStop(self)
}
func browserLocationViewDidTapReaderMode(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressReaderMode(self)
}
func browserLocationViewLocationAccessibilityActions(browserLocationView: BrowserLocationView) -> [UIAccessibilityCustomAction]? {
return delegate?.urlBarLocationAccessibilityActions(self)
}
}
extension URLBarView: AutocompleteTextFieldDelegate {
func autocompleteTextFieldShouldReturn(autocompleteTextField: AutocompleteTextField) -> Bool {
guard let text = locationTextField.text else { return true }
delegate?.urlBar(self, didSubmitText: text)
return true
}
func autocompleteTextField(autocompleteTextField: AutocompleteTextField, didEnterText text: String) {
delegate?.urlBar(self, didEnterText: text)
}
func autocompleteTextFieldDidBeginEditing(autocompleteTextField: AutocompleteTextField) {
autocompleteTextField.highlightAll()
}
func autocompleteTextFieldShouldClear(autocompleteTextField: AutocompleteTextField) -> Bool {
delegate?.urlBar(self, didEnterText: "")
return true
}
}
// MARK: UIAppearance
extension URLBarView {
dynamic var progressBarTint: UIColor? {
get { return progressBar.progressTintColor }
set { progressBar.progressTintColor = newValue }
}
dynamic var cancelTextColor: UIColor? {
get { return cancelButton.titleColorForState(UIControlState.Normal) }
set { return cancelButton.setTitleColor(newValue, forState: UIControlState.Normal) }
}
dynamic var actionButtonTintColor: UIColor? {
get { return helper?.buttonTintColor }
set {
guard let value = newValue else { return }
helper?.buttonTintColor = value
}
}
}
/* Code for drawing the urlbar curve */
// Curve's aspect ratio
private let ASPECT_RATIO = 0.729
// Width multipliers
private let W_M1 = 0.343
private let W_M2 = 0.514
private let W_M3 = 0.49
private let W_M4 = 0.545
private let W_M5 = 0.723
// Height multipliers
private let H_M1 = 0.25
private let H_M2 = 0.5
private let H_M3 = 0.72
private let H_M4 = 0.961
/* Code for drawing the urlbar curve */
private class CurveView: UIView {
private lazy var leftCurvePath: UIBezierPath = {
var leftArc = UIBezierPath(arcCenter: CGPoint(x: 5, y: 5), radius: CGFloat(5), startAngle: CGFloat(-M_PI), endAngle: CGFloat(-M_PI_2), clockwise: true)
leftArc.addLineToPoint(CGPoint(x: 0, y: 0))
leftArc.addLineToPoint(CGPoint(x: 0, y: 5))
leftArc.closePath()
return leftArc
}()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
self.opaque = false
self.contentMode = .Redraw
}
private func getWidthForHeight(height: Double) -> Double {
return height * ASPECT_RATIO
}
private func drawFromTop(path: UIBezierPath) {
let height: Double = Double(UIConstants.ToolbarHeight)
let width = getWidthForHeight(height)
let from = (Double(self.frame.width) - width * 2 - Double(URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer), Double(0))
path.moveToPoint(CGPoint(x: from.0, y: from.1))
path.addCurveToPoint(CGPoint(x: from.0 + width * W_M2, y: from.1 + height * H_M2),
controlPoint1: CGPoint(x: from.0 + width * W_M1, y: from.1),
controlPoint2: CGPoint(x: from.0 + width * W_M3, y: from.1 + height * H_M1))
path.addCurveToPoint(CGPoint(x: from.0 + width, y: from.1 + height),
controlPoint1: CGPoint(x: from.0 + width * W_M4, y: from.1 + height * H_M3),
controlPoint2: CGPoint(x: from.0 + width * W_M5, y: from.1 + height * H_M4))
}
private func getPath() -> UIBezierPath {
let path = UIBezierPath()
self.drawFromTop(path)
path.addLineToPoint(CGPoint(x: self.frame.width, y: UIConstants.ToolbarHeight))
path.addLineToPoint(CGPoint(x: self.frame.width, y: 0))
path.addLineToPoint(CGPoint(x: 0, y: 0))
path.closePath()
return path
}
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
CGContextClearRect(context, rect)
CGContextSetFillColorWithColor(context, URLBarViewUX.backgroundColorWithAlpha(1).CGColor)
getPath().fill()
leftCurvePath.fill()
CGContextDrawPath(context, CGPathDrawingMode.Fill)
CGContextRestoreGState(context)
}
}
class ToolbarTextField: AutocompleteTextField {
dynamic var clearButtonTintColor: UIColor? {
didSet {
// Clear previous tinted image that's cache and ask for a relayout
tintedClearImage = nil
setNeedsLayout()
}
}
private var tintedClearImage: UIImage?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
// Since we're unable to change the tint color of the clear image, we need to iterate through the
// subviews, find the clear button, and tint it ourselves. Thanks to Mikael Hellman for the tip:
// http://stackoverflow.com/questions/27944781/how-to-change-the-tint-color-of-the-clear-button-on-a-uitextfield
for view in subviews as [UIView] {
if let button = view as? UIButton {
if let image = button.imageForState(.Normal) {
if tintedClearImage == nil {
tintedClearImage = tintImage(image, color: clearButtonTintColor)
}
if button.imageView?.image != tintedClearImage {
button.setImage(tintedClearImage, forState: .Normal)
}
}
}
}
}
private func tintImage(image: UIImage, color: UIColor?) -> UIImage {
guard let color = color else { return image }
let size = image.size
UIGraphicsBeginImageContextWithOptions(size, false, 2)
let context = UIGraphicsGetCurrentContext()
image.drawAtPoint(CGPointZero, blendMode: CGBlendMode.Normal, alpha: 1.0)
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextSetBlendMode(context, CGBlendMode.SourceIn)
CGContextSetAlpha(context, 1.0)
let rect = CGRectMake(
CGPointZero.x,
CGPointZero.y,
image.size.width,
image.size.height)
CGContextFillRect(UIGraphicsGetCurrentContext(), rect)
let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return tintedImage
}
}
| mpl-2.0 | 7e503dd8902513641ffa40fe4990f064 | 39.534689 | 207 | 0.671939 | 5.527157 | false | false | false | false |
vector-im/riot-ios | Riot/Modules/Room/EmojiPicker/EmojiPickerViewController.swift | 1 | 12248 | // File created from ScreenTemplate
// $ createScreen.sh toto EmojiPicker
/*
Copyright 2019 New Vector Ltd
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 Reusable
final class EmojiPickerViewController: UIViewController {
// MARK: - Constants
private enum CollectionViewLayout {
static let sectionInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0)
static let minimumInteritemSpacing: CGFloat = 6.0
static let minimumLineSpacing: CGFloat = 2.0
static let itemSize = CGSize(width: 50, height: 50)
}
private static let sizingHeaderView = EmojiPickerHeaderView.loadFromNib()
// MARK: - Properties
// MARK: Outlets
@IBOutlet private weak var collectionView: UICollectionView!
// MARK: Private
private var viewModel: EmojiPickerViewModelType!
private var theme: Theme!
private var keyboardAvoider: KeyboardAvoider?
private var errorPresenter: MXKErrorPresentation!
private var activityPresenter: ActivityIndicatorPresenter!
private var searchController: UISearchController?
private var emojiCategories: [EmojiPickerCategoryViewData] = []
// MARK: - Setup
class func instantiate(with viewModel: EmojiPickerViewModelType) -> EmojiPickerViewController {
let viewController = StoryboardScene.EmojiPickerViewController.initialScene.instantiate()
viewController.viewModel = viewModel
viewController.theme = ThemeService.shared().theme
return viewController
}
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = VectorL10n.emojiPickerTitle
self.setupViews()
self.keyboardAvoider = KeyboardAvoider(scrollViewContainerView: self.view, scrollView: self.collectionView)
self.activityPresenter = ActivityIndicatorPresenter()
self.errorPresenter = MXKErrorAlertPresentation()
self.registerThemeServiceDidChangeThemeNotification()
self.update(theme: self.theme)
self.viewModel.viewDelegate = self
self.viewModel.process(viewAction: .loadData)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.keyboardAvoider?.startAvoiding()
// Update theme here otherwise the UISearchBar search text color is not updated
self.update(theme: self.theme)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Enable to hide search bar on scrolling after first time view appear
// Commenting out below code for now. It broke the navigation bar background. For details: https://github.com/vector-im/riot-ios/issues/3271
// if #available(iOS 11.0, *) {
// self.navigationItem.hidesSearchBarWhenScrolling = true
// }
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.keyboardAvoider?.stopAvoiding()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return self.theme.statusBarStyle
}
// MARK: - Private
private func update(theme: Theme) {
self.theme = theme
self.view.backgroundColor = theme.backgroundColor
if let navigationBar = self.navigationController?.navigationBar {
theme.applyStyle(onNavigationBar: navigationBar)
}
if let searchController = self.searchController {
theme.applyStyle(onSearchBar: searchController.searchBar)
}
}
private func registerThemeServiceDidChangeThemeNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil)
}
@objc private func themeDidChange() {
self.update(theme: ThemeService.shared().theme)
}
private func setupViews() {
let cancelBarButtonItem = MXKBarButtonItem(title: VectorL10n.cancel, style: .plain) { [weak self] in
self?.cancelButtonAction()
}
self.navigationItem.rightBarButtonItem = cancelBarButtonItem
self.setupCollectionView()
if #available(iOS 11.0, *) {
self.setupSearchController()
}
}
private func setupCollectionView() {
self.collectionView.delegate = self
self.collectionView.dataSource = self
self.collectionView.keyboardDismissMode = .interactive
if let collectionViewFlowLayout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
collectionViewFlowLayout.minimumInteritemSpacing = CollectionViewLayout.minimumInteritemSpacing
collectionViewFlowLayout.minimumLineSpacing = CollectionViewLayout.minimumLineSpacing
collectionViewFlowLayout.itemSize = CollectionViewLayout.itemSize
collectionViewFlowLayout.sectionInset = CollectionViewLayout.sectionInsets
collectionViewFlowLayout.sectionHeadersPinToVisibleBounds = true // Enable sticky headers
// Avoid device notch in landascape (e.g. iPhone X)
if #available(iOS 11.0, *) {
collectionViewFlowLayout.sectionInsetReference = .fromSafeArea
}
}
self.collectionView.register(supplementaryViewType: EmojiPickerHeaderView.self, ofKind: UICollectionView.elementKindSectionHeader)
self.collectionView.register(cellType: EmojiPickerViewCell.self)
}
private func setupSearchController() {
let searchController = UISearchController(searchResultsController: nil)
searchController.dimsBackgroundDuringPresentation = false
searchController.searchResultsUpdater = self
searchController.searchBar.placeholder = VectorL10n.searchDefaultPlaceholder
searchController.hidesNavigationBarDuringPresentation = false
if #available(iOS 11.0, *) {
self.navigationItem.searchController = searchController
// Make the search bar visible on first view appearance
self.navigationItem.hidesSearchBarWhenScrolling = false
}
self.definesPresentationContext = true
self.searchController = searchController
}
private func render(viewState: EmojiPickerViewState) {
switch viewState {
case .loading:
self.renderLoading()
case .loaded(emojiCategories: let emojiCategories):
self.renderLoaded(emojiCategories: emojiCategories)
case .error(let error):
self.render(error: error)
}
}
private func renderLoading() {
self.activityPresenter.presentActivityIndicator(on: self.view, animated: true)
}
private func renderLoaded(emojiCategories: [EmojiPickerCategoryViewData]) {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
self.update(emojiCategories: emojiCategories)
}
private func render(error: Error) {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil)
}
private func update(emojiCategories: [EmojiPickerCategoryViewData]) {
self.emojiCategories = emojiCategories
self.collectionView.reloadData()
}
private func emojiItemViewData(at indexPath: IndexPath) -> EmojiPickerItemViewData {
return self.emojiCategories[indexPath.section].emojiViewDataList[indexPath.row]
}
private func emojiCategoryViewData(at section: Int) -> EmojiPickerCategoryViewData? {
return self.emojiCategories[section]
}
private func headerViewSize(for title: String) -> CGSize {
let sizingHeaderView = EmojiPickerViewController.sizingHeaderView
sizingHeaderView.fill(with: title)
sizingHeaderView.setNeedsLayout()
sizingHeaderView.layoutIfNeeded()
var fittingSize = UIView.layoutFittingCompressedSize
fittingSize.width = self.collectionView.bounds.size.width
return sizingHeaderView.systemLayoutSizeFitting(fittingSize)
}
// MARK: - Actions
private func cancelButtonAction() {
self.viewModel.process(viewAction: .cancel)
}
}
// MARK: - UICollectionViewDataSource
extension EmojiPickerViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.emojiCategories.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.emojiCategories[section].emojiViewDataList.count
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let emojiPickerCategory = self.emojiCategories[indexPath.section]
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, for: indexPath) as EmojiPickerHeaderView
headerView.update(theme: self.theme)
headerView.fill(with: emojiPickerCategory.name)
return headerView
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: EmojiPickerViewCell = collectionView.dequeueReusableCell(for: indexPath)
if let theme = self.theme {
cell.update(theme: theme)
}
let viewData = self.emojiItemViewData(at: indexPath)
cell.fill(viewData: viewData)
return cell
}
}
// MARK: - UICollectionViewDelegate
extension EmojiPickerViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let emojiItemViewData = self.emojiItemViewData(at: indexPath)
self.viewModel.process(viewAction: .tap(emojiItemViewData: emojiItemViewData))
}
func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {
// Fix UICollectionView scroll bar appears underneath header view
view.layer.zPosition = 0.0
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension EmojiPickerViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
let emojiCategory = self.emojiCategories[section]
let headerSize = self.headerViewSize(for: emojiCategory.name)
return headerSize
}
}
// MARK: - EmojiPickerViewModelViewDelegate
extension EmojiPickerViewController: EmojiPickerViewModelViewDelegate {
func emojiPickerViewModel(_ viewModel: EmojiPickerViewModelType, didUpdateViewState viewSate: EmojiPickerViewState) {
self.render(viewState: viewSate)
}
}
// MARK: - UISearchResultsUpdating
extension EmojiPickerViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
let searchText = searchController.searchBar.text
self.viewModel.process(viewAction: .search(text: searchText))
}
}
| apache-2.0 | e6bfbd207ec84712ea78d213a5bbffef | 37.275 | 183 | 0.701094 | 5.857484 | false | false | false | false |
sahin/youtube-parser | YoutubeSourceParserKit/Youtube.swift | 5 | 6181 | //
// Youtube.swift
// youtube-parser
//
// Created by Toygar Dündaralp on 7/5/15.
// Copyright (c) 2015 Toygar Dündaralp. All rights reserved.
//
import UIKit
public extension NSURL {
/**
Parses a query string of an NSURL
@return key value dictionary with each parameter as an array
*/
func dictionaryForQueryString() -> [String: AnyObject]? {
if let query = self.query {
return query.dictionaryFromQueryStringComponents()
}
// Note: find youtube ID in m.youtube.com "https://m.youtube.com/#/watch?v=1hZ98an9wjo"
let result = absoluteString.componentsSeparatedByString("?")
if result.count > 1 {
return result.last?.dictionaryFromQueryStringComponents()
}
return nil
}
}
public extension NSString {
/**
Convenient method for decoding a html encoded string
*/
func stringByDecodingURLFormat() -> String {
let result = self.stringByReplacingOccurrencesOfString("+", withString:" ")
return result.stringByRemovingPercentEncoding!
}
/**
Parses a query string
@return key value dictionary with each parameter as an array
*/
func dictionaryFromQueryStringComponents() -> [String: AnyObject] {
var parameters = [String: AnyObject]()
for keyValue in componentsSeparatedByString("&") {
let keyValueArray = keyValue.componentsSeparatedByString("=")
if keyValueArray.count < 2 {
continue
}
let key = keyValueArray[0].stringByDecodingURLFormat()
let value = keyValueArray[1].stringByDecodingURLFormat()
parameters[key] = value
}
return parameters
}
}
public class Youtube: NSObject {
static let infoURL = "http://www.youtube.com/get_video_info?video_id="
static var userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4"
/**
Method for retrieving the youtube ID from a youtube URL
@param youtubeURL the the complete youtube video url, either youtu.be or youtube.com
@return string with desired youtube id
*/
public static func youtubeIDFromYoutubeURL(youtubeURL: NSURL) -> String? {
if let
youtubeHost = youtubeURL.host,
youtubePathComponents = youtubeURL.pathComponents {
let youtubeAbsoluteString = youtubeURL.absoluteString
if youtubeHost == "youtu.be" as String? {
return youtubePathComponents[1]
} else if youtubeAbsoluteString.rangeOfString("www.youtube.com/embed") != nil {
return youtubePathComponents[2]
} else if youtubeHost == "youtube.googleapis.com" ||
youtubeURL.pathComponents!.first == "www.youtube.com" as String? {
return youtubePathComponents[2]
} else if let
queryString = youtubeURL.dictionaryForQueryString(),
searchParam = queryString["v"] as? String {
return searchParam
}
}
return nil
}
/**
Method for retreiving a iOS supported video link
@param youtubeURL the the complete youtube video url
@return dictionary with the available formats for the selected video
*/
public static func h264videosWithYoutubeID(youtubeID: String) -> [String: AnyObject]? {
let urlString = String(format: "%@%@", infoURL, youtubeID) as String
let url = NSURL(string: urlString)!
let request = NSMutableURLRequest(URL: url)
request.timeoutInterval = 5.0
request.setValue(userAgent, forHTTPHeaderField: "User-Agent")
request.HTTPMethod = "GET"
var responseString = NSString()
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let group = dispatch_group_create()
dispatch_group_enter(group)
session.dataTaskWithRequest(request, completionHandler: { (data, response, _) -> Void in
if let data = data as NSData? {
responseString = NSString(data: data, encoding: NSUTF8StringEncoding)!
}
dispatch_group_leave(group)
}).resume()
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
let parts = responseString.dictionaryFromQueryStringComponents()
if parts.count > 0 {
var videoTitle: String = ""
var streamImage: String = ""
if let title = parts["title"] as? String {
videoTitle = title
}
if let image = parts["iurl"] as? String {
streamImage = image
}
if let fmtStreamMap = parts["url_encoded_fmt_stream_map"] as? String {
// Live Stream
if let _: AnyObject = parts["live_playback"]{
if let hlsvp = parts["hlsvp"] as? String {
return [
"url": "\(hlsvp)",
"title": "\(videoTitle)",
"image": "\(streamImage)",
"isStream": true
]
}
} else {
let fmtStreamMapArray = fmtStreamMap.componentsSeparatedByString(",")
for videoEncodedString in fmtStreamMapArray {
var videoComponents = videoEncodedString.dictionaryFromQueryStringComponents()
videoComponents["title"] = videoTitle
videoComponents["isStream"] = false
return videoComponents as [String: AnyObject]
}
}
}
}
return nil
}
/**
Block based method for retreiving a iOS supported video link
@param youtubeURL the the complete youtube video url
@param completeBlock the block which is called on completion
*/
public static func h264videosWithYoutubeURL(youtubeURL: NSURL,completion: ((
videoInfo: [String: AnyObject]?, error: NSError?) -> Void)?) {
let priority = DISPATCH_QUEUE_PRIORITY_BACKGROUND
dispatch_async(dispatch_get_global_queue(priority, 0)) {
if let youtubeID = self.youtubeIDFromYoutubeURL(youtubeURL), videoInformation = self.h264videosWithYoutubeID(youtubeID) {
dispatch_async(dispatch_get_main_queue()) {
completion?(videoInfo: videoInformation, error: nil)
}
}else{
dispatch_async(dispatch_get_main_queue()) {
completion?(videoInfo: nil, error: NSError(domain: "com.player.youtube.backgroundqueue", code: 1001, userInfo: ["error": "Invalid YouTube URL"]))
}
}
}
}
}
| mit | 53fd28288d72c23c6a7ce98b88b19326 | 35.134503 | 157 | 0.663214 | 4.801088 | false | false | false | false |
ProVir/WebServiceSwift | Source/WebService.swift | 1 | 33365 | //
// WebService.swift
// WebServiceSwift 3.0.0
//
// Created by Короткий Виталий (ViR) on 14.06.2017.
// Updated to 3.0.0 by Короткий Виталий (ViR) on 04.09.2018.
// Copyright © 2017 - 2018 ProVir. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
#endif
/// Controller for work. All requests are performed through it.
public class WebService {
/// Dependency type to next request (`performRequest()`). Use only to read from storage.
public enum ReadStorageDependencyType {
/// Not depend for next request
case notDepend
/// Ignore result from storage only after success response
case dependSuccessResult
/// As dependSuccessResult, but canceled read from storage after duplicated or canceled next request.
case dependFull
}
/// Perform response closures and delegates in dispath queue. Default: main thread.
public let queueForResponse: DispatchQueue
/// Ignore endpoint parameter ans always don't use networkActivityIndicator in statusBar when requests in process.
public var disableNetworkActivityIndicator = false
/**
Constructor for WebService.
- Parameters:
- endpoints: All sorted endpoints that support all requests.
- storages: All sorted storages that support all requests.
- queueForResponse: Dispatch Queue for results response. Thread for public method call and queueForResponse recommended be equal. Default: main thread.
*/
public init(endpoints: [WebServiceEndpoint],
storages: [WebServiceStorage],
queueForResponse: DispatchQueue = DispatchQueue.main) {
self.endpoints = endpoints
self.storages = storages
self.queueForResponse = queueForResponse
}
deinit {
let requestList = mutex.synchronized({ self.requestList })
let requestListIds = Set(requestList.keys)
//End networkActivityIndicator for all requests
WebService.staticMutex.synchronized {
WebService.networkActivityIndicatorRequestIds.subtract(requestListIds)
}
//Cancel all requests for endpoint
let queue = queueForResponse
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
for (_, requestData) in requestList {
requestData.cancel(queueForResponse: queue)
}
}
}
/// Clone WebService with only list endpoints, storages and queueForResponse.
public func clone() -> WebService {
return WebService(endpoints: endpoints, storages: storages, queueForResponse: queueForResponse)
}
//MARK: Private data
private static var staticMutex = PThreadMutexLock()
private var mutex = PThreadMutexLock()
private static var networkActivityIndicatorRequestIds = Set<UInt64>() {
didSet {
#if os(iOS)
let isVisible = !networkActivityIndicatorRequestIds.isEmpty
DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = isVisible }
#endif
}
}
private let endpoints: [WebServiceEndpoint]
private let storages: [WebServiceStorage]
private var requestList: [UInt64: RequestData] = [:] //All requests
private var requestsForTypes: [String: Set<UInt64>] = [:] //[Request.Type: [Id]]
private var requestsForHashs: [AnyHashable: Set<UInt64>] = [:] //[Request<Hashable>: [Id]]
private var requestsForKeys: [AnyHashable: Set<UInt64>] = [:] //[Key: [Id]]
private weak var readStorageDependNextRequestWait: ReadStorageDependRequestInfo?
// MARK: Perform requests
/**
Request to server (endpoint). Response result in closure.
- Parameters:
- request: The request with data and result type.
- completionHandler: Closure for response result from server.
*/
public func performRequest<RequestType: WebServiceRequesting>(_ request: RequestType, completionHandler: @escaping (_ response: WebServiceResponse<RequestType.ResultType>) -> Void) {
performBaseRequest(request, key: nil, excludeDuplicate: false, completionHandler: { completionHandler( $0.convert() ) })
}
/**
Request to server (endpoint). Response result in closure.
- Parameters:
- request: The request with data and result type.
- key: unique key for controling requests - contains and canceled. Also use for excludeDuplicate.
- excludeDuplicate: Exclude duplicate requests. Requests are equal if their keys match.
- completionHandler: Closure for response result from server.
*/
public func performRequest<RequestType: WebServiceRequesting>(_ request: RequestType, key: AnyHashable, excludeDuplicate: Bool, completionHandler: @escaping (_ response: WebServiceResponse<RequestType.ResultType>) -> Void) {
performBaseRequest(request, key: key, excludeDuplicate: excludeDuplicate, completionHandler: { completionHandler( $0.convert() ) })
}
/**
Request to server (endpoint). Response result in closure.
- Parameters:
- request: The hashable (also equatable) request with data and result type.
- excludeDuplicate: Exclude duplicate equatable requests.
- completionHandler: Closure for response result from server.
*/
public func performRequest<RequestType: WebServiceRequesting & Hashable>(_ request: RequestType, excludeDuplicate: Bool, completionHandler: @escaping (_ response: WebServiceResponse<RequestType.ResultType>) -> Void) {
performBaseRequest(request, key: nil, excludeDuplicate: excludeDuplicate, completionHandler: { completionHandler( $0.convert() ) })
}
/**
Request without support generic for server (endpoint). Response result in closure.
- Parameters:
- request: The request with data.
- key: Unique key for controling requests - contains and canceled. Also use for excludeDuplicate. Default: nil.
- excludeDuplicate: Exclude duplicate requests. Equal requests alogorithm: test for key if not null, else test requests equal if request is hashable.
- completionHandler: Closure for response result from server.
*/
public func performBaseRequest(_ request: WebServiceBaseRequesting,
key: AnyHashable? = nil,
excludeDuplicate: Bool = false,
completionHandler: @escaping (_ response: WebServiceAnyResponse) -> Void) {
//1. Depend from previous read storage.
weak var readStorageRequestInfo: ReadStorageDependRequestInfo? = readStorageDependNextRequestWait
readStorageDependNextRequestWait = nil
//2. Test duplicate requests
let requestHashable = request.asHashable
if excludeDuplicate, let key = key {
if containsRequest(key: key) {
readStorageRequestInfo?.setDuplicate()
completionHandler(.canceledRequest(duplicate: true))
return
}
} else if excludeDuplicate, let requestHashable = requestHashable {
if mutex.synchronized({ !(requestsForHashs[requestHashable]?.isEmpty ?? true) }) {
readStorageRequestInfo?.setDuplicate()
completionHandler(.canceledRequest(duplicate: true))
return
}
}
//3. Find Endpoint and Storage
guard let endpoint = internalFindEndpoint(request: request) else {
readStorageRequestInfo?.setState(.error)
completionHandler(.error(WebServiceRequestError.notFoundEndpoint))
return
}
let storage = internalFindStorage(request: request)
//4. Request in memory database and Perform request (Step #0 -> Step #4)
let requestType = type(of: request)
let requestId = internalNewRequestId()
var requestState = RequestState.inWork
//Step #4: Call this closure with result response
let completeHandlerResponse: (WebServiceAnyResponse) -> Void = { [weak self, queueForResponse = self.queueForResponse] response in
//Usually main thread
queueForResponse.async {
guard requestState == .inWork else { return }
self?.internalRemoveRequest(requestId: requestId, key: key, requestHashable: requestHashable, requestType: requestType)
switch response {
case .data(let data):
requestState = .completed
readStorageRequestInfo?.setState(requestState)
completionHandler(.data(data))
case .error(let error):
requestState = .error
readStorageRequestInfo?.setState(requestState)
completionHandler(.error(error))
case .canceledRequest(duplicate: let duplicate):
requestState = .canceled
readStorageRequestInfo?.setState(requestState)
completionHandler(.canceledRequest(duplicate: duplicate))
}
}
}
//Step #0: Add request to memory database
internalAddRequest(requestId: requestId, key: key, requestHashable: requestHashable, requestType: requestType, endpoint: endpoint, cancelHandler: {
//Canceled request
completeHandlerResponse(.canceledRequest(duplicate: false))
})
//Step #3: Data handler closure for raw data from server
let dataHandler: (Any) -> Void = { (data) in
do {
let resultData = try endpoint.dataProcessing(request: request,
rawData: data,
fromStorage: false)
storage?.writeData(request: request, data: data, isRaw: true)
storage?.writeData(request: request, data: resultData, isRaw: false)
completeHandlerResponse(.data(resultData))
} catch {
completeHandlerResponse(.error(error))
}
}
//Step #2: Beginer request closure
let requestHandler = {
endpoint.performRequest(requestId: requestId,
request: request,
completionWithRawData: { data in
//Raw data from server
guard requestState == .inWork else { return }
if let queue = endpoint.queueForDataProcessing {
queue.async { dataHandler(data) }
} else {
dataHandler(data)
}
},
completionWithError: { error in
//Error request
completeHandlerResponse(.error(error))
})
}
//Step #1: Call request in queue
if let queue = endpoint.queueForRequest {
queue.async(execute: requestHandler)
} else {
requestHandler()
}
}
//MARK: Read from storage
/**
Read last success data from storage. Response result in closure.
- Parameters:
- request: The request with data.
- dependencyNextRequest: Type dependency from next performRequest.
- completionHandler: Closure for read data from storage.
- timeStamp: TimeStamp when saved from server (endpoint).
- response: Result read from storage.
*/
public func readStorage<RequestType: WebServiceRequesting>(_ request: RequestType, dependencyNextRequest: ReadStorageDependencyType = .notDepend, completionHandler: @escaping (_ timeStamp: Date?, _ response: WebServiceResponse<RequestType.ResultType>) -> Void) {
if let storage = internalFindStorage(request: request) {
//CompletionResponse
let completionHandlerInternal:(_ timeStamp: Date?, _ response: WebServiceAnyResponse) -> Void = { completionHandler($0, $1.convert()) }
//Request
internalReadStorage(storage: storage, request: request, dependencyNextRequest: dependencyNextRequest, completionHandler: completionHandlerInternal)
} else {
completionHandler(nil, .error(WebServiceRequestError.notFoundStorage))
}
}
/**
Read last success data from storage without information result type data. Response result in closure.
- Parameters:
- request: The request with data.
- dependencyNextRequest: Type dependency from next performRequest.
- completionHandler: Closure for read data from storage.
- timeStamp: TimeStamp when saved from server (endpoint).
- response: Result read from storage.
*/
public func readStorageAnyData(_ request: WebServiceBaseRequesting,
dependencyNextRequest: ReadStorageDependencyType = .notDepend,
completionHandler: @escaping (_ timeStamp: Date?, _ response: WebServiceAnyResponse) -> Void) {
if let storage = internalFindStorage(request: request) {
internalReadStorage(storage: storage, request: request, dependencyNextRequest: dependencyNextRequest, completionHandler: completionHandler)
} else {
completionHandler(nil, .error(WebServiceRequestError.notFoundStorage))
}
}
// MARK: Perform requests use delegate for response
/**
Request to server (endpoint). Response result send to delegate.
- Parameters:
- request: The request with data.
- responseDelegate: Weak delegate for response from this request.
*/
public func performRequest(_ request: WebServiceBaseRequesting, responseDelegate: WebServiceDelegate?) {
internalPerformRequest(request, key: nil, excludeDuplicate: false, responseDelegate: responseDelegate)
}
/**
Request to server (endpoint). Response result send to delegate.
- Parameters:
- request: The request with data.
- key: unique key for controling requests - contains and canceled. Also use for excludeDuplicate.
- excludeDuplicate: Exclude duplicate requests. Requests are equal if their keys match.
- responseDelegate: Weak delegate for response from this request.
*/
public func performRequest(_ request: WebServiceBaseRequesting, key: AnyHashable, excludeDuplicate: Bool, responseDelegate: WebServiceDelegate?) {
internalPerformRequest(request, key: key, excludeDuplicate: excludeDuplicate, responseDelegate: responseDelegate)
}
/**
Request to server (endpoint). Response result send to delegate.
- Parameters:
- request: The hashable (also equatable) request with data.
- excludeDuplicate: Exclude duplicate equatable requests.
- responseDelegate: Weak delegate for response from this request.
*/
public func performRequest<RequestType: WebServiceBaseRequesting & Hashable>(_ request: RequestType, excludeDuplicate: Bool, responseDelegate: WebServiceDelegate?) {
internalPerformRequest(request, key: nil, excludeDuplicate: excludeDuplicate, responseDelegate: responseDelegate)
}
/**
Read last success data from storage. Response result send to delegate.
- Parameters:
- request: The request with data.
- key: unique key for controling requests, use only for response delegate.
- dependencyNextRequest: Type dependency from next performRequest.
- responseOnlyData: When `true` - response result send to delegate only if have data. Default false.
- responseDelegate: Weak delegate for response from this request.
*/
public func readStorage(_ request: WebServiceBaseRequesting, key: AnyHashable? = nil, dependencyNextRequest: ReadStorageDependencyType = .notDepend, responseOnlyData: Bool = false, responseDelegate delegate: WebServiceDelegate) {
readStorageAnyData(request, dependencyNextRequest: dependencyNextRequest) { [weak delegate] _, response in
if responseOnlyData == false { }
else if case .data = response { }
else { return }
if let delegate = delegate {
delegate.webServiceResponse(request: request, key: key, isStorageRequest: true, response: response)
}
}
}
// MARK: Contains requests
/// Returns a Boolean value indicating whether the current queue contains many requests.
public func containsManyRequests() -> Bool {
return mutex.synchronized { !requestList.isEmpty }
}
/**
Returns a Boolean value indicating whether the current queue contains the given request.
- Parameter request: The request to find in the current queue.
- Returns: `true` if the request was found in the current queue; otherwise, `false`.
*/
public func containsRequest<RequestType: WebServiceBaseRequesting & Hashable>(_ request: RequestType) -> Bool {
return mutex.synchronized { !(requestsForHashs[request]?.isEmpty ?? true) }
}
/**
Returns a Boolean value indicating whether the current queue contains requests the given type.
- Parameter requestType: The type request to find in the all current queue.
- Returns: `true` if one request with WebServiceBaseRequesting.Type was found in the current queue; otherwise, `false`.
*/
public func containsRequest(type requestType: WebServiceBaseRequesting.Type) -> Bool {
return mutex.synchronized { !(requestsForTypes["\(requestType)"]?.isEmpty ?? true) }
}
/**
Returns a Boolean value indicating whether the current queue contains the given request with key.
- Parameter key: The key to find requests in the current queue.
- Returns: `true` if the request with key was found in the current queue; otherwise, `false`.
*/
public func containsRequest(key: AnyHashable) -> Bool {
return mutex.synchronized { !(requestsForKeys[key]?.isEmpty ?? true) }
}
/**
Returns a Boolean value indicating whether the current queue contains requests the given type key.
- Parameter keyType: The type requestKey to find in the all current queue.
- Returns: `true` if one request with key.Type was found in the current queue; otherwise, `false`.
*/
public func containsRequest<K: Hashable>(keyType: K.Type) -> Bool {
return (internalListRequest(keyType: keyType, onlyFirst: true)?.count ?? 0) > 0
}
//MARK: Cancel requests
/// Cancel all requests in current queue.
public func cancelAllRequests() {
let requestList = mutex.synchronized { self.requestList }
internalCancelRequests(ids: Set(requestList.keys))
}
/**
Cancel all requests with equal this request.
- Parameter request: The request to find in the current queue.
*/
public func cancelRequests<RequestType: WebServiceBaseRequesting & Hashable>(_ request: RequestType) {
if let list = mutex.synchronized({ requestsForHashs[request] }) {
internalCancelRequests(ids: list)
}
}
/**
Cancel all requests for request type.
- Parameter requestType: The WebServiceBaseRequesting.Type to find in the current queue.
*/
public func cancelRequests(type requestType: WebServiceBaseRequesting.Type) {
if let list = mutex.synchronized({ requestsForTypes["\(requestType)"] }) {
internalCancelRequests(ids: list)
}
}
/**
Cancel all requests with key.
- Parameter key: The key to find in the current queue.
*/
public func cancelRequests(key: AnyHashable) {
if let list = mutex.synchronized({ requestsForKeys[key] }) {
internalCancelRequests(ids: list)
}
}
/**
Cancel all requests with key.Type.
- Parameter keyType: The key.Type to find in the current queue.
*/
public func cancelRequests<K: Hashable>(keyType: K.Type) {
if let list = internalListRequest(keyType: keyType, onlyFirst: false) {
internalCancelRequests(ids: list)
}
}
//MARK: Delete data in Storages
/**
Delete data in storage for concrete request.
- Parameter request: Original request.
*/
public func deleteInStorage(request: WebServiceBaseRequesting) {
if let storage = internalFindStorage(request: request) {
storage.deleteData(request: request)
}
}
/**
Delete all data in storages. Used only storages with support concrete data classification.
- Parameter with: Data Classification for find all storages.
*/
public func deleteAllInStorages(withDataClassification dataClassification: AnyHashable) {
for storage in self.storages {
let supportClasses = storage.supportDataClassification
if supportClasses.contains(dataClassification) {
storage.deleteAllData()
}
}
}
/**
Delete all data in storages. Used only storages with support any data classification.
*/
public func deleteAllInStoragesWithAnyDataClassification() {
for storage in self.storages {
let supportClasses = storage.supportDataClassification
if supportClasses.isEmpty {
storage.deleteAllData()
}
}
}
/**
Delete all data in all storages.
*/
public func deleteAllInStorages() {
for storage in self.storages {
storage.deleteAllData()
}
}
//MARK: - Private functions
private func internalPerformRequest(_ request: WebServiceBaseRequesting, key: AnyHashable?, excludeDuplicate: Bool, responseDelegate delegate: WebServiceDelegate?) {
performBaseRequest(request, key: key, excludeDuplicate: excludeDuplicate) { [weak delegate] response in
if let delegate = delegate {
delegate.webServiceResponse(request: request, key: key, isStorageRequest: false, response: response)
}
}
}
private func internalReadStorage(storage: WebServiceStorage, request: WebServiceBaseRequesting, dependencyNextRequest: ReadStorageDependencyType, completionHandler handler: @escaping (_ timeStamp: Date?, _ response: WebServiceAnyResponse) -> Void) {
let nextRequestInfo: ReadStorageDependRequestInfo?
let completionHandler: (_ timeStamp: Date?, _ response: WebServiceAnyResponse) -> Void
//1. Dependency setup
if dependencyNextRequest == .notDepend {
nextRequestInfo = nil
completionHandler = handler
} else {
nextRequestInfo = ReadStorageDependRequestInfo(dependencyType: dependencyNextRequest)
readStorageDependNextRequestWait = nextRequestInfo
completionHandler = { [weak self] timeStamp, response in
if self?.readStorageDependNextRequestWait === nextRequestInfo {
self?.readStorageDependNextRequestWait = nil
}
if nextRequestInfo?.canRead() ?? true {
handler(timeStamp, response)
} else if nextRequestInfo?.isDuplicate ?? false {
handler(timeStamp, .canceledRequest(duplicate: true))
} else {
handler(timeStamp, .canceledRequest(duplicate: false))
}
}
}
//2. Perform read
do {
try storage.readData(request: request) { [weak self, queueForResponse = self.queueForResponse] isRawData, timeStamp, response in
if (nextRequestInfo?.canRead() ?? true) == false {
self?.queueForResponse.async {
completionHandler(nil, .canceledRequest(duplicate: false))
}
} else if isRawData, let rawData = response.dataResponse() {
if let endpoint = self?.internalFindEndpoint(request: request, rawDataTypeForRestoreFromStorage: type(of: rawData)) {
//Handler closure with fined endpoint for use next
let handler = {
do {
let data = try endpoint.dataProcessing(request: request, rawData: rawData, fromStorage: true)
queueForResponse.async {
completionHandler(timeStamp, .data(data))
}
} catch {
queueForResponse.async {
completionHandler(nil, .error(error))
}
}
}
//Call handler
if let queue = endpoint.queueForDataProcessingFromStorage {
queue.async(execute: handler)
} else {
handler()
}
} else {
//Not found endpoint
queueForResponse.async {
completionHandler(nil, .error(WebServiceRequestError.notFoundEndpoint))
}
}
} else {
//No RAW data
self?.queueForResponse.async {
completionHandler(timeStamp, response)
}
}
}
} catch {
self.queueForResponse.async {
completionHandler(nil, .error(error))
}
}
}
// MARK: Find endpoints and storages
private func internalFindEndpoint(request: WebServiceBaseRequesting, rawDataTypeForRestoreFromStorage: Any.Type? = nil) -> WebServiceEndpoint? {
for endpoint in self.endpoints {
if endpoint.isSupportedRequest(request, rawDataTypeForRestoreFromStorage: rawDataTypeForRestoreFromStorage) {
return endpoint
}
}
return nil
}
private func internalFindStorage(request: WebServiceBaseRequesting) -> WebServiceStorage? {
let dataClass: AnyHashable
if let request = request as? WebServiceRequestBaseStoring {
dataClass = request.dataClassificationForStorage
} else {
dataClass = WebServiceDefaultDataClassification
}
for storage in self.storages {
let supportClasses = storage.supportDataClassification
if (supportClasses.isEmpty || supportClasses.contains(dataClass))
&& storage.isSupportedRequest(request) {
return storage
}
}
return nil
}
// MARK: Request Ids
private static var lastRequestId: UInt64 = 0
private func internalNewRequestId() -> UInt64 {
WebService.staticMutex.lock()
defer { WebService.staticMutex.unlock() }
WebService.lastRequestId = WebService.lastRequestId &+ 1
return WebService.lastRequestId
}
private func internalAddRequest(requestId: UInt64, key: AnyHashable?, requestHashable: AnyHashable?, requestType: WebServiceBaseRequesting.Type, endpoint: WebServiceEndpoint, cancelHandler: @escaping ()->Void) {
//Increment counts for visible NetworkActivityIndicator in StatusBar if need only for iOS
#if os(iOS)
if !disableNetworkActivityIndicator && endpoint.useNetworkActivityIndicator {
WebService.staticMutex.lock()
WebService.networkActivityIndicatorRequestIds.insert(requestId)
WebService.staticMutex.unlock()
}
#endif
//Thread safe
mutex.lock()
defer { mutex.unlock() }
requestList[requestId] = RequestData(requestId: requestId, endpoint: endpoint, cancelHandler: cancelHandler)
requestsForTypes["\(requestType)", default: Set<UInt64>()].insert(requestId)
if let key = key {
requestsForKeys[key, default: Set<UInt64>()].insert(requestId)
}
if let requestHashable = requestHashable {
requestsForHashs[requestHashable, default: Set<UInt64>()].insert(requestId)
}
}
private func internalRemoveRequest(requestId: UInt64, key: AnyHashable?, requestHashable: AnyHashable?, requestType: WebServiceBaseRequesting.Type) {
WebService.staticMutex.lock()
WebService.networkActivityIndicatorRequestIds.remove(requestId)
WebService.staticMutex.unlock()
//Thread safe
mutex.lock()
defer { mutex.unlock() }
requestList.removeValue(forKey: requestId)
let typeKey = "\(requestType)"
requestsForTypes[typeKey]?.remove(requestId)
if requestsForTypes[typeKey]?.isEmpty ?? false { requestsForTypes.removeValue(forKey: typeKey) }
if let key = key {
requestsForKeys[key]?.remove(requestId)
if requestsForKeys[key]?.isEmpty ?? false { requestsForKeys.removeValue(forKey: key) }
}
if let requestHashable = requestHashable {
requestsForHashs[requestHashable]?.remove(requestId)
if requestsForHashs[requestHashable]?.isEmpty ?? false { requestsForHashs.removeValue(forKey: requestHashable) }
}
}
private func internalListRequest<T: Hashable>(keyType: T.Type, onlyFirst: Bool) -> Set<UInt64>? {
mutex.lock()
defer { mutex.unlock() }
var ids = Set<UInt64>()
for (requestKey, requestIds) in requestsForKeys {
if requestKey.base is T {
if onlyFirst {
return requestIds
} else {
ids.formUnion(requestIds)
}
}
}
return ids.isEmpty ? nil : ids
}
private func internalCancelRequests(ids: Set<UInt64>) {
for requestId in ids {
if let requestData = mutex.synchronized({ self.requestList[requestId] }) {
requestData.cancel(queueForResponse: queueForResponse)
}
}
}
//MARK: Private types
private struct RequestData {
let requestId: UInt64
let endpoint: WebServiceEndpoint
let cancelHandler: ()->Void
func cancel(queueForResponse: DispatchQueue) {
cancelHandler()
let queue = endpoint.queueForRequest ?? queueForResponse
queue.async {
self.endpoint.canceledRequest(requestId: self.requestId)
}
}
}
private enum RequestState {
case inWork
case completed
case error
case canceled
}
private class ReadStorageDependRequestInfo {
private let mutex = PThreadMutexLock()
let dependencyType: ReadStorageDependencyType
private var _state: RequestState = .inWork
private var _isDuplicate: Bool = false
var state: RequestState { return mutex.synchronized { self._state } }
var isDuplicate: Bool { return mutex.synchronized { self._isDuplicate } }
init(dependencyType: ReadStorageDependencyType) {
self.dependencyType = dependencyType
}
func setDuplicate() {
mutex.synchronized {
self._isDuplicate = true
self._state = .canceled
}
}
func setState(_ state: RequestState) {
mutex.synchronized {
self._isDuplicate = false
self._state = state
}
}
func canRead() -> Bool {
switch dependencyType {
case .notDepend: return true
case .dependSuccessResult: return state != .completed
case .dependFull: return state != .completed && state != .canceled && !isDuplicate
}
}
}
}
| mit | af9f2caf10c6d556f5e4dec580aa3053 | 40.25495 | 266 | 0.605658 | 5.530778 | false | false | false | false |
yorcent/spdbapp | spdbapp/spdbapp/DocViewController.swift | 1 | 2195 | //
// DocViewController.swift
// spdbapp
//
// Created by tommy on 15/5/8.
// Copyright (c) 2015年 shgbit. All rights reserved.
//
import UIKit
class DocViewController: UIViewController, UIScrollViewDelegate,UIToolbarDelegate {
var url : String = ""
var fileIDInfo: String?
var fileNameInfo: String?
@IBOutlet weak var docView: UIWebView!
@IBOutlet var gesTap:UITapGestureRecognizer!
@IBOutlet weak var tbTop: UIToolbar!
override func viewDidLoad() {
super.viewDidLoad()
//初始化时候隐藏tab bar
hideBar()
//为uivewbview中的uiscrollerview添加代理
docView.scrollView.delegate = self
//为uitabbar添加代理
tbTop.delegate = self
gesTap.addTarget(self, action: "actionBar")
loadLocalPDFFile()
var timer = Poller()
timer.start(self, method: "timerDidFire:")
}
@IBAction func btnBack(sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func btnGoHistory(sender: UIBarButtonItem) {
NSLog("Go to history")
}
//屏幕滚动时,触发该事件
func scrollViewDidScroll(scrollView: UIScrollView){
hideBar()
}
//定时器函数,每隔5s自动隐藏tab bar
func timerDidFire(timer: NSTimer!){
if tbTop.hidden == false
{
tbTop.hidden = true
}
}
func actionBar(){
tbTop.hidden = !tbTop.hidden
}
func hideBar(){
tbTop.hidden = true
}
//获取本地pdf文档
func loadLocalPDFFile(){
var filePath: String = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(self.fileNameInfo!)")
var urlString = NSURL(fileURLWithPath: "\(filePath)")
var request = NSURLRequest(URL: urlString!)
self.docView.loadRequest(request)
println("path = \(filePath)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| bsd-3-clause | 1673975536e8ea6e50408364d3def56f | 22.043956 | 114 | 0.602289 | 4.568627 | false | false | false | false |
objcio/DominantColor | DominantColor/iOS/ViewController.swift | 2 | 2076 | //
// ViewController.swift
// Dominant Color iOS
//
// Created by Jamal E. Kharrat on 12/22/14.
// Copyright (c) 2014 Indragie Karunaratne. All rights reserved.
//
import UIKit
import DominantColor
class ViewController: UIViewController , UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet var boxes: [UIView]!
@IBOutlet weak var imageView: UIImageView!
var image: UIImage!
// MARK: IBActions
@IBAction func selectTapped(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .PhotoLibrary
self.presentViewController(imagePicker, animated: true, completion: nil)
}
@IBAction func runBenchmarkTapped(sender: AnyObject) {
if let image = image {
let nValues: [Int] = [100, 1000, 2000, 5000, 10000]
let CGImage = image.CGImage
for n in nValues {
let ns = dispatch_benchmark(5) {
dominantColorsInImage(CGImage, maxSampledPixels: n)
return
}
println("n = \(n) averaged \(ns/1000000) ms")
}
}
}
// MARK: ImagePicker Delegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
if let imageSelected = image {
self.image = imageSelected
imageView.image = imageSelected
let colors = imageSelected.dominantColors()
for box in boxes {
box.backgroundColor = UIColor.clearColor()
}
for i in 0..<min(colors.count, boxes.count) {
boxes[i].backgroundColor = colors[i]
}
}
picker.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
picker.dismissViewControllerAnimated(true, completion: nil);
}
}
| mit | f948875c0c9a48068140027948eeb6f7 | 31.4375 | 142 | 0.611272 | 5.164179 | false | false | false | false |
s4cha/then | Tests/ThenTests/MemoryTests.swift | 2 | 4699 | //
// MemoryTests.swift
// then
//
// Created by Sacha Durand Saint Omer on 09/08/2017.
// Copyright © 2017 s4cha. All rights reserved.
//
import XCTest
@testable import Then
class MemoryTests: XCTestCase {
func testRaceConditionWriteState() {
let p = Promise<String>()
func loopState() {
for i in 0...10000 {
p.updateState(PromiseState<String>.fulfilled(value: "Test1-\(i)"))
p.updateState(PromiseState<String>.fulfilled(value: "Test2-\(i)"))
p.updateState(PromiseState<String>.fulfilled(value: "Test3-\(i)"))
}
}
if #available(iOS 10.0, *) {
let t1 = Thread { loopState() }
let t2 = Thread { loopState() }
let t3 = Thread { loopState() }
let t4 = Thread { loopState() }
t1.start()
t2.start()
t3.start()
t4.start()
} else {
// Fallback on earlier versions
}
loopState()
}
func testRaceConditionReadState() {
let p = Promise("Hello")
func loopState() {
for i in 0...10000 {
p.updateState(PromiseState<String>.fulfilled(value: "Test1-\(i)"))
p.updateState(PromiseState<String>.fulfilled(value: "Test2-\(i)"))
p.updateState(PromiseState<String>.fulfilled(value: "Test3-\(i)"))
//Access Value
let value = p.value
print(value ?? "")
}
}
if #available(iOS 10.0, *) {
let t1 = Thread { loopState() }
let t2 = Thread { loopState() }
let t3 = Thread { loopState() }
let t4 = Thread { loopState() }
t1.start()
t2.start()
t3.start()
t4.start()
} else {
// Fallback on earlier versions
}
loopState()
}
func testRaceConditionResigterBlocks() {
let p = Promise<String>()
func loop() {
for _ in 0...1000 {
p.registerThen { _ in }
p.registerOnError { _ in }
p.registerFinally { }
p.progress { _ in }
}
}
if #available(iOS 10.0, *) {
let t1 = Thread { loop() }
let t2 = Thread { loop() }
let t3 = Thread { loop() }
let t4 = Thread { loop() }
t1.start()
t2.start()
t3.start()
t4.start()
} else {
// Fallback on earlier versions
}
loop()
}
func testRaceConditionWriteWriteBlocks() {
let p = Promise<String>()
func loop() {
for _ in 0...1000 {
p.blocks.success.append({ _ in })
p.blocks.fail.append({ _ in })
p.blocks.progress.append({ _ in })
p.blocks.finally.append({ })
}
}
if #available(iOS 10.0, *) {
let t1 = Thread { loop() }
let t2 = Thread { loop() }
let t3 = Thread { loop() }
let t4 = Thread { loop() }
t1.start()
t2.start()
t3.start()
t4.start()
} else {
// Fallback on earlier versions
}
loop()
}
func testRaceConditionWriteReadBlocks() {
let p = Promise<String>()
p.blocks.success.append({ _ in })
p.blocks.fail.append({ _ in })
p.blocks.progress.append({ _ in })
p.blocks.success.append({ _ in })
p.blocks.fail.append({ _ in })
p.blocks.progress.append({ _ in })
p.blocks.finally.append({ })
func loop() {
for _ in 0...10000 {
for sb in p.blocks.success {
sb("YO")
}
for fb in p.blocks.fail {
fb(PromiseError.default)
}
for p in p.blocks.progress {
p(0.5)
}
for fb in p.blocks.finally {
fb()
}
}
}
if #available(iOS 10.0, *) {
let t1 = Thread { loop() }
let t2 = Thread { loop() }
let t3 = Thread { loop() }
let t4 = Thread { loop() }
t1.start()
t2.start()
t3.start()
t4.start()
} else {
// Fallback on earlier versions
}
loop()
}
}
| mit | d0f3a410e4ad4907bef613191f94e420 | 27.646341 | 82 | 0.422733 | 4.329954 | false | true | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceModel/Tests/EurofurenceModelTests/Client API/EventFeedbackAPITests.swift | 1 | 2496 | import EurofurenceModel
import TestUtilities
import XCTest
import XCTEurofurenceModel
class EventFeedbackAPITests: XCTestCase {
private struct OutgoingFeedbackRequest: Decodable, Equatable {
var EventId: String
var Rating: Int
var Message: String
}
func testSubmittingFeedbackSubmitsExpectedPOSTRequest() {
let jsonSession = CapturingJSONSession()
let apiUrl = StubAPIURLProviding()
let api = JSONAPI(jsonSession: jsonSession, apiUrl: apiUrl)
let id = String.random
let rating = Int.random
let feedback = String.random
let request = EventFeedbackRequest(id: id, rating: rating, feedback: feedback)
api.submitEventFeedback(request) { (_) in }
let expectedFeedbackRequest = OutgoingFeedbackRequest(EventId: id, Rating: rating, Message: feedback)
let actualFeedbackRequest: OutgoingFeedbackRequest? = {
guard let data = jsonSession.POSTData else { return nil }
let encoder = JSONDecoder()
return try? encoder.decode(OutgoingFeedbackRequest.self, from: data)
}()
let expectedURL = "\(apiUrl.url)EventFeedback"
XCTAssertEqual(expectedURL, jsonSession.postedURL)
XCTAssertEqual(expectedFeedbackRequest, actualFeedbackRequest)
}
func testFeedbackSuccess() {
let jsonSession = CapturingJSONSession()
let apiUrl = StubAPIURLProviding()
let api = JSONAPI(jsonSession: jsonSession, apiUrl: apiUrl)
let request = EventFeedbackRequest(id: .random, rating: .random, feedback: .random)
var success = false
api.submitEventFeedback(request) { success = $0 }
XCTAssertFalse(success)
jsonSession.invokeLastPOSTCompletionHandler(responseData: Data())
XCTAssertTrue(success)
}
func testFeedbackFailure() {
let jsonSession = CapturingJSONSession()
let apiUrl = StubAPIURLProviding()
let api = JSONAPI(jsonSession: jsonSession, apiUrl: apiUrl)
let request = EventFeedbackRequest(id: .random, rating: .random, feedback: .random)
var success = false
api.submitEventFeedback(request) { success = $0 }
let error = NSError(domain: "", code: 0, userInfo: nil)
jsonSession.invokeLastPOSTCompletionHandler(responseData: nil, error: error)
XCTAssertFalse(success)
}
}
| mit | 124f3bdf60746d8f497bb53851184e0d | 35.705882 | 109 | 0.655849 | 5.167702 | false | true | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/RightSide/Search/Views/SearchView.swift | 1 | 7250 | //
// SearchView.swift
// zhuishushenqi
//
// Created by Nory Cao on 2017/3/11.
// Copyright © 2017年 QS. All rights reserved.
//
import UIKit
protocol SearchViewDelegate {
func searchViewClearButtonClicked()
func searchViewHotWordClick(index:Int)
}
class SearchView: UIView,UITableViewDataSource,UITableViewDelegate {
var delegate:SearchViewDelegate?
var hotWords = [String](){
didSet{
self.headerView = headView()
self.tableView.dataSource = self
self.tableView.delegate = self
self.addSubview(self.tableView)
}
}
var historyList:[String]?{
didSet{
self.tableView.reloadData()
}
}
var headerHeight:CGFloat = 0
var searchWords:String = ""
var books = [Book]()
var headerView:UIView?
var changeIndex = 0
fileprivate lazy var tableView:UITableView = {
let tableView = UITableView(frame: CGRect(x: 0, y:0, width: ScreenWidth, height: ScreenHeight - 114), style: .grouped)
tableView.dataSource = self
tableView.estimatedSectionHeaderHeight = 114
tableView.delegate = self
tableView.rowHeight = 44
// tableView.register(UINib (nibName: self.iden, bundle: nil), forCellReuseIdentifier: self.iden)
return tableView
}()
fileprivate var tagColor = [UIColor(red: 0.56, green: 0.77, blue: 0.94, alpha: 1.0),
UIColor(red: 0.75, green: 0.41, blue: 0.82, alpha: 1.0),
UIColor(red: 0.96, green: 0.74, blue: 0.49, alpha: 1.0),
UIColor(red: 0.57, green: 0.81, blue: 0.84, alpha: 1.0),
UIColor(red: 0.40, green: 0.80, blue: 0.72, alpha: 1.0),
UIColor(red: 0.91, green: 0.56, blue: 0.56, alpha: 1.0),
UIColor(red: 0.56, green: 0.77, blue: 0.94, alpha: 1.0),
UIColor(red: 0.75, green: 0.41, blue: 0.82, alpha: 1.0)]
fileprivate lazy var clearBtn:UIButton = {
let btn = UIButton(type: .custom)
btn.setTitle("清空", for: .normal)
btn.setImage(UIImage(named:"d_delete"), for: .normal)
btn.setTitleColor(UIColor.darkGray, for: .normal)
btn.frame = CGRect(x: self.bounds.width - 80, y: 11, width: 60, height: 21)
btn.addTarget(self, action: #selector(clearAction(btn:)), for: .touchUpInside)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
return btn
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.tableView.reloadData()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func headView()->UIView{
let headerView = UIView()
headerView.backgroundColor = UIColor.white
let label = UILabel()
label.frame = CGRect(x: 15, y: 20, width: 200, height: 21)
label.font = UIFont.systemFont(ofSize: 15)
label.textColor = UIColor.black
label.text = "大家都在搜"
headerView.addSubview(label)
let btn = UIButton(type: .custom)
btn.setImage(UIImage(named:"actionbar_refresh"), for: .normal)
btn.setTitle("换一批", for: .normal)
btn.setTitleColor(UIColor.darkGray, for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
btn.contentHorizontalAlignment = .right
btn.addTarget(self, action: #selector(changeHotWord(btn:)), for: .touchUpInside)
btn.frame = CGRect(x: self.bounds.width - 90, y: 20, width: 70, height: 21)
headerView.addSubview(btn)
var x:CGFloat = 20
var y:CGFloat = 10 + 21 + 20
let spacex:CGFloat = 10
let spacey:CGFloat = 10
let height:CGFloat = 20
var count = 0
for index in changeIndex..<(changeIndex + 6) {
count = index
if count >= hotWords.count {
count = count - hotWords.count
}
let width = hotWords[count].qs_width(UIFont.systemFont(ofSize: 11), height: 21) + 20
if x + width + 20 > ScreenWidth {
x = 20
y = y + spacey + height
}
let btn = UIButton(type: .custom)
btn.frame = CGRect(x: x, y: y, width: width, height: height)
btn.setTitle(hotWords[count], for: UIControl.State())
btn.titleLabel?.font = UIFont.systemFont(ofSize: 11)
btn.setTitleColor(UIColor.white, for: UIControl.State())
btn.backgroundColor = tagColor[index%tagColor.count]
btn.tag = count + 12121
btn.addTarget(self, action: #selector(hotWordSearchAction(btn:)), for: .touchUpInside)
btn.layer.cornerRadius = 2
headerView.addSubview(btn)
x = x + width + spacex
}
changeIndex = count + 1
headerHeight = y + height + 10
headerView.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: headerHeight)
return headerView
}
@objc func changeHotWord(btn:UIButton){
if changeIndex > self.hotWords.count {
}
let views = self.headerView?.subviews
for index in 0..<(views?.count ?? 0) {
let view = views?[index]
view?.removeFromSuperview()
}
self.headerView = headView()
self.tableView.reloadData()
}
@objc func hotWordSearchAction(btn:UIButton){
delegate?.searchViewHotWordClick(index: btn.tag - 12121)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (historyList?.count ?? 0) + 1
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "HotWords")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "HotWords")
}
cell?.backgroundColor = UIColor.white
cell?.selectionStyle = .none
cell?.textLabel?.textColor = UIColor.darkGray
if indexPath.row == 0 {
cell?.textLabel?.textColor = UIColor.black
cell?.textLabel?.text = "搜索历史"
clearBtn.removeFromSuperview()
cell?.contentView.addSubview(clearBtn)
cell?.imageView?.image = nil
}else{
cell?.imageView?.image = UIImage(named: "bs_last_read")
cell?.textLabel?.text = historyList?[indexPath.row - 1]
}
return cell!
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return self.headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return self.headerHeight
}
@objc func clearAction(btn:UIButton){
delegate?.searchViewClearButtonClicked()
}
}
| mit | fdc63d3ae205e5d8c74124aad59794b0 | 36.598958 | 126 | 0.581798 | 4.304711 | false | false | false | false |
ZhipingYang/UUChatSwift | UUChatTableViewSwift/Source/ConstraintAttributes.swift | 17 | 7117 | //
// SnapKit
//
// Copyright (c) 2011-2015 SnapKit Team - https://github.com/SnapKit
//
// 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.
#if os(iOS)
import UIKit
#else
import AppKit
#endif
/**
Used to define `NSLayoutAttributes` in a more concise and composite manner
*/
internal struct ConstraintAttributes: OptionSetType, BooleanType {
internal init(rawValue: UInt) {
self.rawValue = rawValue
}
internal init(_ rawValue: UInt) {
self.init(rawValue: rawValue)
}
internal init(nilLiteral: ()) {
self.rawValue = 0
}
internal private(set) var rawValue: UInt
internal static var allZeros: ConstraintAttributes { return self.init(0) }
internal static func convertFromNilLiteral() -> ConstraintAttributes { return self.init(0) }
internal var boolValue: Bool { return self.rawValue != 0 }
internal func toRaw() -> UInt { return self.rawValue }
internal static func fromRaw(raw: UInt) -> ConstraintAttributes? { return self.init(raw) }
internal static func fromMask(raw: UInt) -> ConstraintAttributes { return self.init(raw) }
// normal
internal static var None: ConstraintAttributes { return self.init(0) }
internal static var Left: ConstraintAttributes { return self.init(1) }
internal static var Top: ConstraintAttributes { return self.init(2) }
internal static var Right: ConstraintAttributes { return self.init(4) }
internal static var Bottom: ConstraintAttributes { return self.init(8) }
internal static var Leading: ConstraintAttributes { return self.init(16) }
internal static var Trailing: ConstraintAttributes { return self.init(32) }
internal static var Width: ConstraintAttributes { return self.init(64) }
internal static var Height: ConstraintAttributes { return self.init(128) }
internal static var CenterX: ConstraintAttributes { return self.init(256) }
internal static var CenterY: ConstraintAttributes { return self.init(512) }
internal static var Baseline: ConstraintAttributes { return self.init(1024) }
#if os(iOS)
internal static var FirstBaseline: ConstraintAttributes { return self.init(2048) }
internal static var LeftMargin: ConstraintAttributes { return self.init(4096) }
internal static var RightMargin: ConstraintAttributes { return self.init(8192) }
internal static var TopMargin: ConstraintAttributes { return self.init(16384) }
internal static var BottomMargin: ConstraintAttributes { return self.init(32768) }
internal static var LeadingMargin: ConstraintAttributes { return self.init(65536) }
internal static var TrailingMargin: ConstraintAttributes { return self.init(131072) }
internal static var CenterXWithinMargins: ConstraintAttributes { return self.init(262144) }
internal static var CenterYWithinMargins: ConstraintAttributes { return self.init(524288) }
#endif
// aggregates
internal static var Edges: ConstraintAttributes { return self.init(15) }
internal static var Size: ConstraintAttributes { return self.init(192) }
internal static var Center: ConstraintAttributes { return self.init(768) }
#if os(iOS)
internal static var Margins: ConstraintAttributes { return self.init(61440) }
internal static var CenterWithinMargins: ConstraintAttributes { return self.init(786432) }
#endif
internal var layoutAttributes:[NSLayoutAttribute] {
var attrs = [NSLayoutAttribute]()
if (self.contains(ConstraintAttributes.Left)) {
attrs.append(.Left)
}
if (self.contains(ConstraintAttributes.Top)) {
attrs.append(.Top)
}
if (self.contains(ConstraintAttributes.Right)) {
attrs.append(.Right)
}
if (self.contains(ConstraintAttributes.Bottom)) {
attrs.append(.Bottom)
}
if (self.contains(ConstraintAttributes.Leading)) {
attrs.append(.Leading)
}
if (self.contains(ConstraintAttributes.Trailing)) {
attrs.append(.Trailing)
}
if (self.contains(ConstraintAttributes.Width)) {
attrs.append(.Width)
}
if (self.contains(ConstraintAttributes.Height)) {
attrs.append(.Height)
}
if (self.contains(ConstraintAttributes.CenterX)) {
attrs.append(.CenterX)
}
if (self.contains(ConstraintAttributes.CenterY)) {
attrs.append(.CenterY)
}
if (self.contains(ConstraintAttributes.Baseline)) {
attrs.append(.Baseline)
}
#if os(iOS)
if (self.contains(ConstraintAttributes.FirstBaseline)) {
attrs.append(.FirstBaseline)
}
if (self.contains(ConstraintAttributes.LeftMargin)) {
attrs.append(.LeftMargin)
}
if (self.contains(ConstraintAttributes.RightMargin)) {
attrs.append(.RightMargin)
}
if (self.contains(ConstraintAttributes.TopMargin)) {
attrs.append(.TopMargin)
}
if (self.contains(ConstraintAttributes.BottomMargin)) {
attrs.append(.BottomMargin)
}
if (self.contains(ConstraintAttributes.LeadingMargin)) {
attrs.append(.LeadingMargin)
}
if (self.contains(ConstraintAttributes.TrailingMargin)) {
attrs.append(.TrailingMargin)
}
if (self.contains(ConstraintAttributes.CenterXWithinMargins)) {
attrs.append(.CenterXWithinMargins)
}
if (self.contains(ConstraintAttributes.CenterYWithinMargins)) {
attrs.append(.CenterYWithinMargins)
}
#endif
return attrs
}
}
internal func +=(inout left: ConstraintAttributes, right: ConstraintAttributes) {
left.unionInPlace(right)
}
internal func -=(inout left: ConstraintAttributes, right: ConstraintAttributes) {
left.subtractInPlace(right)
}
internal func ==(left: ConstraintAttributes, right: ConstraintAttributes) -> Bool {
return left.rawValue == right.rawValue
}
| mit | bc7f040ef4686ef2b6290bce5cf9dcc9 | 41.616766 | 96 | 0.686385 | 4.831636 | false | false | false | false |
dangnguyenhuu/JSQMessagesSwift | Sources/Views/JSQMessagesInputToolbar.swift | 1 | 5309 | //
// JSQMessagesInputToolbar.swift
// JSQMessagesViewController
//
// Created by Sylvain FAY-CHATELARD on 20/08/2015.
// Copyright (c) 2015 Dviance. All rights reserved.
//
import UIKit
let kJSQMessagesInputToolbarKeyValueObservingContext: UnsafeMutableRawPointer? = nil
public protocol JSQMessagesInputToolbarDelegate: UIToolbarDelegate {
func messagesInputToolbar(_ toolbar: JSQMessagesInputToolbar, didPressRightBarButton sender: UIButton)
func messagesInputToolbar(_ toolbar: JSQMessagesInputToolbar, didPressLeftBarButton sender: UIButton)
}
open class JSQMessagesInputToolbar: UIToolbar {
var toolbarDelegate: JSQMessagesInputToolbarDelegate? {
get { return self.delegate as? JSQMessagesInputToolbarDelegate }
set { self.delegate = newValue }
}
fileprivate(set) open var contentView: JSQMessagesToolbarContentView!
open var sendButtonOnRight: Bool = true
open var preferredDefaultHeight: CGFloat = 44
open var maximumHeight: Int = NSNotFound
fileprivate var jsq_isObserving: Bool = false
open override func awakeFromNib() {
super.awakeFromNib()
self.translatesAutoresizingMaskIntoConstraints = false
let toolbarContentView = self.loadToolbarContentView()
toolbarContentView.frame = self.frame
self.addSubview(toolbarContentView)
self.jsq_pinAllEdgesOfSubview(toolbarContentView)
self.setNeedsUpdateConstraints()
self.contentView = toolbarContentView
self.jsq_addObservers()
self.contentView.leftBarButtonItem = JSQMessagesToolbarButtonFactory.defaultAccessoryButtonItem()
self.contentView.rightBarButtonItem = JSQMessagesToolbarButtonFactory.defaultSendButtonItem()
self.toggleSendButtonEnabled()
}
func loadToolbarContentView() -> JSQMessagesToolbarContentView {
return Bundle(for: JSQMessagesToolbarContentView.self).loadNibNamed(JSQMessagesToolbarContentView.jsq_className, owner: nil, options: nil)!.first as! JSQMessagesToolbarContentView
}
deinit {
self.jsq_removeObservers()
self.contentView = nil
}
// MARK: - Input toolbar
func toggleSendButtonEnabled() {
let hasText = self.contentView.textView.hasText
if self.sendButtonOnRight {
self.contentView.rightBarButtonItem?.isEnabled = hasText
}
else {
self.contentView.leftBarButtonItem?.isEnabled = hasText
}
}
// MARK: - Actions
func jsq_leftBarButtonPressed(_ sender: UIButton) {
self.toolbarDelegate?.messagesInputToolbar(self, didPressLeftBarButton: sender)
}
func jsq_rightBarButtonPressed(_ sender: UIButton) {
self.toolbarDelegate?.messagesInputToolbar(self, didPressRightBarButton: sender)
}
// MARK: - Key-value observing
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == kJSQMessagesInputToolbarKeyValueObservingContext {
if let object = object as? JSQMessagesToolbarContentView {
if object == self.contentView {
if keyPath == "leftBarButtonItem" {
self.contentView.leftBarButtonItem?.removeTarget(self, action: nil, for: .touchUpInside)
self.contentView.leftBarButtonItem?.addTarget(self, action: #selector(JSQMessagesInputToolbar.jsq_leftBarButtonPressed(_:)), for: .touchUpInside)
}
else if keyPath == "rightBarButtonItem" {
self.contentView.rightBarButtonItem?.removeTarget(self, action: nil, for: .touchUpInside)
self.contentView.rightBarButtonItem?.addTarget(self, action: #selector(JSQMessagesInputToolbar.jsq_rightBarButtonPressed(_:)), for: .touchUpInside)
}
self.toggleSendButtonEnabled()
}
}
}
}
func jsq_addObservers() {
if self.jsq_isObserving {
return
}
self.contentView.addObserver(self, forKeyPath: "leftBarButtonItem", options: NSKeyValueObservingOptions(), context: kJSQMessagesInputToolbarKeyValueObservingContext)
self.contentView.addObserver(self, forKeyPath: "rightBarButtonItem", options: NSKeyValueObservingOptions(), context: kJSQMessagesInputToolbarKeyValueObservingContext)
self.jsq_isObserving = true
}
func jsq_removeObservers() {
if !self.jsq_isObserving {
return
}
self.contentView.removeObserver(self, forKeyPath: "leftBarButtonItem", context: kJSQMessagesInputToolbarKeyValueObservingContext)
self.contentView.removeObserver(self, forKeyPath: "rightBarButtonItem", context: kJSQMessagesInputToolbarKeyValueObservingContext)
self.jsq_isObserving = false
}
}
| apache-2.0 | ed477d6f6eb6bfde88549c89ab4ea75f | 35.613793 | 187 | 0.651912 | 6.032955 | false | false | false | false |
darina/omim | iphone/Maps/Classes/Components/Modal/AlertPresentationController.swift | 6 | 1276 | final class AlertPresentationController: DimmedModalPresentationController {
override var frameOfPresentedViewInContainerView: CGRect {
let f = super.frameOfPresentedViewInContainerView
let s = presentedViewController.view.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
let r = CGRect(x: 0, y: 0, width: s.width, height: s.height)
return r.offsetBy(dx: (f.width - r.width) / 2, dy: (f.height - r.height) / 2)
}
override func presentationTransitionWillBegin() {
super.presentationTransitionWillBegin()
presentedViewController.view.layer.cornerRadius = 12
presentedViewController.view.clipsToBounds = true
guard let containerView = containerView, let presentedView = presentedView else { return }
containerView.addSubview(presentedView)
presentedView.center = containerView.center
presentedView.frame = frameOfPresentedViewInContainerView
presentedView.autoresizingMask = [.flexibleLeftMargin, .flexibleTopMargin, .flexibleRightMargin, .flexibleBottomMargin]
}
override func dismissalTransitionDidEnd(_ completed: Bool) {
super.presentationTransitionDidEnd(completed)
guard let presentedView = presentedView else { return }
if completed {
presentedView.removeFromSuperview()
}
}
}
| apache-2.0 | 14b3acd21fce446f28970dbffc574b11 | 46.259259 | 123 | 0.775078 | 5.572052 | false | false | false | false |
progrmr/State_Hunt_swift | State_Hunt/UIColor+Additions.swift | 1 | 1750 | //
// UIColor+Additions.swift
// State_Hunt
//
// Created by Gary Morris on 7/4/14.
// Copyright (c) 2014 Gary Morris. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
// colors using 32 bit hex RGB values, like 0x00FF00 for pure green
convenience init(rgb:UInt32, alpha:CGFloat = 1.0) {
let red = CGFloat((rgb & 0xff0000) >> 16) / 255.0
let green = CGFloat((rgb & 0x00ff00) >> 8) / 255.0
let blue = CGFloat (rgb & 0x0000ff) / 255.0
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
// colors using 32 bit hex RGBA values, like 0xFF0000FF for pure red
convenience init(rgba: UInt32) {
let red = CGFloat((rgba & 0xff000000) >> 24) / 255.0
let green = CGFloat((rgba & 0x00ff0000) >> 16) / 255.0
let blue = CGFloat((rgba & 0x0000ff00) >> 8) / 255.0
let alpha = CGFloat (rgba & 0x000000ff) / 255.0
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
// r,g,b,a using CGFloats, all have defaults
// e.g.: UIColor(g:0.6) // gives dark green
// UIColor(r:1.0) // pure red
// UIColor(b:1.0, a:0.5) // blue with transparency
convenience init(r:CGFloat=0.0, g:CGFloat=0.0, b:CGFloat=0.0, a:CGFloat=1.0) {
self.init(red:r, green:g, blue:b, alpha:a)
}
// any gray from black (0.0) to white (1.0)
//
// e.g.: UIColor(gray:0.0) // black
// UIColor(gray:0.5) // middle gray
// UIColor(gray:0.8) // light gray
// UIColor(gray:1.0) // white
//
convenience init(gray:CGFloat) {
self.init(white:gray, alpha:1)
}
} | gpl-2.0 | 4d71f9d76c26e8ae56e9c88b0f1a439e | 32.673077 | 82 | 0.552 | 3.136201 | false | false | false | false |
rsyncOSX/RsyncOSX | RsyncOSX/ViewControllerSchedule.swift | 1 | 6403 | //
// ViewControllertabSchedule.swift
// RsyncOSXver30
//
// Created by Thomas Evensen on 19/08/2016.
// Copyright © 2016 Thomas Evensen. All rights reserved.
//
// swiftlint:disable line_length
import Cocoa
import Foundation
class ViewControllerSchedule: NSViewController, SetConfigurations, Checkforrsync, Setcolor, Help {
var schedulesobject: Schedules?
var sortedandexpanded: ScheduleSortedAndExpand?
var index: Int?
// var schedulessorted: ScheduleSortedAndExpand?
var schedule: Scheduletype?
// Scheduleetails
var scheduledetails: [NSMutableDictionary]?
var addschduleisallowed = false
var configurations: Estimatedlistforsynchronization?
// Main tableview
@IBOutlet var scheduletable: NSTableView!
@IBOutlet var info: NSTextField!
@IBOutlet var scheduletabledetails: NSTableView!
// Sidebar Once
@IBAction func once(_: NSButton) {
guard addschduleisallowed else { return }
schedule = .once
addschedule()
}
// Sidebar Daily
@IBAction func daily(_: NSButton) {
guard addschduleisallowed else { return }
schedule = .daily
addschedule()
}
// Sidebar Weekly
@IBAction func weekly(_: NSButton) {
guard addschduleisallowed else { return }
schedule = .weekly
addschedule()
}
// Sidebar update
@IBAction func update(_: NSButton) {
schedulesobject?.deleteandstopschedules(data: scheduledetails)
reloadtabledata()
}
@IBAction func selectdate(_: NSDatePicker) {
schedulebuttonsonoff()
}
@IBAction func selecttime(_: NSDatePicker) {
schedulebuttonsonoff()
}
private func addschedule() {
guard index != nil else { return }
let question: String = NSLocalizedString("Add Schedule?", comment: "Add schedule")
let text: String = NSLocalizedString("Cancel or Add", comment: "Add schedule")
let dialog: String = NSLocalizedString("Add", comment: "Add schedule")
let answer = Alerts.dialogOrCancel(question: question, text: text, dialog: dialog)
if answer {
info.stringValue = Infoschedule().info(num: 2)
let seconds: TimeInterval = starttime.dateValue.timeIntervalSinceNow
let startdate: Date = self.startdate.dateValue.addingTimeInterval(seconds)
if let index = index {
if let hiddenID = configurations?.gethiddenID(index: index),
let schedule = schedule
{
guard hiddenID != -1 else { return }
schedulesobject?.addschedule(hiddenID, schedule, startdate)
reloadtabledata()
}
}
}
}
private func schedulebuttonsonoff() {
let seconds: TimeInterval = starttime.dateValue.timeIntervalSinceNow
// Date and time for stop
let startime: Date = startdate.dateValue.addingTimeInterval(seconds)
let secondstostart = startime.timeIntervalSinceNow
if secondstostart < 60 {
selectedstart.isHidden = true
addschduleisallowed = false
}
if secondstostart > 60 {
addschduleisallowed = true
selectedstart.isHidden = false
selectedstart.stringValue = startime.localized_string_from_date() + " (" + Dateandtime().timestring(seconds: secondstostart) + ")"
selectedstart.textColor = setcolor(nsviewcontroller: self, color: .green)
}
}
@IBOutlet var startdate: NSDatePicker!
@IBOutlet var starttime: NSDatePicker!
@IBOutlet var selectedstart: NSTextField!
// Initial functions viewDidLoad and viewDidAppear
override func viewDidLoad() {
super.viewDidLoad()
configurations = Estimatedlistforsynchronization()
scheduletable.delegate = self
scheduletable.dataSource = self
scheduletabledetails.delegate = self
scheduletabledetails.dataSource = self
SharedReference.shared.setvcref(viewcontroller: .vcschedule, nsviewcontroller: self)
}
override func viewDidAppear() {
super.viewDidAppear()
info.stringValue = Infoschedule().info(num: 0)
selectedstart.isHidden = true
startdate.dateValue = Date()
starttime.dateValue = Date()
reloadtabledata()
}
override func viewDidDisappear() {
super.viewDidDisappear()
schedulesobject = nil
sortedandexpanded = nil
}
// setting which table row is selected
func tableViewSelectionDidChange(_ notification: Notification) {
let myTableViewFromNotification = (notification.object as? NSTableView)!
if myTableViewFromNotification == scheduletable {
info.stringValue = Infoschedule().info(num: 0)
let indexes = myTableViewFromNotification.selectedRowIndexes
if let index = indexes.first {
self.index = index
let hiddendID = configurations?.gethiddenID(index: self.index ?? -1)
scheduledetails = schedulesobject?.readscheduleonetask(hiddenID: hiddendID)
} else {
index = nil
scheduledetails = nil
}
globalMainQueue.async { () in
self.scheduletabledetails.reloadData()
self.scheduletable.reloadData()
}
}
}
func reloadtabledata() {
schedulesobject = nil
sortedandexpanded = nil
schedulesobject = Schedules()
sortedandexpanded = ScheduleSortedAndExpand()
if let index = index {
if let hiddendID = configurations?.gethiddenID(index: index) {
scheduledetails = schedulesobject?.readscheduleonetask(hiddenID: hiddendID)
}
}
globalMainQueue.async { () in
self.scheduletable.reloadData()
self.scheduletabledetails.reloadData()
}
}
}
extension ViewControllerSchedule: DismissViewController {
func dismiss_view(viewcontroller: NSViewController) {
dismiss(viewcontroller)
reloadtabledata()
}
}
// Deselect a row
extension ViewControllerSchedule: DeselectRowTable {
// deselect a row after row is deleted
func deselect() {
guard index != nil else { return }
scheduletable.deselectRow(index!)
}
}
| mit | fbfc06081428df10b731629d2cfd6aad | 33.053191 | 142 | 0.640737 | 4.820783 | false | false | false | false |
yonaskolb/XcodeGen | Tests/XcodeGenCoreTests/ArrayExtensionsTests.swift | 1 | 1077 | import XCTest
@testable import XcodeGenCore
class ArrayExtensionsTests: XCTestCase {
func testSearchingForFirstIndex() {
let array = SortedArray([1, 2, 3, 4 ,5])
XCTAssertEqual(array.firstIndex(where: { $0 > 2 }), 2)
}
func testIndexCannotBeFound() {
let array = SortedArray([1, 2, 3, 4, 5])
XCTAssertEqual(array.firstIndex(where: { $0 > 10 }), nil)
}
func testEmptyArray() {
let array = SortedArray([Int]())
XCTAssertEqual(array.firstIndex(where: { $0 > 0 }), nil)
}
func testSearchingReturnsFirstIndexWhenMultipleElementsHaveSameValue() {
let array = SortedArray([1, 2, 3, 3 ,3])
XCTAssertEqual(array.firstIndex(where: { $0 == 3 }), 2)
}
}
class SortedArrayTests: XCTestCase {
func testSortingOnInitialization() {
let array = [1, 5, 4, 2]
let sortedArray = SortedArray(array)
XCTAssertEqual([1, 2, 4, 5], sortedArray.value)
}
func testEmpty() {
XCTAssertEqual([Int](), SortedArray([Int]()).value)
}
}
| mit | c8d257467600ba6df4be92cba467029b | 25.925 | 76 | 0.601671 | 4.142308 | false | true | false | false |
quickthyme/PUTcat | PUTcat/Presentation/_Shared/StoryboardEmbeddable/StoryboardEmbeddableTransition/StoryboardEmbeddableTransitionFade.swift | 1 | 2083 |
import UIKit
class StoryboardEmbeddableTransitionSlowFade : StoryboardEmbeddableTransitionFade {
fileprivate override func getDuration() -> TimeInterval { return 0.8 }
}
class StoryboardEmbeddableTransitionFade : StoryboardEmbeddableTransition {
func embed(viewController: UIViewController, inViewController: UIViewController, inView: UIView, completion:(()->())?) {
guard let view = viewController.view else { return }
view.frame = inView.bounds
view.translatesAutoresizingMaskIntoConstraints = true
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
viewController.willMove(toParentViewController: inViewController)
if let existing = inViewController.childViewControllers.last {
inView.insertSubview(view, belowSubview: existing.view)
self.deEmbed(viewController: existing, fromViewController: inViewController, completion: {
inViewController.addChildViewController(viewController)
viewController.didMove(toParentViewController: inViewController)
completion?()
})
} else {
DispatchQueue.main.async {
inView.addSubview(view)
inViewController.addChildViewController(viewController)
viewController.didMove(toParentViewController: inViewController)
completion?()
}
}
}
func deEmbed(viewController: UIViewController, fromViewController: UIViewController, completion: (()->())?) {
guard let view = viewController.view else { return }
viewController.willMove(toParentViewController: nil)
UIView.animate(
withDuration: self.getDuration(),
animations: { view.alpha = 0.0 },
completion: { _ in
view.removeFromSuperview()
viewController.removeFromParentViewController()
completion?()
})
}
fileprivate func getDuration() -> TimeInterval { return 0.28 }
}
| apache-2.0 | a68aa44268e10b6f414e2123b8a3ce21 | 39.057692 | 124 | 0.650504 | 6.429012 | false | false | false | false |
banxi1988/BXAppKit | BXForm/View/ExpandableTextView.swift | 1 | 4426 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import UIKit
open class ExpandableTextView: UITextView {
fileprivate let placeholder: UITextView = UITextView()
public init(frame: CGRect) {
super.init(frame: frame, textContainer: nil)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
override open var contentSize: CGSize {
didSet {
self.invalidateIntrinsicContentSize()
self.onContentSizeChangedCallback?(contentSize)
self.layoutIfNeeded() // needed?
}
}
open var onContentSizeChangedCallback:( (CGSize) -> Void )?
open var onTextDidChangeCallback: ((String) -> Void)?
deinit {
NotificationCenter.default.removeObserver(self)
}
fileprivate func commonInit() {
NotificationCenter.default.addObserver(self, selector: #selector(ExpandableTextView.textDidChange), name: NSNotification.Name.UITextViewTextDidChange, object: self)
self.configurePlaceholder()
self.updatePlaceholderVisibility()
}
override open func layoutSubviews() {
super.layoutSubviews()
self.placeholder.frame = self.bounds
}
override open var intrinsicContentSize : CGSize {
return self.contentSize
}
override open var text: String! {
didSet {
self.textDidChange()
}
}
override open var textContainerInset: UIEdgeInsets {
didSet {
self.configurePlaceholder()
}
}
override open var textAlignment: NSTextAlignment {
didSet {
self.configurePlaceholder()
}
}
open func setTextPlaceholder(_ textPlaceholder: String) {
self.placeholder.text = textPlaceholder
}
open func setTextPlaceholderColor(_ color: UIColor) {
self.placeholder.textColor = color
}
open func setTextPlaceholderFont(_ font: UIFont) {
self.placeholder.font = font
}
@objc func textDidChange() {
self.updatePlaceholderVisibility()
self.scrollToCaret()
onTextDidChangeCallback?(text)
}
fileprivate func scrollToCaret() {
if selectedTextRange != nil {
var rect = caretRect(for: self.selectedTextRange!.end)
rect = CGRect(origin: rect.origin, size: CGSize(width: rect.width, height: rect.height + textContainerInset.bottom))
self.scrollRectToVisible(rect, animated: false)
}
}
fileprivate func updatePlaceholderVisibility() {
if text == "" {
self.showPlaceholder()
} else {
self.hidePlaceholder()
}
}
fileprivate func showPlaceholder() {
self.addSubview(placeholder)
}
fileprivate func hidePlaceholder() {
self.placeholder.removeFromSuperview()
}
fileprivate func configurePlaceholder() {
self.placeholder.translatesAutoresizingMaskIntoConstraints = false
self.placeholder.isEditable = false
self.placeholder.isSelectable = false
self.placeholder.isUserInteractionEnabled = false
self.placeholder.textAlignment = textAlignment
self.placeholder.textContainerInset = textContainerInset
self.placeholder.backgroundColor = UIColor.clear
}
}
| mit | 3b6f4831521c1ec2197c3c0c2c35a69c | 30.169014 | 172 | 0.683913 | 5.281623 | false | false | false | false |
airbnb/lottie-ios | Sources/Private/Model/Assets/AssetLibrary.swift | 3 | 2228 | //
// AssetLibrary.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/9/19.
//
import Foundation
final class AssetLibrary: Codable, AnyInitializable {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
var containerForKeys = container
var decodedAssets = [String : Asset]()
var imageAssets = [String : ImageAsset]()
var precompAssets = [String : PrecompAsset]()
while !container.isAtEnd {
let keyContainer = try containerForKeys.nestedContainer(keyedBy: PrecompAsset.CodingKeys.self)
if keyContainer.contains(.layers) {
let precompAsset = try container.decode(PrecompAsset.self)
decodedAssets[precompAsset.id] = precompAsset
precompAssets[precompAsset.id] = precompAsset
} else {
let imageAsset = try container.decode(ImageAsset.self)
decodedAssets[imageAsset.id] = imageAsset
imageAssets[imageAsset.id] = imageAsset
}
}
assets = decodedAssets
self.precompAssets = precompAssets
self.imageAssets = imageAssets
}
init(value: Any) throws {
guard let dictionaries = value as? [[String: Any]] else {
throw InitializableError.invalidInput
}
var decodedAssets = [String : Asset]()
var imageAssets = [String : ImageAsset]()
var precompAssets = [String : PrecompAsset]()
try dictionaries.forEach { dictionary in
if dictionary[PrecompAsset.CodingKeys.layers.rawValue] != nil {
let asset = try PrecompAsset(dictionary: dictionary)
decodedAssets[asset.id] = asset
precompAssets[asset.id] = asset
} else {
let asset = try ImageAsset(dictionary: dictionary)
decodedAssets[asset.id] = asset
imageAssets[asset.id] = asset
}
}
assets = decodedAssets
self.precompAssets = precompAssets
self.imageAssets = imageAssets
}
// MARK: Internal
/// The Assets
let assets: [String: Asset]
let imageAssets: [String: ImageAsset]
let precompAssets: [String: PrecompAsset]
func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(contentsOf: Array(assets.values))
}
}
| apache-2.0 | 7f295cd35a0fe505f8f4735e29781fa9 | 28.706667 | 100 | 0.682675 | 4.251908 | false | false | false | false |
SomeHero/iShopAwayAPIManager | IShopAwayApiManager/Classes/models/ShoppingSession.swift | 1 | 1931 | //
// ShoppingSession.swift
// PersonalShopper
//
// Created by James Rhodes on 5/16/16.
// Copyright © 2016 James Rhodes. All rights reserved.
//
import Foundation
import ObjectMapper
public class ShoppingSession: Mappable {
public static var sharedShoppingSession: ShoppingSession?
public var id: String?
public var shopper: User?
public var openTokSessionId: String?
public var openTokToken: String?
public var personalShopper: User?
public var cart: [CartItem]!
public init(shopper: User, openTokSessionId: String, openTokToken: String) {
self.shopper = shopper
self.openTokSessionId = openTokSessionId
self.openTokToken = openTokToken
}
public required init?(_ map: Map){
mapping(map)
}
public func mapping(map: Map) {
id <- map["_id"]
//shopper <- map["shopper"]
openTokSessionId <- map["opentok_session_id"]
openTokToken <- map["opentok_token"]
personalShopper <- map["personal_shopper"]
cart <- map["cart"]
}
}
public class CartItem: Mappable {
public var itemName: String!
public var imageUrl: String!
public var itemLocalCost: NSDecimalNumber!
public var itemShopperPrice: NSDecimalNumber!
public init(itemName: String, imageUrl: String, itemLocalCost: NSDecimalNumber, itemShopperPrice: NSDecimalNumber) {
self.itemName = itemName
self.imageUrl = imageUrl
self.itemLocalCost = itemLocalCost
self.itemShopperPrice = itemShopperPrice
}
public required init?(_ map: Map){
mapping(map)
}
public func mapping(map: Map) {
self.itemName <- map["item_name"]
self.imageUrl <- map["image_url"]
self.itemLocalCost <- (map["item_local_cost"], NSDecimalNumberTransform())
self.itemShopperPrice <- (map["item_shopper_price"], NSDecimalNumberTransform())
}
} | mit | 9ba6721cd7ead3587891db273fbee2fb | 30.145161 | 120 | 0.659067 | 4.317673 | false | false | false | false |
myTargetSDK/mytarget-ios | myTargetDemoSwift/myTargetDemo/Views/CustomButton.swift | 1 | 1169 | //
// CustomButton.swift
// myTargetDemo
//
// Created by Andrey Seredkin on 23/07/2019.
// Copyright © 2019 Mail.Ru Group. All rights reserved.
//
import UIKit
final class CustomButton: UIButton {
init(title: String) {
super.init(frame: .zero)
setTitle(title, for: .normal)
setup()
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
guard #available(iOS 13.0, *), traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) else {
return
}
layer.borderColor = UIColor.foregroundColor().cgColor
}
private func setup() {
layer.borderWidth = 0.3
layer.cornerRadius = 4.0
backgroundColor = .backgroundColor()
setTitleColor(.disabledColor(), for: .disabled)
setTitleColor(.foregroundColor(), for: .normal)
layer.borderColor = UIColor.foregroundColor().cgColor
}
}
| lgpl-3.0 | da3edd4eb2d587c440e2201c11143639 | 26.809524 | 126 | 0.657534 | 4.767347 | false | false | false | false |
HongliYu/firefox-ios | Client/Frontend/Settings/SyncContentSettingsViewController.swift | 1 | 7885 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Sync
class ManageSetting: Setting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return "Manage" }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: Strings.FxAManageAccount, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = FxAContentViewController(profile: profile)
if let account = profile.getAccount() {
var cs = URLComponents(url: account.configuration.settingsURL, resolvingAgainstBaseURL: false)
cs?.queryItems?.append(URLQueryItem(name: "email", value: account.email))
if let url = try? cs?.asURL() {
viewController.url = url
}
}
navigationController?.pushViewController(viewController, animated: true)
}
}
class DisconnectSetting: Setting {
let settingsVC: SettingsTableViewController
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .none }
override var textAlignment: NSTextAlignment { return .center }
override var title: NSAttributedString? {
return NSAttributedString(string: Strings.SettingsDisconnectSyncButton, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.general.destructiveRed])
}
init(settings: SettingsTableViewController) {
self.settingsVC = settings
self.profile = settings.profile
}
override var accessibilityIdentifier: String? { return "SignOut" }
override func onClick(_ navigationController: UINavigationController?) {
let alertController = UIAlertController(
title: Strings.SettingsDisconnectSyncAlertTitle,
message: Strings.SettingsDisconnectSyncAlertBody,
preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(
UIAlertAction(title: Strings.SettingsDisconnectCancelAction, style: .cancel) { (action) in
// Do nothing.
})
alertController.addAction(
UIAlertAction(title: Strings.SettingsDisconnectDestructiveAction, style: .destructive) { (action) in
FxALoginHelper.sharedInstance.applicationDidDisconnect(UIApplication.shared)
LeanPlumClient.shared.set(attributes: [LPAttributeKey.signedInSync: self.profile.hasAccount()])
// If there is more than one view controller in the navigation controller, we can pop.
// Otherwise, assume that we got here directly from the App Menu and dismiss the VC.
if let navigationController = navigationController, navigationController.viewControllers.count > 1 {
_ = navigationController.popViewController(animated: true)
} else {
self.settingsVC.dismiss(animated: true, completion: nil)
}
})
navigationController?.present(alertController, animated: true, completion: nil)
}
}
class DeviceNamePersister: SettingValuePersister {
let profile: Profile
init(profile: Profile) {
self.profile = profile
}
func readPersistedValue() -> String? {
return self.profile.getAccount()?.deviceName
}
func writePersistedValue(value: String?) {
guard let newName = value,
let account = self.profile.getAccount() else {
return
}
account.updateDeviceName(newName)
self.profile.flushAccount()
_ = self.profile.syncManager.syncNamedCollections(why: .clientNameChanged, names: ["clients"])
}
}
class DeviceNameSetting: StringSetting {
init(settings: SettingsTableViewController) {
let settingsIsValid: (String?) -> Bool = { !($0?.isEmpty ?? true) }
super.init(defaultValue: DeviceInfo.defaultClientName(), placeholder: "", accessibilityIdentifier: "DeviceNameSetting", persister: DeviceNamePersister(profile: settings.profile), settingIsValid: settingsIsValid)
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
textField.textAlignment = .natural
}
}
class SyncContentSettingsViewController: SettingsTableViewController {
fileprivate var enginesToSyncOnExit: Set<String> = Set()
init() {
super.init(style: .grouped)
self.title = Strings.FxASettingsTitle
hasSectionSeparatorLine = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillDisappear(_ animated: Bool) {
if !enginesToSyncOnExit.isEmpty {
_ = self.profile.syncManager.syncNamedCollections(why: SyncReason.engineEnabled, names: Array(enginesToSyncOnExit))
enginesToSyncOnExit.removeAll()
}
super.viewWillDisappear(animated)
}
func engineSettingChanged(_ engineName: String) -> (Bool) -> Void {
let prefName = "sync.engine.\(engineName).enabledStateChanged"
return { enabled in
if let _ = self.profile.prefs.boolForKey(prefName) { // Switch it back to not-changed
self.profile.prefs.removeObjectForKey(prefName)
self.enginesToSyncOnExit.remove(engineName)
} else {
self.profile.prefs.setBool(true, forKey: prefName)
self.enginesToSyncOnExit.insert(engineName)
}
}
}
override func generateSettings() -> [SettingSection] {
let manage = ManageSetting(settings: self)
let manageSection = SettingSection(title: nil, footerTitle: nil, children: [manage])
let bookmarks = BoolSetting(prefs: profile.prefs, prefKey: "sync.engine.bookmarks.enabled", defaultValue: true, attributedTitleText: NSAttributedString(string: Strings.FirefoxSyncBookmarksEngine), attributedStatusText: nil, settingDidChange: engineSettingChanged("bookmarks"))
let history = BoolSetting(prefs: profile.prefs, prefKey: "sync.engine.history.enabled", defaultValue: true, attributedTitleText: NSAttributedString(string: Strings.FirefoxSyncHistoryEngine), attributedStatusText: nil, settingDidChange: engineSettingChanged("history"))
let tabs = BoolSetting(prefs: profile.prefs, prefKey: "sync.engine.tabs.enabled", defaultValue: true, attributedTitleText: NSAttributedString(string: Strings.FirefoxSyncTabsEngine), attributedStatusText: nil, settingDidChange: engineSettingChanged("tabs"))
let passwords = BoolSetting(prefs: profile.prefs, prefKey: "sync.engine.passwords.enabled", defaultValue: true, attributedTitleText: NSAttributedString(string: Strings.FirefoxSyncLoginsEngine), attributedStatusText: nil, settingDidChange: engineSettingChanged("passwords"))
let enginesSection = SettingSection(title: NSAttributedString(string: Strings.FxASettingsSyncSettings), footerTitle: nil, children: [bookmarks, history, tabs, passwords])
let deviceName = DeviceNameSetting(settings: self)
let deviceNameSection = SettingSection(title: NSAttributedString(string: Strings.FxASettingsDeviceName), footerTitle: nil, children: [deviceName])
let disconnect = DisconnectSetting(settings: self)
let disconnectSection = SettingSection(title: nil, footerTitle: nil, children: [disconnect])
return [manageSection, enginesSection, deviceNameSection, disconnectSection]
}
}
| mpl-2.0 | 8fa1668b03db775e94273013fdd6aa8e | 45.656805 | 284 | 0.706405 | 5.221854 | false | false | false | false |
thanhtrdang/FluentYogaKit | FluentYogaKit/ViewController.swift | 1 | 3639 | //
// ViewController.swift
// FluentYogaKit
//
// Created by Thanh Dang on 5/24/17.
// Copyright © 2017 Thanh Dang. All rights reserved.
//
import FluentSwift
import UIKit
class ViewController: UIViewController {
fileprivate var titleLabel: UILabel!
fileprivate var usernameLabel: UILabel!
fileprivate var usernameTextField: UITextField!
fileprivate var passwordLabel: UILabel!
fileprivate var passwordTextField: UITextField!
fileprivate var forgotPasswordButton: UIButton!
fileprivate var signInButton: UIButton!
fileprivate var signUpLabel: UILabel!
fileprivate var signUpButton: UIButton!
fileprivate var rootLayout: YGLayout!
fileprivate var formLayout: YGLayout!
override func viewDidLoad() {
super.viewDidLoad()
configHeader()
configForm()
configFooter()
Duration.measure("Layout") {
applyLayout()
}
}
fileprivate func configHeader() {
titleLabel = UILabel().then {
$0.text("HOMELAND")
$0.textColor = .black
$0.font = .h1Medium
}
}
fileprivate func configForm() {
usernameLabel = UILabel().then {
$0.text("Username")
$0.textColor = .lightGray
$0.font = .h5
}
usernameTextField = UITextField().then {
$0.placeholder("[email protected]")
$0.font = .h4
}
passwordLabel = UILabel().then {
$0.text("Password")
$0.textColor = .lightGray
$0.font = .h5
}
passwordTextField = UITextField().then {
$0.isSecureTextEntry = true
$0.placeholder("At least 8 characters")
$0.font = .h4
}
forgotPasswordButton = UIButton().then {
$0.title("Forgot password?")
$0.titleLabel?.font = .h4
$0.setTitleColor(.black, for: .normal)
}
signInButton = UIButton().then {
$0.title("Sign in")
$0.titleLabel?.font = .h4
$0.setTitleColor(.black, for: .normal)
$0.addTarget(self, action: #selector(signInButtonDidTap), for: .touchUpInside)
}
}
fileprivate func configFooter() {
signUpLabel = UILabel().then {
$0.text("Don't have an account?")
$0.textColor = .lightGray
$0.font = .h4
}
signUpButton = UIButton().then {
$0.title("Sign up")
$0.titleLabel?.font = .h4
$0.setTitleColor(.black, for: .normal)
$0.addTarget(self, action: #selector(signUpButtonDidTap), for: .touchUpInside)
}
}
@objc fileprivate func signUpButtonDidTap() {
print("signUpButton did tap !!!")
UIView.transition(with: view, duration: 0.5, options: .transitionCrossDissolve, animations: {
self.formLayout.isEnabled(!self.formLayout.isEnabled)
Duration.measure("titleLabel hided") {
self.rootLayout.layout()
}
}, completion: { _ in
})
}
@objc fileprivate func signInButtonDidTap() {
present(ViewController2(), animated: true, completion: nil)
}
fileprivate func applyLayout() {
view.subview(
titleLabel,
usernameLabel,
usernameTextField,
passwordLabel,
passwordTextField,
forgotPasswordButton, signInButton,
signUpLabel, signUpButton
)
formLayout = YGLayout.vTop(
usernameLabel,
8,
usernameTextField,
16,
passwordLabel,
8,
passwordTextField,
16,
YGLayout.hSpace(forgotPasswordButton, signInButton)
)
.flexGrow(1)
rootLayout = view.yoga
rootLayout.vTop(
titleLabel.yoga
.crossAxis(align: .flexStart),
30,
formLayout,
YGLayout.hCenter(signUpLabel, 4, signUpButton)
)
.paddingTop(44)
.paddingHorizontal(16)
.paddingBottom(12)
.layout()
}
}
| apache-2.0 | 0ba4bd11c437264589339ca180856147 | 23.253333 | 97 | 0.639637 | 4.162471 | false | false | false | false |
senosa/KonachanFrame | KonachanFrame/ViewController.swift | 1 | 1460 | //
// ViewController.swift
// KonachanFrame
//
// Created by Sensuke Osawa on 2015/09/10.
// Copyright (c) 2015年 Sensuke Osawa. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var imageView: NSImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear() {
let url = NSURL(string: "http://konachan.net/post.json?limit=1&tags=order%3Arandom")
let req = NSURLRequest(URL: url!)
var resp: NSURLResponse?
var error: NSError?
var data = NSURLConnection.sendSynchronousRequest(req, returningResponse: &resp, error: &error)
if (error == nil) {
var json = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments, error: &error) as! NSArray
if (error == nil) {
// ok
let item = json[0] as! NSDictionary
var jpegUrl = item.objectForKey("jpeg_url") as! String
let img = NSImage(contentsOfURL: NSURL(string: jpegUrl)!)
imageView.image = img
} else {
// json parse error
println(error)
}
} else {
// URL connection error
println(error)
}
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
| mit | 0aebd4c791d06e3879b1b878b6d76c08 | 28.16 | 141 | 0.580247 | 4.542056 | false | false | false | false |
narner/AudioKit | Examples/iOS/SongProcessor/SongProcessor/View Controllers/iTunes Library Access/AlbumsViewController.swift | 1 | 2250 | //
// AlbumsViewController.swift
// SongProcessor
//
// Created by Aurelius Prochazka on 6/22/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import AVFoundation
import MediaPlayer
import UIKit
class AlbumsViewController: UITableViewController {
var artistName: String!
var albumsList = [MPMediaItemCollection]()
override func viewDidLoad() {
super.viewDidLoad()
let artistPredicate = MPMediaPropertyPredicate(value: artistName,
forProperty: MPMediaItemPropertyArtist,
comparisonType: .contains)
let albumsQuery = MPMediaQuery.albums()
albumsQuery.addFilterPredicate(artistPredicate)
if let list = albumsQuery.collections {
albumsList = list
tableView.reloadData()
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return albumsList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "AlbumCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) ??
UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
// Configure the cell...
if let repItem = albumsList[(indexPath as NSIndexPath).row].representativeItem,
let albumTitle = repItem.value(forProperty: MPMediaItemPropertyAlbumTitle) as? String {
cell.textLabel?.text = albumTitle
}
return cell
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SongsSegue" {
if let senderCell = sender as? UITableViewCell, let songsVC = segue.destination as? SongsViewController {
songsVC.artistName = artistName
songsVC.albumName = senderCell.textLabel?.text
songsVC.title = senderCell.textLabel?.text
}
}
}
}
| mit | b2ba9490014c4af0d3e3bb7b40f2fd40 | 29.808219 | 117 | 0.635394 | 5.419277 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/StartUI/Common/Cells/InviteTeamMemberCell.swift | 1 | 4979 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import UIKit
import WireCommonComponents
class StartUIIconCell: UICollectionViewCell {
typealias CellColors = SemanticColors.View
typealias PeoplePicker = L10n.Localizable.Peoplepicker
fileprivate let iconView = UIImageView()
fileprivate let titleLabel = DynamicFontLabel(fontSpec: .normalLightFont, color: .textForeground)
fileprivate let separator = UIView()
fileprivate var icon: StyleKitIcon? {
didSet {
iconView.image = icon?.makeImage(size: .tiny, color: SemanticColors.Icon.foregroundDefault).withRenderingMode(.alwaysTemplate)
iconView.tintColor = SemanticColors.Icon.foregroundDefault
}
}
fileprivate var title: String? {
didSet {
titleLabel.text = title
}
}
override var isHighlighted: Bool {
didSet {
backgroundColor = isHighlighted ? CellColors.backgroundUserCellHightLighted : CellColors.backgroundUserCell
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
createConstraints()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setupViews() {
iconView.contentMode = .center
titleLabel.applyStyle(.primaryCellLabel)
separator.backgroundColor = CellColors.backgroundSeparatorCell
backgroundColor = CellColors.backgroundUserCell
[iconView, titleLabel, separator].forEach(contentView.addSubview)
}
fileprivate func createConstraints() {
let iconSize: CGFloat = 32.0
[iconView, titleLabel, separator].prepareForLayout()
NSLayoutConstraint.activate([
iconView.widthAnchor.constraint(equalToConstant: iconSize),
iconView.heightAnchor.constraint(equalToConstant: iconSize),
iconView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
iconView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
titleLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 64),
titleLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor),
titleLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
separator.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
separator.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
separator.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
separator.heightAnchor.constraint(equalToConstant: .hairline)
])
}
}
final class InviteTeamMemberCell: StartUIIconCell {
override func setupViews() {
super.setupViews()
icon = .envelope
title = PeoplePicker.inviteTeamMembers
isAccessibilityElement = true
accessibilityLabel = title
accessibilityTraits.insert(.button)
accessibilityIdentifier = "button.searchui.invite_team"
}
}
final class CreateGroupCell: StartUIIconCell {
override func setupViews() {
super.setupViews()
icon = .createConversation
title = PeoplePicker.QuickAction.createConversation
isAccessibilityElement = true
accessibilityLabel = title
accessibilityTraits.insert(.button)
accessibilityIdentifier = "button.searchui.creategroup"
}
}
final class CreateGuestRoomCell: StartUIIconCell {
override func setupViews() {
super.setupViews()
icon = .guest
title = PeoplePicker.QuickAction.createGuestRoom
isAccessibilityElement = true
accessibilityLabel = title
accessibilityTraits.insert(.button)
accessibilityIdentifier = "button.searchui.createguestroom"
}
}
final class OpenServicesAdminCell: StartUIIconCell {
override func setupViews() {
super.setupViews()
icon = .bot
title = PeoplePicker.QuickAction.adminServices
isAccessibilityElement = true
accessibilityLabel = title
accessibilityIdentifier = "button.searchui.open-services"
}
}
| gpl-3.0 | 82030093bd9b0b016b93c5a7e61d7921 | 32.870748 | 138 | 0.70235 | 5.279958 | false | false | false | false |
Dimillian/HackerSwifter | Hacker Swifter/Hacker SwifterTests/CacheTests.swift | 1 | 3693 | //
// CacheTests.swift
// HackerSwifter
//
// Created by Thomas Ricouard on 16/07/14.
// Copyright (c) 2014 Thomas Ricouard. All rights reserved.
//
import XCTest
import HackerSwifter
class CacheTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func pathtest() {
let path = "test/test?test/test"
let result = "test#test?test#test"
XCTAssertTrue(DiskCache.generateCacheKey(path) == result, "cache key is not equal to result")
}
func testMemoryCache() {
let post = Post()
post.title = "Test"
MemoryCache.sharedMemoryCache.setObject(post, key: "post")
let postTest = MemoryCache.sharedMemoryCache.objectForKeySync("post") as! Post
XCTAssertNotNil(postTest, "Post is nil")
XCTAssertTrue(postTest.isKindOfClass(Post), "Post is not kind of class post")
XCTAssertTrue(postTest.title == "Test", "Post title is not equal to prior test")
MemoryCache.sharedMemoryCache.removeObject("post")
XCTAssertNil(MemoryCache.sharedMemoryCache.objectForKeySync("post"), "post should be nil")
}
func testDiskCache() {
let post = Post()
post.title = "Test"
DiskCache.sharedDiskCache.setObject(post, key: "post")
let postTest = DiskCache.sharedDiskCache.objectForKeySync("post") as! Post
XCTAssertNotNil(postTest, "Post is nil")
XCTAssertTrue(postTest.isKindOfClass(Post), "Post is not kind of class post")
XCTAssertTrue(postTest.title == "Test", "Post title is not equal to prior test")
DiskCache.sharedDiskCache.removeObject("post")
XCTAssertNil(DiskCache.sharedDiskCache.objectForKeySync("post"), "post should be nil")
}
func testGlobalCache() {
let post = Post()
post.title = "Global Test"
Cache.sharedCache.setObject(post, key: "post")
let globalPost = Cache.sharedCache.objectForKeySync("post") as! Post
let memoryPost = MemoryCache.sharedMemoryCache.objectForKeySync("post") as! Post
let diskPost = DiskCache.sharedDiskCache.objectForKeySync("post") as! Post
XCTAssertNotNil(globalPost, "Global Post is nil")
XCTAssertNotNil(memoryPost, "Memory Post is nil")
XCTAssertNotNil(diskPost, "Dissk Post is nil")
XCTAssertTrue(globalPost.isKindOfClass(Post), "Global Post is not kind of class post")
XCTAssertTrue(globalPost.title == "Global Test", "Global Post title is not equal to prior test")
XCTAssertTrue(memoryPost.isKindOfClass(Post), "Memory Post is not kind of class post")
XCTAssertTrue(memoryPost.title == "Global Test", "Memory Post title is not equal to prior test")
XCTAssertTrue(diskPost.isKindOfClass(Post), "Disk Post is not kind of class post")
XCTAssertTrue(diskPost.title == "Global Test", "Disk Post title is not equal to prior test")
Cache.sharedCache.removeObject("post")
XCTAssertNil(Cache.sharedCache.objectForKeySync("post"), "post should be nil")
XCTAssertNil(MemoryCache.sharedMemoryCache.objectForKeySync("post"), "post should be nil")
XCTAssertNil(DiskCache.sharedDiskCache.objectForKeySync("post"), "post should be nil")
}
}
| mit | 8457fc2259fc532e844d768bce0d4193 | 38.287234 | 111 | 0.650961 | 4.710459 | false | true | false | false |
KennethTsang/AddressBookKit | Example/AddressBookKit/GroupedTableViewController.swift | 1 | 2880 | //
// ResultTableViewController.swift
// AddressBookKit
//
// Created by Kenneth on 19/2/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import AddressBookKit
class GroupedTableViewController: UITableViewController {
private var groupedContacts = [GroupedContact]()
override func viewDidLoad() {
title = "Grouped Contacts"
AddressBookKit.requestPermission { [weak self] (success) -> Void in
if success {
self?.loadAddressBook()
} else {
self?.showAlert()
}
}
}
private func loadAddressBook() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
self.groupedContacts = AddressBookKit.groupedContacts([.PhoneNumber, .Email])
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
}
}
private func showAlert() {
let alertController = UIAlertController(
title: "Contacts Access Denied",
message: "This app requires access to your device's contacts.\n\nPlease enable contacts access for this app in Settings > Privacy > Contacts)",
preferredStyle: .Alert)
alertController.addAction(UIAlertAction(
title: "Close",
style: .Default,
handler:nil))
alertController.addAction(UIAlertAction(
title: "Settings",
style: .Default,
handler: { (_) in
if let settingUrl = NSURL(string: UIApplicationOpenSettingsURLString) {
UIApplication.sharedApplication().openURL(settingUrl)
}
}))
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return groupedContacts.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let contact = groupedContacts[section]
return contact.phoneNumbers.count + contact.emails.count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return groupedContacts[section].fullName
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let contact = groupedContacts[indexPath.section]
if indexPath.row < contact.phoneNumbers.count {
cell.textLabel?.text = "📞 " + contact.phoneNumbers[indexPath.row]
} else {
cell.textLabel?.text = "✉️ " + contact.emails[indexPath.row - contact.phoneNumbers.count]
}
return cell
}
} | mit | 2bc90fd66b97fabfad3597e6d36f8c97 | 34.9125 | 155 | 0.622214 | 5.289134 | false | false | false | false |
robtimp/xswift | exercises/custom-set/Sources/CustomSet/CustomSetExample.swift | 2 | 2099 | func == <T> (lh: CustomSet<T>, rh: CustomSet<T>) -> Bool {
return lh.contents.keys.sorted { $0.hashValue < $1.hashValue } == rh.contents.keys.sorted { $0.hashValue < $1.hashValue }
}
extension CustomSet where T: Comparable {
var toSortedArray: [Element] { return Array(contents.keys.sorted { $0 < $1 }) }
}
struct CustomSet<T: Hashable>: Equatable {
typealias Element = T
fileprivate var contents = [Element: Bool]()
var size: Int { return contents.count }
init<S: Sequence>(_ sequence: S) where S.Iterator.Element == Element {
self.contents = [:]
_ = sequence.map { self.contents[$0] = true }
}
mutating func put(_ item: Element) {
contents[item] = true
}
mutating func delete(_ item: Element) {
contents[item] = nil
}
mutating func removeAll() {
contents = [:]
}
func intersection(_ item: CustomSet) -> CustomSet {
var temp = [Element: Bool]()
for each in Array(item.contents.keys) {
guard contents[each] != nil else { continue }
temp[each] = true
}
return CustomSet(temp.keys)
}
func difference(_ item: CustomSet) -> CustomSet {
var temp = contents
for each in Array(item.contents.keys) {
temp[each] = nil
}
return CustomSet(temp.keys)
}
func union(_ item: CustomSet) -> CustomSet {
var temp = contents
for each in Array(item.contents.keys) {
temp[each] = true
}
return CustomSet(temp.keys)
}
func isSupersetOf (_ item: CustomSet) -> Bool {
return item.contents.count == item.contents.filter { self.contents.keys.contains($0.0) }.count
}
func isDisjoint(_ item: CustomSet) -> Bool {
for each in Array(item.contents.keys) {
if contents.keys.contains(each) {
return false
}
}
return true
}
func containsMember(_ item: Element) -> Bool {
if contents[item] != nil {
return true}
return false
}
}
| mit | f47df3a9045bcc338cff5188a7540b4a | 24.597561 | 125 | 0.565507 | 3.975379 | false | false | false | false |
mozilla-mobile/firefox-ios | CredentialProvider/Cells/EmptyPlaceholderCell.swift | 2 | 1787 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import UIKit
class EmptyPlaceholderCell: UITableViewCell {
static let identifier = "emptyPlaceholderCell"
lazy private var titleLabel: UILabel = .build { label in
label.textColor = UIColor.CredentialProvider.titleColor
label.text = .LoginsListNoLoginsFoundTitle
label.font = UIFont.systemFont(ofSize: 15)
}
lazy private var descriptionLabel: UILabel = .build { label in
label.text = .LoginsListNoLoginsFoundDescription
label.font = UIFont.systemFont(ofSize: 13)
label.textColor = .systemGray
label.textAlignment = .center
label.numberOfLines = 0
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
backgroundColor = UIColor.CredentialProvider.tableViewBackgroundColor
contentView.addSubviews(titleLabel, descriptionLabel)
NSLayoutConstraint.activate([
titleLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 55),
descriptionLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
descriptionLabel.widthAnchor.constraint(equalToConstant: 280),
descriptionLabel.topAnchor.constraint(equalTo: titleLabel.layoutMarginsGuide.bottomAnchor, constant: 20),
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mpl-2.0 | 0ec6dadddf1394fb3e429a60d2f0a16c | 40.55814 | 117 | 0.713486 | 5.16474 | false | false | false | false |
remobjects/Marzipan | CodeGen4/TypeReferences.swift | 1 | 15790 | /* Type References */
public enum CGTypeNullabilityKind {
case Unknown
case Default
case NotNullable
case NullableUnwrapped
case NullableNotUnwrapped
}
public __abstract class CGTypeReference : CGEntity {
public fileprivate(set) var Nullability: CGTypeNullabilityKind = .Default
public fileprivate(set) var DefaultNullability: CGTypeNullabilityKind = .NotNullable
public fileprivate(set) var DefaultValue: CGExpression?
public fileprivate(set) var IsClassType = false
public lazy var NullableUnwrapped: CGTypeReference = ActualNullability == CGTypeNullabilityKind.NullableUnwrapped ? self : self.copyWithNullability(CGTypeNullabilityKind.NullableUnwrapped)
public lazy var NullableNotUnwrapped: CGTypeReference = ActualNullability == CGTypeNullabilityKind.NullableNotUnwrapped ? self : self.copyWithNullability(CGTypeNullabilityKind.NullableNotUnwrapped)
public lazy var NotNullable: CGTypeReference = ActualNullability == CGTypeNullabilityKind.NotNullable ? self : self.copyWithNullability(CGTypeNullabilityKind.NotNullable)
public var ActualNullability: CGTypeNullabilityKind {
if Nullability == CGTypeNullabilityKind.Default || Nullability == CGTypeNullabilityKind.Unknown {
return DefaultNullability
}
return Nullability
}
public var IsVoid: Boolean {
return false
}
public __abstract func copyWithNullability(_ nullability: CGTypeNullabilityKind) -> CGTypeReference
}
public enum CGStorageModifierKind {
case Strong
case Weak
case Unretained
}
public class CGNamedTypeReference : CGTypeReference {
public let Name: String
public private(set) var Namespace: CGNamespaceReference?
public var GenericArguments: List<CGTypeReference>?
public var FullName: String {
if let namespace = Namespace {
return namespace.Name+"."+Name
}
return Name
}
public init(_ name: String) {
Name = name
IsClassType = true
DefaultNullability = .NullableUnwrapped
}
public convenience init(_ name: String, namespace: CGNamespaceReference) {
init(name)
Namespace = namespace
}
public convenience init(_ name: String, defaultNullability: CGTypeNullabilityKind) {
init(name)
DefaultNullability = defaultNullability
}
public convenience init(_ name: String, defaultNullability: CGTypeNullabilityKind, nullability: CGTypeNullabilityKind) {
init(name)
DefaultNullability = defaultNullability
Nullability = nullability
}
public convenience init(_ name: String, isClassType: Boolean) {
init(name)
IsClassType = isClassType
DefaultNullability = isClassType ? CGTypeNullabilityKind.NullableUnwrapped : CGTypeNullabilityKind.NotNullable
}
public convenience init(_ name: String, namespace: CGNamespaceReference, isClassType: Boolean) {
init(name)
Namespace = namespace
IsClassType = isClassType
DefaultNullability = isClassType ? CGTypeNullabilityKind.NullableUnwrapped : CGTypeNullabilityKind.NotNullable
}
override func copyWithNullability(_ nullability: CGTypeNullabilityKind) -> CGTypeReference {
let result = CGNamedTypeReference(Name, defaultNullability: DefaultNullability, nullability: nullability)
result.GenericArguments = GenericArguments
result.Namespace = Namespace
result.DefaultValue = DefaultValue
result.IsClassType = IsClassType
return result
}
@ToString public func ToString() -> String {
return "<\(Name)>";
}
}
public class CGPredefinedTypeReference : CGTypeReference {
public var Kind: CGPredefinedTypeKind
//todo:these should become provate and force use of the static members
private init(_ kind: CGPredefinedTypeKind) {
Kind = kind
switch Kind {
case .Int: fallthrough
case .UInt: fallthrough
case .Int8: fallthrough
case .UInt8: fallthrough
case .Int16: fallthrough
case .UInt16: fallthrough
case .Int32: fallthrough
case .UInt32: fallthrough
case .Int64: fallthrough
case .UInt64: fallthrough
case .IntPtr: fallthrough
case .UIntPtr:
DefaultValue = CGIntegerLiteralExpression.Zero
DefaultNullability = .NotNullable
case .Single: fallthrough
case .Double:
DefaultValue = CGFloatLiteralExpression.Zero
DefaultNullability = .NotNullable
//case .Decimal
case .Boolean:
DefaultValue = CGBooleanLiteralExpression.False
DefaultNullability = .NotNullable
case .String:
DefaultValue = CGStringLiteralExpression.Empty
DefaultNullability = .NullableUnwrapped
IsClassType = true
case .AnsiChar: fallthrough
case .UTF16Char: fallthrough
case .UTF32Char:
DefaultValue = CGCharacterLiteralExpression.Zero
DefaultNullability = .NotNullable
case .Dynamic: fallthrough
case .InstanceType: fallthrough
case .Void:
DefaultValue = CGNilExpression.Nil
DefaultNullability = .NullableUnwrapped
IsClassType = true
case .Object:
DefaultValue = CGNilExpression.Nil
DefaultNullability = .NullableUnwrapped
IsClassType = true
case .Class:
DefaultValue = CGNilExpression.Nil
DefaultNullability = .NullableUnwrapped
IsClassType = true
}
}
private convenience init(_ kind: CGPredefinedTypeKind, defaultNullability: CGTypeNullabilityKind?, nullability: CGTypeNullabilityKind?) {
init(kind)
if let defaultNullability = defaultNullability {
DefaultNullability = defaultNullability
}
if let nullability = nullability {
Nullability = nullability
}
}
private convenience init(_ kind: CGPredefinedTypeKind, defaultValue: CGExpression) {
init(kind)
DefaultValue = defaultValue
}
override var IsVoid: Boolean {
return Kind == CGPredefinedTypeKind.Void
}
/*public lazy var NullableUnwrapped: CGPredefinedTypeReference = ActualNullability == CGTypeNullabilityKind.NullableUnwrapped ? self : CGPredefinedTypeReference(Kind, nullability: CGTypeNullabilityKind.NullableUnwrapped)
public lazy var NullableNotUnwrapped: CGPredefinedTypeReference = ActualNullability == CGTypeNullabilityKind.NullableNotUnwrapped ? self : CGPredefinedTypeReference(Kind, nullability: CGTypeNullabilityKind.NullableNotUnwrapped)
public lazy var NotNullable: CGPredefinedTypeReference = ActualNullability == CGTypeNullabilityKind.NotNullable ? self : CGPredefinedTypeReference(Kind, nullability: CGTypeNullabilityKind.NotNullable)*/
override func copyWithNullability(_ nullability: CGTypeNullabilityKind) -> CGTypeReference {
let result = CGPredefinedTypeReference(Kind, defaultNullability: nil, nullability: nullability)
result.DefaultValue = DefaultValue
result.IsClassType = IsClassType
return result
}
public static lazy var Int = CGPredefinedTypeReference(.Int)
public static lazy var UInt = CGPredefinedTypeReference(.UInt)
public static lazy var Int8 = CGPredefinedTypeReference(.Int8)
public static lazy var UInt8 = CGPredefinedTypeReference(.UInt8)
public static lazy var Int16 = CGPredefinedTypeReference(.Int16)
public static lazy var UInt16 = CGPredefinedTypeReference(.UInt16)
public static lazy var Int32 = CGPredefinedTypeReference(.Int32)
public static lazy var UInt32 = CGPredefinedTypeReference(.UInt32)
public static lazy var Int64 = CGPredefinedTypeReference(.Int64)
public static lazy var UInt64 = CGPredefinedTypeReference(.UInt64)
public static lazy var IntPtr = CGPredefinedTypeReference(.IntPtr)
public static lazy var UIntPtr = CGPredefinedTypeReference(.UIntPtr)
public static lazy var Single = CGPredefinedTypeReference(.Single)
public static lazy var Double = CGPredefinedTypeReference(.Double)
//public static lazy var Decimal = CGPredefinedTypeReference(.Decimal)
public static lazy var Boolean = CGPredefinedTypeReference(.Boolean)
public static lazy var String = CGPredefinedTypeReference(.String)
public static lazy var AnsiChar = CGPredefinedTypeReference(.AnsiChar)
public static lazy var UTF16Char = CGPredefinedTypeReference(.UTF16Char)
public static lazy var UTF32Char = CGPredefinedTypeReference(.UTF32Char)
public static lazy var Dynamic = CGPredefinedTypeReference(.Dynamic)
public static lazy var InstanceType = CGPredefinedTypeReference(.InstanceType)
public static lazy var Void = CGPredefinedTypeReference(.Void)
public static lazy var Object = CGPredefinedTypeReference(.Object)
public static lazy var Class = CGPredefinedTypeReference(.Class)
@ToString public func ToString() -> String {
return Kind.ToString();
}
}
public enum CGPredefinedTypeKind {
case Int
case UInt
case Int8
case UInt8
case Int16
case UInt16
case Int32
case UInt32
case Int64
case UInt64
case IntPtr
case UIntPtr
case Single
case Double
//case Decimal
case Boolean
case String
case AnsiChar
case UTF16Char
case UTF32Char
case Dynamic // aka "id", "Any"
case InstanceType // aka "Self"
case Void
case Object
case Class
}
public class CGIntegerRangeTypeReference : CGTypeReference {
public let Start: Integer
public let End: Integer
public init(_ start: Integer, _ end: Integer) {
Start = start
End = end
}
override func copyWithNullability(_ nullability: CGTypeNullabilityKind) -> CGTypeReference {
let result = CGIntegerRangeTypeReference(Start, End)
result.Nullability = nullability
return result
}
}
public class CGInlineBlockTypeReference : CGTypeReference {
public let Block: CGBlockTypeDefinition
public init(_ block: CGBlockTypeDefinition) {
Block = block
DefaultNullability = .NullableUnwrapped
}
override func copyWithNullability(_ nullability: CGTypeNullabilityKind) -> CGTypeReference {
let result = CGInlineBlockTypeReference(Block)
result.Nullability = nullability
result.DefaultValue = DefaultValue
result.IsClassType = IsClassType
return result
}
@ToString public func ToString() -> String {
return "block";
}
}
public class CGPointerTypeReference : CGTypeReference {
public let `Type`: CGTypeReference
public private(set) var Reference = false /* C++ only: "&" (true) vs "*" (false) */
public init(_ type: CGTypeReference) {
`Type` = type
DefaultNullability = .NullableUnwrapped
}
public convenience init(_ type: CGTypeReference, reference: Boolean) { /* C++ only */
init(type)
Reference = reference
}
public static lazy var VoidPointer = CGPointerTypeReference(CGPredefinedTypeReference.Void)
override func copyWithNullability(_ nullability: CGTypeNullabilityKind) -> CGTypeReference {
let result = CGPointerTypeReference(`Type`, reference: Reference)
result.Nullability = nullability
result.DefaultValue = DefaultValue
result.IsClassType = IsClassType
return result
}
@ToString public func ToString() -> String {
return "<pointer to \(`Type`.ToString())>";
}
}
public class CGConstantTypeReference : CGTypeReference { /* C++ only, currently */
public let `Type`: CGTypeReference
public init(_ type: CGTypeReference) {
`Type` = type
DefaultNullability = .NullableUnwrapped
IsClassType = true
}
override func copyWithNullability(_ nullability: CGTypeNullabilityKind) -> CGTypeReference {
let result = CGConstantTypeReference(`Type`)
result.Nullability = nullability
result.DefaultValue = DefaultValue
result.IsClassType = IsClassType
return result
}
@ToString public func ToString() -> String {
return "<constant \(`Type`.ToString())>";
}
}
public class CGKindOfTypeReference : CGTypeReference {
public let `Type`: CGTypeReference
public init(_ type: CGTypeReference) {
`Type` = type
DefaultNullability = .NullableUnwrapped
IsClassType = true
}
override func copyWithNullability(_ nullability: CGTypeNullabilityKind) -> CGTypeReference {
let result = CGKindOfTypeReference(`Type`)
result.Nullability = nullability
result.DefaultValue = DefaultValue
result.IsClassType = IsClassType
return result
}
@ToString public func ToString() -> String {
return "<kind of \(`Type`.ToString())>";
}
}
public class CGTupleTypeReference : CGTypeReference {
public var Members: List<CGTypeReference>
public init(_ members: List<CGTypeReference>) {
Members = members
DefaultNullability = .NotNullable
}
public convenience init(_ members: CGTypeReference...) {
init(members.ToList())
}
override func copyWithNullability(_ nullability: CGTypeNullabilityKind) -> CGTypeReference {
let result = CGTupleTypeReference(Members)
result.Nullability = nullability
result.DefaultValue = DefaultValue
result.IsClassType = IsClassType
return result
}
@ToString public func ToString() -> String {
return "<tuple ...)>";
}
}
public class CGSequenceTypeReference : CGTypeReference {
public var `Type`: CGTypeReference
public init(_ type: CGTypeReference) {
`Type` = type
DefaultNullability = .NullableNotUnwrapped
IsClassType = true
}
override func copyWithNullability(_ nullability: CGTypeNullabilityKind) -> CGTypeReference {
let result = CGSequenceTypeReference(`Type`)
result.Nullability = nullability
result.DefaultValue = DefaultValue
result.IsClassType = IsClassType
return result
}
@ToString public func ToString() -> String {
return "<sequence od \(`Type`.ToString())>";
}
}
public class CGSetTypeReference : CGTypeReference {
public var `Type`: CGTypeReference
public init(_ type: CGTypeReference) {
`Type` = type
DefaultNullability = .NotNullable
}
override func copyWithNullability(_ nullability: CGTypeNullabilityKind) -> CGTypeReference {
let result = CGSetTypeReference(`Type`)
result.Nullability = nullability
result.DefaultValue = DefaultValue
result.IsClassType = IsClassType
return result
}
}
/* Arrays */
public enum CGArrayKind {
case Static
case Dynamic
case HighLevel /* Swift only */
}
public class CGArrayTypeReference : CGTypeReference {
public var `Type`: CGTypeReference
public var Bounds: List<CGArrayBounds>?
public var BoundsTypes: List<CGTypeReference>?
public var ArrayKind: CGArrayKind = .Dynamic
public init(_ type: CGTypeReference, _ bounds: List<CGArrayBounds>? = nil) {
`Type` = type
DefaultNullability = .NullableNotUnwrapped
if let bounds = bounds {
Bounds = bounds
}
}
public init(_ type: CGTypeReference, _ bounds: CGArrayBounds...) {
`Type` = type
DefaultNullability = .NullableNotUnwrapped
Bounds = bounds.ToList()
}
public init(_ type: CGTypeReference, _ boundsTypes: List<CGTypeReference>) {
`Type` = type
DefaultNullability = .NullableNotUnwrapped
BoundsTypes = boundsTypes
}
public init(_ type: CGTypeReference, _ boundsTypes: CGTypeReference...) {
`Type` = type
DefaultNullability = .NullableNotUnwrapped
BoundsTypes = boundsTypes.ToList()
}
override func copyWithNullability(_ nullability: CGTypeNullabilityKind) -> CGTypeReference {
let result = CGArrayTypeReference(`Type`, Bounds)
result.Nullability = nullability
result.ArrayKind = ArrayKind
result.DefaultValue = DefaultValue
result.IsClassType = IsClassType
return result
}
@ToString public func ToString() -> String {
return "<array of \(`Type`.ToString())>";
}
}
public class CGArrayBounds : CGEntity {
public var Start: Int32 = 0
public var End: Int32?
public init() {
}
public init(_ start: Int32, end: Int32) {
Start = start
End = end
}
}
/* Dictionaries (Swift only for now) */
public class CGDictionaryTypeReference : CGTypeReference {
public var KeyType: CGTypeReference
public var ValueType: CGTypeReference
public init(_ keyType: CGTypeReference, _ valueType: CGTypeReference) {
KeyType = keyType
ValueType = valueType
DefaultNullability = .NullableNotUnwrapped
IsClassType = true
}
override func copyWithNullability(_ nullability: CGTypeNullabilityKind) -> CGTypeReference {
let result = CGDictionaryTypeReference(KeyType, ValueType)
result.Nullability = nullability
result.DefaultValue = DefaultValue
result.IsClassType = IsClassType
return result
}
@ToString public func ToString() -> String {
return "<dinctionary of \(`KeyType`.ToString()):\(`ValueType`.ToString())>";
}
} | bsd-3-clause | 416e7f9f3578be36a2adac9e58567701 | 29.777778 | 228 | 0.768622 | 3.874356 | false | false | false | false |
fizx/jane | ruby/lib/vendor/grpc-swift/Sources/protoc-gen-swiftgrpc/options.swift | 1 | 4135 | /*
* Copyright 2017, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
enum GenerationError: Error {
/// Raised when parsing the parameter string and found an unknown key
case unknownParameter(name: String)
/// Raised when a parameter was giving an invalid value
case invalidParameterValue(name: String, value: String)
var localizedDescription: String {
switch self {
case .unknownParameter(let name):
return "Unknown generation parameter '\(name)'"
case .invalidParameterValue(let name, let value):
return "Unknown value for generation parameter '\(name)': '\(value)'"
}
}
}
final class GeneratorOptions {
enum Visibility: String {
case `internal` = "Internal"
case `public` = "Public"
var sourceSnippet: String {
switch self {
case .internal:
return "internal"
case .public:
return "public"
}
}
}
private(set) var visibility = Visibility.internal
private(set) var generateServer = true
private(set) var generateClient = true
private(set) var generateAsynchronous = true
private(set) var generateSynchronous = true
private(set) var generateTestStubs = false
init(parameter: String?) throws {
for pair in GeneratorOptions.parseParameter(string: parameter) {
switch pair.key {
case "Visibility":
if let value = Visibility(rawValue: pair.value) {
visibility = value
} else {
throw GenerationError.invalidParameterValue(name: pair.key, value: pair.value)
}
case "Server":
if let value = Bool(pair.value) {
generateServer = value
} else {
throw GenerationError.invalidParameterValue(name: pair.key, value: pair.value)
}
case "Client":
if let value = Bool(pair.value) {
generateClient = value
} else {
throw GenerationError.invalidParameterValue(name: pair.key, value: pair.value)
}
case "Async":
if let value = Bool(pair.value) {
generateAsynchronous = value
} else {
throw GenerationError.invalidParameterValue(name: pair.key, value: pair.value)
}
case "Sync":
if let value = Bool(pair.value) {
generateSynchronous = value
} else {
throw GenerationError.invalidParameterValue(name: pair.key, value: pair.value)
}
case "TestStubs":
if let value = Bool(pair.value) {
generateTestStubs = value
} else {
throw GenerationError.invalidParameterValue(name: pair.key, value: pair.value)
}
default:
throw GenerationError.unknownParameter(name: pair.key)
}
}
}
static func parseParameter(string: String?) -> [(key: String, value: String)] {
guard let string = string, !string.isEmpty else {
return []
}
let parts = string.components(separatedBy: ",")
// Partitions the string into the section before the = and after the =
let result = parts.map { string -> (key: String, value: String) in
// Finds the equal sign and exits early if none
guard let index = string.range(of: "=")?.lowerBound else {
return (string, "")
}
// Creates key/value pair and trims whitespace
let key = string[..<index]
.trimmingCharacters(in: .whitespacesAndNewlines)
let value = string[string.index(after: index)...]
.trimmingCharacters(in: .whitespacesAndNewlines)
return (key: key, value: value)
}
return result
}
}
| mit | b20e690388dfa7af09beaec70efb3b8d | 30.564885 | 90 | 0.645224 | 4.451023 | false | false | false | false |
exevil/Keys-For-Sketch | Source/Update/UpdateCompletionAlert.swift | 1 | 1010 | //
// UpdateCompleteAlert.swift
// KeysForSketch
//
// Created by Vyacheslav Dubovitsky on 19/03/2017.
// Copyright © 2017 Vyacheslav Dubovitsky. All rights reserved.
//
public class UpdateCompletionAlert: NSAlert {
override init() {
super.init()
messageText = "Keys Were Installed Sucessfully"
informativeText = "Please restart Sketch to finish the instalation process."
icon = image(Const.Image.keysIcon)
addButton(withTitle: "Restart Sketch")
addButton(withTitle: "Later")
}
/// Default completion handler for alert.
@objc public func completionHandler(with response: NSApplication.ModalResponse) {
if response == .alertFirstButtonReturn {
// Relaunch Sketch
let task = Process()
task.launchPath = "/bin/sh"
task.arguments = ["-c", "sleep \(0.5); open \"\(Bundle.main.bundlePath)\""]
task.launch()
NSApp.terminate(nil)
}
}
}
| mit | d4113c1bf4cfb2070f2e029814210513 | 29.575758 | 87 | 0.615461 | 4.464602 | false | false | false | false |
wwdc14/SkyNet | SkyNet/Classes/CPU/CPU.swift | 1 | 2442 | //
// File.swift
// Pods
//
// Created by FD on 14/08/2017.
//
//
import Foundation
public struct CPUUsage {
static func convertThreadInfoToThreadBasicInfo(_ threadInfo: thread_info_t) -> thread_basic_info {
var result = thread_basic_info()
result.user_time = time_value_t(seconds: threadInfo[0], microseconds: threadInfo[1])
result.system_time = time_value_t(seconds: threadInfo[2], microseconds: threadInfo[3])
result.cpu_usage = threadInfo[4]
result.policy = threadInfo[5]
result.run_state = threadInfo[6]
result.flags = threadInfo[7]
result.suspend_count = threadInfo[8]
result.sleep_time = threadInfo[9]
return result
}
static public func cpu_usage() -> Float {
var kr: kern_return_t
var tinfo = [integer_t]()
var task_info_count: mach_msg_type_number_t
task_info_count = mach_msg_type_number_t(TASK_INFO_MAX)
kr = task_info(mach_task_self_, task_flavor_t(TASK_BASIC_INFO), &tinfo, &task_info_count)
if (kr != KERN_SUCCESS) {
return -1
}
var thread_list: thread_act_array_t? = UnsafeMutablePointer(mutating: [thread_act_t]())
var thread_count: mach_msg_type_number_t = 0
let thinfo: thread_info_t = UnsafeMutablePointer(mutating: [integer_t]())
var thread_info_count: mach_msg_type_number_t
kr = task_threads(mach_task_self_, &thread_list, &thread_count)
if (kr != KERN_SUCCESS) {
return -1
}
var tot_cpu: Float = 0
if thread_list != nil {
for j in 0 ..< Int(thread_count) {
thread_info_count = mach_msg_type_number_t(THREAD_INFO_MAX)
kr = thread_info(thread_list![j], thread_flavor_t(THREAD_BASIC_INFO),
thinfo, &thread_info_count)
if (kr != KERN_SUCCESS) {
return -1
}
let threadBasicInfo = convertThreadInfoToThreadBasicInfo(thinfo)
if threadBasicInfo.flags != TH_FLAGS_IDLE {
tot_cpu = tot_cpu + (Float(threadBasicInfo.cpu_usage) / Float(TH_USAGE_SCALE)) * 100.0
}
} // for each thread
}
return tot_cpu
}
}
| mit | 8196436377d902cd46651b9cb7a602c7 | 32 | 106 | 0.539722 | 3.839623 | false | false | false | false |
brentsimmons/Evergreen | Articles/Sources/Articles/ArticleStatus.swift | 1 | 1935 | //
// ArticleStatus.swift
// NetNewsWire
//
// Created by Brent Simmons on 7/1/17.
// Copyright © 2017 Ranchero Software, LLC. All rights reserved.
//
import Foundation
// Threading rules:
// * Main-thread only
// * Except: may be created on background thread by StatusesTable.
// Which is safe, because at creation time it’t not yet shared,
// and it won’t be mutated ever on a background thread.
public final class ArticleStatus: Hashable {
public enum Key: String {
case read = "read"
case starred = "starred"
}
public let articleID: String
public let dateArrived: Date
public var read = false
public var starred = false
public init(articleID: String, read: Bool, starred: Bool, dateArrived: Date) {
self.articleID = articleID
self.read = read
self.starred = starred
self.dateArrived = dateArrived
}
public convenience init(articleID: String, read: Bool, dateArrived: Date) {
self.init(articleID: articleID, read: read, starred: false, dateArrived: dateArrived)
}
public func boolStatus(forKey key: ArticleStatus.Key) -> Bool {
switch key {
case .read:
return read
case .starred:
return starred
}
}
public func setBoolStatus(_ status: Bool, forKey key: ArticleStatus.Key) {
switch key {
case .read:
read = status
case .starred:
starred = status
}
}
// MARK: - Hashable
public func hash(into hasher: inout Hasher) {
hasher.combine(articleID)
}
// MARK: - Equatable
public static func ==(lhs: ArticleStatus, rhs: ArticleStatus) -> Bool {
return lhs.articleID == rhs.articleID && lhs.dateArrived == rhs.dateArrived && lhs.read == rhs.read && lhs.starred == rhs.starred
}
}
public extension Set where Element == ArticleStatus {
func articleIDs() -> Set<String> {
return Set<String>(map { $0.articleID })
}
}
public extension Array where Element == ArticleStatus {
func articleIDs() -> [String] {
return map { $0.articleID }
}
}
| mit | cd49a156c3995a6991cc205aee9660e7 | 21.97619 | 131 | 0.693264 | 3.409894 | false | false | false | false |
tkester/swift-algorithm-club | Selection Sampling/SelectionSampling.playground/Contents.swift | 1 | 1903 | //: Playground - noun: a place where people can play
// last checked with Xcode 9.0b4
#if swift(>=4.0)
print("Hello, Swift 4!")
#endif
import Foundation
/* Returns a random integer in the range min...max, inclusive. */
public func random(min: Int, max: Int) -> Int {
assert(min < max)
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
/*
func select<T>(from a: [T], count k: Int) -> [T] {
var a = a
for i in 0..<k {
let r = random(min: i, max: a.count - 1)
if i != r {
swap(&a[i], &a[r])
}
}
return Array(a[0..<k])
}
*/
func select<T>(from a: [T], count requested: Int) -> [T] {
var examined = 0
var selected = 0
var b = [T]()
while selected < requested {
examined += 1
// Calculate random variable 0.0 <= r < 1.0 (exclusive!).
let r = Double(arc4random()) / 0x100000000
let leftToExamine = a.count - examined + 1
let leftToAdd = requested - selected
// Decide whether to use the next record from the input.
if Double(leftToExamine) * r < Double(leftToAdd) {
selected += 1
b.append(a[examined - 1])
}
}
return b
}
let poem = [
"there", "once", "was", "a", "man", "from", "nantucket",
"who", "kept", "all", "of", "his", "cash", "in", "a", "bucket",
"his", "daughter", "named", "nan",
"ran", "off", "with", "a", "man",
"and", "as", "for", "the", "bucket", "nan", "took", "it",
]
let output = select(from: poem, count: 10)
print(output)
output.count
// Use this to verify that all input elements have the same probability
// of being chosen. The "counts" dictionary should have a roughly equal
// count for each input element.
/*
let input = [ "a", "b", "c", "d", "e", "f", "g" ]
var counts = [String: Int]()
for x in input {
counts[x] = 0
}
for _ in 0...1000 {
let output = select(from: input, count: 3)
for x in output {
counts[x] = counts[x]! + 1
}
}
print(counts)
*/
| mit | a6dc695bafac34e280447dc4f8712701 | 21.927711 | 71 | 0.581188 | 2.927692 | false | false | false | false |
googlemaps/google-maps-ios-utils | samples/SwiftDemoApp/SwiftDemoApp/HeatmapViewController.swift | 1 | 3455 | /* Copyright (c) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import GoogleMaps
import UIKit
import GoogleMapsUtils
class HeatmapViewController: UIViewController, GMSMapViewDelegate {
private var mapView: GMSMapView!
private var heatmapLayer: GMUHeatmapTileLayer!
private var button: UIButton!
private var gradientColors = [UIColor.green, UIColor.red]
private var gradientStartPoints = [0.2, 1.0] as [NSNumber]
override func loadView() {
let camera = GMSCameraPosition.camera(withLatitude: -37.848, longitude: 145.001, zoom: 10)
mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
mapView.delegate = self
self.view = mapView
makeButton()
}
override func viewDidLoad() {
// Set heatmap options.
heatmapLayer = GMUHeatmapTileLayer()
heatmapLayer.radius = 80
heatmapLayer.opacity = 0.8
heatmapLayer.gradient = GMUGradient(colors: gradientColors,
startPoints: gradientStartPoints,
colorMapSize: 256)
addHeatmap()
// Set the heatmap to the mapview.
heatmapLayer.map = mapView
}
// Parse JSON data and add it to the heatmap layer.
func addHeatmap() {
var list = [GMUWeightedLatLng]()
do {
// Get the data: latitude/longitude positions of police stations.
if let path = Bundle.main.url(forResource: "police_stations", withExtension: "json") {
let data = try Data(contentsOf: path)
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let object = json as? [[String: Any]] {
for item in object {
let lat = item["lat"]
let lng = item["lng"]
let coords = GMUWeightedLatLng(coordinate: CLLocationCoordinate2DMake(lat as! CLLocationDegrees, lng as! CLLocationDegrees), intensity: 1.0)
list.append(coords)
}
} else {
print("Could not read the JSON.")
}
}
} catch {
print(error.localizedDescription)
}
// Add the latlngs to the heatmap layer.
heatmapLayer.weightedData = list
}
@objc
func removeHeatmap() {
heatmapLayer.map = nil
heatmapLayer = nil
// Disable the button to prevent subsequent calls, since heatmapLayer is now nil.
button.isEnabled = false
}
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
print("You tapped at \(coordinate.latitude), \(coordinate.longitude)")
}
// Add a button to the view.
func makeButton() {
// A button to test removing the heatmap.
button = UIButton(frame: CGRect(x: 5, y: 150, width: 200, height: 35))
button.backgroundColor = .blue
button.alpha = 0.5
button.setTitle("Remove heatmap", for: .normal)
button.addTarget(self, action: #selector(removeHeatmap), for: .touchUpInside)
self.mapView.addSubview(button)
}
}
| apache-2.0 | 19225ae313263fab3ab1010a47c2dc48 | 33.89899 | 152 | 0.672359 | 4.45232 | false | false | false | false |
pqnga/ios-basic-app | SimpleApp/PQNSwiftSimpleViewCell.swift | 1 | 1637 | //
// PQNSwiftSimpleViewCell.swift
// SimpleApp
//
// Created by Nga Pham on 10/29/14.
// Copyright (c) 2014 Misfit. All rights reserved.
//
import UIKit
class PQNSwiftSimpleViewCell: UICollectionViewCell {
// MARK: Properties
let nameLabel = UILabel()
let iconImageView = UIImageView()
let gestureRecognizer = UITapGestureRecognizer()
var isShowingImage: Bool = false {
didSet {
var fromView: UIView!
var toView: UIView!
if (isShowingImage)
{
fromView = self.iconImageView;
toView = self.nameLabel;
}
else
{
fromView = self.nameLabel;
toView = self.iconImageView;
}
UIView.transitionWithView(self, duration: 0.3, options: UIViewAnimationOptions.TransitionFlipFromLeft, animations: { () -> Void in
fromView.removeFromSuperview();
self.addSubview(toView);
}, completion: nil);
}
}
func configure() {
nameLabel.frame = self.bounds;
nameLabel.textAlignment = NSTextAlignment.Center;
nameLabel.textColor = UIColor.whiteColor();
nameLabel.font = UIFont(name:"Helvetica", size: 20);
self.addSubview(nameLabel);
iconImageView.frame = self.bounds;
gestureRecognizer.addTarget(self, action: "handleGesture");
self.addGestureRecognizer(gestureRecognizer);
}
func handleGesture() {
self.isShowingImage = !self.isShowingImage;
}
}
| mit | c39aaf3dd550f363f21149a8bf5ccc5b | 27.719298 | 142 | 0.574832 | 5.246795 | false | false | false | false |
huangboju/QMUI.swift | QMUI.swift/QMUIKit/UICommon/QMUIConfigurationMacros.swift | 1 | 12530 | //
// QMUIConfigurationMacros.swift
// QMUI.swift
//
// Created by qd-hxt on 2018/3/27.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
/**
* 提供一系列方便书写的宏,以便在代码里读取配置表的各种属性。
* @warning 请不要在 + load 方法里调用 QMUIConfigurationTemplate 或 QMUIConfigurationMacros 提供的宏,那个时机太早,可能导致 crash
* @waining 维护时,如果需要增加一个宏,则需要定义一个新的 QMUIConfiguration 属性。
*/
// 单例的宏
var QMUICMI: QMUIConfiguration {
let shared = QMUIConfiguration.shared
shared.applyInitialTemplate()
return shared
}
// MARK: - Global Color
// MARK: TODO 这里的声明全是 let 常量,但实际上,QMUICMI里的属性时可变的,是否要改为可变的,比如说 TabBarTintColor
// 基础颜色
let UIColorClear = QMUICMI.clear
let UIColorWhite = QMUICMI.white
let UIColorBlack = QMUICMI.black
let UIColorGray = QMUICMI.gray
let UIColorGrayDarken = QMUICMI.grayDarken
let UIColorGrayLighten = QMUICMI.grayLighten
let UIColorRed = QMUICMI.red
let UIColorGreen = QMUICMI.green
let UIColorBlue = QMUICMI.blue
let UIColorYellow = QMUICMI.yellow
// 功能颜色
let UIColorLink = QMUICMI.linkColor // 全局统一文字链接颜色
let UIColorDisabled = QMUICMI.disabledColor // 全局统一文字disabled颜色
let UIColorForBackground = QMUICMI.backgroundColor // 全局统一的背景色
let UIColorMask = QMUICMI.maskDarkColor // 全局统一的mask背景色
let UIColorMaskWhite = QMUICMI.maskLightColor // 全局统一的mask背景色,白色
let UIColorSeparator = QMUICMI.separatorColor // 全局分隔线颜色
let UIColorSeparatorDashed = QMUICMI.separatorDashedColor // 全局分隔线颜色(虚线)
let UIColorPlaceholder = QMUICMI.placeholderColor // 全局的输入框的placeholder颜色
// 测试用的颜色
let UIColorTestRed = QMUICMI.testColorRed
let UIColorTestGreen = QMUICMI.testColorGreen
let UIColorTestBlue = QMUICMI.testColorBlue
// 可操作的控件
// MARK: - UIControl
let UIControlHighlightedAlpha = QMUICMI.controlHighlightedAlpha // 一般control的Highlighted透明值
let UIControlDisabledAlpha = QMUICMI.controlDisabledAlpha // 一般control的Disable透明值
// 按钮
// MARK: - UIButton
let ButtonHighlightedAlpha = QMUICMI.buttonHighlightedAlpha // 按钮Highlighted状态的透明度
let ButtonDisabledAlpha = QMUICMI.buttonDisabledAlpha // 按钮Disabled状态的透明度
let ButtonTintColor = QMUICMI.buttonTintColor // 普通按钮的颜色
let GhostButtonColorBlue = QMUICMI.ghostButtonColorBlue // QMUIGhostButtonColorBlue的颜色
let GhostButtonColorRed = QMUICMI.ghostButtonColorRed // QMUIGhostButtonColorRed的颜色
let GhostButtonColorGreen = QMUICMI.ghostButtonColorGreen // QMUIGhostButtonColorGreen的颜色
let GhostButtonColorGray = QMUICMI.ghostButtonColorGray // QMUIGhostButtonColorGray的颜色
let GhostButtonColorWhite = QMUICMI.ghostButtonColorWhite // QMUIGhostButtonColorWhite的颜色
let FillButtonColorBlue = QMUICMI.fillButtonColorBlue // QMUIFillButtonColorBlue的颜色
let FillButtonColorRed = QMUICMI.fillButtonColorRed // QMUIFillButtonColorRed的颜色
let FillButtonColorGreen = QMUICMI.fillButtonColorGreen // QMUIFillButtonColorGreen的颜色
let FillButtonColorGray = QMUICMI.fillButtonColorGray // QMUIFillButtonColorGray的颜色
let FillButtonColorWhite = QMUICMI.fillButtonColorWhite // QMUIFillButtonColorWhite的颜色
// 输入框
// MARK: - TextField & TextView
let TextFieldTintColor = QMUICMI.textFieldTintColor // 全局UITextField、UITextView的tintColor
let TextFieldTextInsets = QMUICMI.textFieldTextInsets // QMUITextField的内边距
// MARK: - NavigationBar
let NavBarHighlightedAlpha = QMUICMI.navBarHighlightedAlpha
let NavBarDisabledAlpha = QMUICMI.navBarDisabledAlpha
let NavBarButtonFont = QMUICMI.navBarButtonFont
let NavBarButtonFontBold = QMUICMI.navBarButtonFontBold
var NavBarBackgroundImage: UIImage? { return QMUICMI.navBarBackgroundImage }
var NavBarShadowImage: UIImage? { return QMUICMI.navBarShadowImage }
let NavBarBarTintColor = QMUICMI.navBarBarTintColor
let NavBarTintColor = QMUICMI.navBarTintColor
var NavBarTitleColor: UIColor? { return QMUICMI.navBarTitleColor }
let NavBarTitleFont = QMUICMI.navBarTitleFont
let NavBarLargeTitleColor = QMUICMI.navBarLargeTitleColor
let NavBarLargeTitleFont = QMUICMI.navBarLargeTitleFont
let NavBarBarBackButtonTitlePositionAdjustment = QMUICMI.navBarBackButtonTitlePositionAdjustment
let NavBarBackIndicatorImage = QMUICMI.navBarBackIndicatorImage // 自定义的返回按钮,尺寸建议与系统的返回按钮尺寸一致(iOS8下实测系统大小是(13, 21)),可提高性能
let NavBarCloseButtonImage = QMUICMI.navBarCloseButtonImage
let NavBarLoadingMarginRight = QMUICMI.navBarLoadingMarginRight // titleView里左边的loading的右边距
let NavBarAccessoryViewMarginLeft = QMUICMI.navBarAccessoryViewMarginLeft // titleView里的accessoryView的左边距
let NavBarActivityIndicatorViewStyle = QMUICMI.navBarActivityIndicatorViewStyle // titleView loading 的style
let NavBarAccessoryViewTypeDisclosureIndicatorImage = QMUICMI.navBarAccessoryViewTypeDisclosureIndicatorImage // titleView上倒三角的默认图片
// MARK: - TabBar
let TabBarBackgroundImage = QMUICMI.tabBarBackgroundImage
let TabBarBarTintColor = QMUICMI.tabBarBarTintColor
let TabBarShadowImageColor = QMUICMI.tabBarShadowImageColor
var TabBarTintColor: UIColor? {
return QMUICMI.tabBarTintColor
}
let TabBarItemTitleColor = QMUICMI.tabBarItemTitleColor
let TabBarItemTitleColorSelected = QMUICMI.tabBarItemTitleColorSelected
let TabBarItemTitleFont = QMUICMI.tabBarItemTitleFont
// MARK: - Toolbar
let ToolBarHighlightedAlpha = QMUICMI.toolBarHighlightedAlpha
let ToolBarDisabledAlpha = QMUICMI.toolBarDisabledAlpha
let ToolBarTintColor = QMUICMI.toolBarTintColor
let ToolBarTintColorHighlighted = QMUICMI.toolBarTintColorHighlighted
let ToolBarTintColorDisabled = QMUICMI.toolBarTintColorDisabled
let ToolBarBackgroundImage = QMUICMI.toolBarBackgroundImage
let ToolBarBarTintColor = QMUICMI.toolBarBarTintColor
let ToolBarShadowImageColor = QMUICMI.toolBarShadowImageColor
let ToolBarButtonFont = QMUICMI.toolBarButtonFont
// MARK: - SearchBar
let SearchBarTextFieldBackground = QMUICMI.searchBarTextFieldBackground
let SearchBarTextFieldBorderColor = QMUICMI.searchBarTextFieldBorderColor
let SearchBarBottomBorderColor = QMUICMI.searchBarBottomBorderColor
let SearchBarBarTintColor = QMUICMI.searchBarBarTintColor
let SearchBarTintColor = QMUICMI.searchBarTintColor
let SearchBarTextColor = QMUICMI.searchBarTextColor
let SearchBarPlaceholderColor = QMUICMI.searchBarPlaceholderColor
let SearchBarFont = QMUICMI.searchBarFont
let SearchBarSearchIconImage = QMUICMI.searchBarSearchIconImage
let SearchBarClearIconImage = QMUICMI.searchBarClearIconImage
let SearchBarTextFieldCornerRadius = QMUICMI.searchBarTextFieldCornerRadius
// MARK: - TableView / TableViewCell
let TableViewEstimatedHeightEnabled = QMUICMI.tableViewEstimatedHeightEnabled // 是否要开启全局 UITableView 的 estimatedRow(Section/Footer)Height
let TableViewBackgroundColor = QMUICMI.tableViewBackgroundColor // 普通列表的背景色
let TableViewGroupedBackgroundColor = QMUICMI.tableViewGroupedBackgroundColor // Grouped类型的列表的背景色
let TableSectionIndexColor = QMUICMI.tableSectionIndexColor // 列表右边索引条的文字颜色,iOS6及以后生效
let TableSectionIndexBackgroundColor = QMUICMI.tableSectionIndexBackgroundColor // 列表右边索引条的背景色,iOS7及以后生效
let TableSectionIndexTrackingBackgroundColor = QMUICMI.tableSectionIndexTrackingBackgroundColor // 列表右边索引条按下时的背景色,iOS6及以后生效
let TableViewSeparatorColor = QMUICMI.tableViewSeparatorColor // 列表分隔线颜色
let TableViewCellBackgroundColor = QMUICMI.tableViewCellBackgroundColor // 列表cel的背景色
let TableViewCellSelectedBackgroundColor = QMUICMI.tableViewCellSelectedBackgroundColor // 列表cell按下时的背景色
let TableViewCellWarningBackgroundColor = QMUICMI.tableViewCellWarningBackgroundColor // 列表cell在未读状态下的背景色
let TableViewCellNormalHeight = QMUICMI.tableViewCellNormalHeight // 默认cell的高度
let TableViewCellDisclosureIndicatorImage = QMUICMI.tableViewCellDisclosureIndicatorImage // 列表cell右边的箭头图片
let TableViewCellCheckmarkImage = QMUICMI.tableViewCellCheckmarkImage // 列表cell右边的打钩checkmark
let TableViewCellDetailButtonImage = QMUICMI.tableViewCellDetailButtonImage // 列表 cell 右边的 i 按钮
let TableViewCellSpacingBetweenDetailButtonAndDisclosureIndicator = QMUICMI.tableViewCellSpacingBetweenDetailButtonAndDisclosureIndicator // 列表 cell 右边的 i 按钮和向右箭头之间的间距(仅当两者都使用了自定义图片并且同时显示时才生效)
let TableViewSectionHeaderBackgroundColor = QMUICMI.tableViewSectionHeaderBackgroundColor
let TableViewSectionFooterBackgroundColor = QMUICMI.tableViewSectionFooterBackgroundColor
let TableViewSectionHeaderFont = QMUICMI.tableViewSectionHeaderFont
let TableViewSectionFooterFont = QMUICMI.tableViewSectionFooterFont
let TableViewSectionHeaderTextColor = QMUICMI.tableViewSectionHeaderTextColor
let TableViewSectionFooterTextColor = QMUICMI.tableViewSectionFooterTextColor
let TableViewSectionHeaderAccessoryMargins = QMUICMI.tableViewSectionHeaderAccessoryMargins
let TableViewSectionFooterAccessoryMargins = QMUICMI.tableViewSectionFooterAccessoryMargins
let TableViewSectionHeaderContentInset = QMUICMI.tableViewSectionHeaderContentInset
let TableViewSectionFooterContentInset = QMUICMI.tableViewSectionFooterContentInset
let TableViewGroupedSectionHeaderFont = QMUICMI.tableViewGroupedSectionHeaderFont
let TableViewGroupedSectionFooterFont = QMUICMI.tableViewGroupedSectionFooterFont
let TableViewGroupedSectionHeaderTextColor = QMUICMI.tableViewGroupedSectionHeaderTextColor
let TableViewGroupedSectionFooterTextColor = QMUICMI.tableViewGroupedSectionFooterTextColor
let TableViewGroupedSectionHeaderAccessoryMargins = QMUICMI.tableViewGroupedSectionHeaderAccessoryMargins
let TableViewGroupedSectionFooterAccessoryMargins = QMUICMI.tableViewGroupedSectionFooterAccessoryMargins
let TableViewGroupedSectionHeaderDefaultHeight = QMUICMI.tableViewGroupedSectionHeaderDefaultHeight
let TableViewGroupedSectionFooterDefaultHeight = QMUICMI.tableViewGroupedSectionFooterDefaultHeight
let TableViewGroupedSectionHeaderContentInset = QMUICMI.tableViewGroupedSectionHeaderContentInset
let TableViewGroupedSectionFooterContentInset = QMUICMI.tableViewGroupedSectionFooterContentInset
let TableViewCellTitleLabelColor = QMUICMI.tableViewCellTitleLabelColor // cell的title颜色
let TableViewCellDetailLabelColor = QMUICMI.tableViewCellDetailLabelColor // cell的detailTitle颜色
// MARK: - UIWindowLevel
let UIWindowLevelQMUIAlertView = QMUICMI.windowLevelQMUIAlertView
let UIWindowLevelQMUIImagePreviewView = QMUICMI.windowLevelQMUIImagePreviewView
// MARK: - Others
let SupportedOrientationMask = QMUICMI.supportedOrientationMask // 默认支持的横竖屏方向
let AutomaticallyRotateDeviceOrientation = QMUICMI.automaticallyRotateDeviceOrientation // 是否在界面切换或 viewController.supportedOrientationMask 发生变化时自动旋转屏幕,默认为 NO
let StatusbarStyleLightInitially = QMUICMI.statusbarStyleLightInitially // 默认的状态栏内容是否使用白色,默认为NO,也即黑色
let NeedsBackBarButtonItemTitle = QMUICMI.needsBackBarButtonItemTitle // 全局是否需要返回按钮的title,不需要则只显示一个返回image
let HidesBottomBarWhenPushedInitially = QMUICMI.hidesBottomBarWhenPushedInitially // QMUICommonViewController.hidesBottomBarWhenPushed的初始值,默认为YES
let PreventConcurrentNavigationControllerTransitions = QMUICMI.preventConcurrentNavigationControllerTransitions // PreventConcurrentNavigationControllerTransitions : 自动保护 QMUINavigationController 在上一次 push/pop 尚未结束的时候就进行下一次 push/pop 的行为,避免产生 crash
let NavigationBarHiddenInitially = QMUICMI.navigationBarHiddenInitially // preferredNavigationBarHidden 的初始值,默认为NO
let ShouldFixTabBarTransitionBugInIPhoneX = QMUICMI.shouldFixTabBarTransitionBugInIPhoneX // 是否需要自动修复 iOS 11 下,iPhone X 的设备在 push 界面时,tabBar 会瞬间往上跳的 bug
| mit | df475de45c5bafaeb2d2547f7c46366a | 51.753555 | 247 | 0.873506 | 4.344653 | false | false | false | false |
lotz84/TwitterMediaTimeline | twitter-media-timeline/ViewController.swift | 1 | 4164 | //
// ViewController.swift
// twitter-media-timeline
//
// Created by Hirose Tatsuya on 2015/03/26.
// Copyright (c) 2015年 lotz84. All rights reserved.
//
import UIKit
import Social
import Accounts
class ViewController: UIViewController {
@IBOutlet weak var queryTextField: UITextField!
func showTwitterMediaTimeline(account : ACAccount){
let vc = TwitterMediaTimeline()
vc.account = account
vc.dataSource = self
self.presentViewController(vc, animated: true, completion: nil)
}
@IBAction func selectTwitterAccount()
{
queryTextField.resignFirstResponder()
if(SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter)){
let accountStore = ACAccountStore()
let twitterAccountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
accountStore.requestAccessToAccountsWithType(twitterAccountType, options: nil) {granted, error in
if granted {
let accounts = accountStore.accountsWithAccountType(twitterAccountType)
if accounts.count == 1 {
dispatch_async(dispatch_get_main_queue()) { [weak self] in
self!.showTwitterMediaTimeline(accounts[0] as! ACAccount)
}
} else {
let alert = UIAlertController(title: "Select User", message: nil, preferredStyle: .ActionSheet)
for item in accounts {
let account = item as! ACAccount
alert.addAction(UIAlertAction(title: "@"+account.username, style: .Default) { action in
self.showTwitterMediaTimeline(account)
})
}
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
}
} else {
let message = "No User"
let alert = UIAlertController(title: nil, message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
func defaultRequestHandler(handler: JSON -> Void) -> SLRequestHandler {
return { body, response, error in
if body == nil {
println("HTTPRequest Error: \(error.localizedDescription)")
return
}
if response.statusCode < 200 && 300 <= response.statusCode {
println("The response status code is \(response.statusCode)")
return
}
handler(JSON(data: body!))
}
}
}
extension ViewController : TwitterMediaTimelineDataSource {
func getNextStatusIds(request: TMTRequest, callback: TMTResultHandler) -> () {
if queryTextField.text.isEmpty {
return
}
let url = "https://api.twitter.com/1.1/search/tweets.json"
var param = [
"q": queryTextField.text,
"result_type": "recent",
"count": "100"
]
if let maxId = request.maxId {
param.updateValue(maxId, forKey: "max_id")
}
let slRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .GET, URL: NSURL(string: url), parameters: param)
slRequest.account = request.account
slRequest.performRequestWithHandler(defaultRequestHandler { json in
var idArray : [String] = []
for status in json["statuses"].arrayValue {
if status["retweeted_status"] != nil {
continue
}
if let id = status["id_str"].string {
idArray.append(id)
}
}
callback(idArray: idArray)
})
}
}
| mit | 46b1d8375e05c3f8894f0d355271bfbc | 37.183486 | 136 | 0.559827 | 5.261694 | false | false | false | false |
huonw/swift | test/Interpreter/enum-nonexhaustivity.swift | 1 | 9122 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -Onone -o %t/main -import-objc-header %S/Inputs/enum-nonexhaustivity.h -Xfrontend -disable-objc-attr-requires-foundation-module
// RUN: %target-run %t/main
// RUN: %target-build-swift %s -O -o %t/main -import-objc-header %S/Inputs/enum-nonexhaustivity.h -Xfrontend -disable-objc-attr-requires-foundation-module
// RUN: %target-run %t/main
// RUN: %target-build-swift %s -Ounchecked -o %t/main -import-objc-header %S/Inputs/enum-nonexhaustivity.h -Xfrontend -disable-objc-attr-requires-foundation-module
// RUN: %target-run %t/main
// REQUIRES: executable_test
import StdlibUnittest
var EnumTestSuite = TestSuite("Enums")
EnumTestSuite.test("PlainOldSwitch/NonExhaustive") {
var gotCorrectValue = false
switch getExpectedValue() {
case .A, .C:
expectUnreachable()
case .B:
gotCorrectValue = true
}
expectTrue(gotCorrectValue)
}
EnumTestSuite.test("TrapOnUnexpected/NonExhaustive")
.crashOutputMatches("'NonExhaustiveEnum(rawValue: 3)'")
.code {
expectCrashLater()
switch getUnexpectedValue() {
case .A, .C:
expectUnreachable()
case .B:
expectUnreachable()
}
expectUnreachable()
}
EnumTestSuite.test("TrapOnUnexpectedNested/NonExhaustive")
.crashOutputMatches("'(NonExhaustiveEnum, NonExhaustiveEnum)'")
.code {
expectCrashLater()
switch (getExpectedValue(), getUnexpectedValue()) {
case (.A, .A), (.C, .C):
expectUnreachable()
case (_, .B):
expectUnreachable()
case (_, .A), (_, .C):
expectUnreachable()
}
expectUnreachable()
}
EnumTestSuite.test("TrapOnUnexpectedNested2/NonExhaustive")
.crashOutputMatches("'(NonExhaustiveEnum, NonExhaustiveEnum)'")
.code {
expectCrashLater()
switch (getUnexpectedValue(), getExpectedValue()) {
case (.A, .A), (.C, .C):
expectUnreachable()
case (.B, _):
expectUnreachable()
case (.A, _), (.C, _):
expectUnreachable()
}
expectUnreachable()
}
EnumTestSuite.test("UnexpectedOkayNested/NonExhaustive") {
var gotCorrectValue = false
switch (getExpectedValue(), getUnexpectedValue()) {
case (.A, .A), (.C, .C):
expectUnreachable()
case (.B, _):
gotCorrectValue = true
case (.A, _), (.C, _):
expectUnreachable()
}
expectTrue(gotCorrectValue)
}
EnumTestSuite.test("UnexpectedOkayNested2/NonExhaustive") {
var gotCorrectValue = false
switch (getUnexpectedValue(), getExpectedValue()) {
case (.A, .A), (.C, .C):
expectUnreachable()
case (_, .B):
gotCorrectValue = true
case (_, .A), (_, .C):
expectUnreachable()
}
expectTrue(gotCorrectValue)
}
EnumTestSuite.test("PlainOldSwitch/LyingExhaustive") {
var gotCorrectValue = false
switch getExpectedLiarValue() {
case .A, .C:
expectUnreachable()
case .B:
gotCorrectValue = true
}
expectTrue(gotCorrectValue)
}
EnumTestSuite.test("TrapOnUnexpected/LyingExhaustive")
.crashOutputMatches("'LyingExhaustiveEnum(rawValue: 3)'")
.code {
expectCrashLater()
switch getUnexpectedLiarValue() {
case .A, .C:
expectUnreachable()
case .B:
expectUnreachable()
}
expectUnreachable()
}
EnumTestSuite.test("TrapOnUnexpectedNested/LyingExhaustive")
.crashOutputMatches("'(LyingExhaustiveEnum, LyingExhaustiveEnum)'")
.code {
expectCrashLater()
switch (getExpectedLiarValue(), getUnexpectedLiarValue()) {
case (.A, .A), (.C, .C):
expectUnreachable()
case (_, .B):
expectUnreachable()
case (_, .A), (_, .C):
expectUnreachable()
}
expectUnreachable()
}
EnumTestSuite.test("TrapOnUnexpectedNested2/LyingExhaustive")
.crashOutputMatches("'(LyingExhaustiveEnum, LyingExhaustiveEnum)'")
.code {
expectCrashLater()
switch (getUnexpectedLiarValue(), getExpectedLiarValue()) {
case (.A, .A), (.C, .C):
expectUnreachable()
case (.B, _):
expectUnreachable()
case (.A, _), (.C, _):
expectUnreachable()
}
expectUnreachable()
}
EnumTestSuite.test("UnexpectedOkayNested/LyingExhaustive") {
var gotCorrectValue = false
switch (getExpectedLiarValue(), getUnexpectedLiarValue()) {
case (.A, .A), (.C, .C):
expectUnreachable()
case (.B, _):
gotCorrectValue = true
case (.A, _), (.C, _):
expectUnreachable()
}
expectTrue(gotCorrectValue)
}
EnumTestSuite.test("UnexpectedOkayNested2/LyingExhaustive") {
var gotCorrectValue = false
switch (getUnexpectedLiarValue(), getExpectedLiarValue()) {
case (.A, .A), (.C, .C):
expectUnreachable()
case (_, .B):
gotCorrectValue = true
case (_, .A), (_, .C):
expectUnreachable()
}
expectTrue(gotCorrectValue)
}
#if _runtime(_ObjC)
@objc enum SwiftEnum : Int32 {
case A, B, C
@inline(never) static func getExpectedValue() -> SwiftEnum {
return .B
}
@inline(never) static func getUnexpectedValue() -> SwiftEnum {
return unsafeBitCast(-42 as Int32, to: SwiftEnum.self)
}
}
EnumTestSuite.test("PlainOldSwitch/SwiftExhaustive") {
var gotCorrectValue = false
switch SwiftEnum.getExpectedValue() {
case .A, .C:
expectUnreachable()
case .B:
gotCorrectValue = true
}
expectTrue(gotCorrectValue)
}
EnumTestSuite.test("TrapOnUnexpected/SwiftExhaustive")
.crashOutputMatches("'SwiftEnum(rawValue: -42)'")
.code {
expectCrashLater()
switch SwiftEnum.getUnexpectedValue() {
case .A, .C:
expectUnreachable()
case .B:
expectUnreachable()
}
expectUnreachable()
}
EnumTestSuite.test("TrapOnUnexpectedNested/SwiftExhaustive")
.crashOutputMatches("'(SwiftEnum, SwiftEnum)'")
.code {
expectCrashLater()
switch (SwiftEnum.getExpectedValue(), SwiftEnum.getUnexpectedValue()) {
case (.A, .A), (.C, .C):
expectUnreachable()
case (_, .B):
expectUnreachable()
case (_, .A), (_, .C):
expectUnreachable()
}
expectUnreachable()
}
EnumTestSuite.test("TrapOnUnexpectedNested2/SwiftExhaustive")
.crashOutputMatches("'(SwiftEnum, SwiftEnum)'")
.code {
expectCrashLater()
switch (SwiftEnum.getUnexpectedValue(), SwiftEnum.getExpectedValue()) {
case (.A, .A), (.C, .C):
expectUnreachable()
case (.B, _):
expectUnreachable()
case (.A, _), (.C, _):
expectUnreachable()
}
expectUnreachable()
}
EnumTestSuite.test("UnexpectedOkayNested/SwiftExhaustive") {
var gotCorrectValue = false
switch (SwiftEnum.getExpectedValue(), SwiftEnum.getUnexpectedValue()) {
case (.A, .A), (.C, .C):
expectUnreachable()
case (.B, _):
gotCorrectValue = true
case (.A, _), (.C, _):
expectUnreachable()
}
expectTrue(gotCorrectValue)
}
EnumTestSuite.test("UnexpectedOkayNested2/SwiftExhaustive") {
var gotCorrectValue = false
switch (SwiftEnum.getUnexpectedValue(), SwiftEnum.getExpectedValue()) {
case (.A, .A), (.C, .C):
expectUnreachable()
case (_, .B):
gotCorrectValue = true
case (_, .A), (_, .C):
expectUnreachable()
}
expectTrue(gotCorrectValue)
}
@inline(never)
func switchOnTwoThings<T>(_ a: T, _ b: SwiftEnum) {
switch (a, b) {
case (is String, _):
expectUnreachable()
case (_, .B):
return
case (_, .A), (_, .C):
expectUnreachable()
}
}
EnumTestSuite.test("Generic/Trap")
.crashOutputMatches("'(Int, SwiftEnum)'")
.code {
expectCrashLater()
switchOnTwoThings(1, SwiftEnum.getUnexpectedValue())
}
EnumTestSuite.test("Generic/Okay") {
switchOnTwoThings(1, SwiftEnum.getExpectedValue())
}
@objc enum UnsignedSwiftEnum : UInt64 {
case A, B, C
@inline(never) static func getExpectedValue() -> UnsignedSwiftEnum {
return .B
}
@inline(never) static func getUnexpectedValue() -> UnsignedSwiftEnum {
return unsafeBitCast(~(0 as UInt64), to: UnsignedSwiftEnum.self)
}
}
EnumTestSuite.test("PlainOldSwitch/LargeSwiftExhaustive") {
var gotCorrectValue = false
switch UnsignedSwiftEnum.getExpectedValue() {
case .A, .C:
expectUnreachable()
case .B:
gotCorrectValue = true
}
expectTrue(gotCorrectValue)
}
EnumTestSuite.test("TrapOnUnexpected/LargeSwiftExhaustive")
.crashOutputMatches("'UnsignedSwiftEnum(rawValue: 18446744073709551615)'")
.code {
expectCrashLater()
switch UnsignedSwiftEnum.getUnexpectedValue() {
case .A, .C:
expectUnreachable()
case .B:
expectUnreachable()
}
expectUnreachable()
}
struct Outer {
@objc enum NestedSwiftEnum: Int32 {
case A, B, C
@inline(never) static func getExpectedValue() -> NestedSwiftEnum {
return .B
}
@inline(never) static func getUnexpectedValue() -> NestedSwiftEnum {
return unsafeBitCast(-1 as Int32, to: NestedSwiftEnum.self)
}
}
}
EnumTestSuite.test("PlainOldSwitch/NestedSwiftExhaustive") {
var gotCorrectValue = false
switch Outer.NestedSwiftEnum.getExpectedValue() {
case .A, .C:
expectUnreachable()
case .B:
gotCorrectValue = true
}
expectTrue(gotCorrectValue)
}
EnumTestSuite.test("TrapOnUnexpected/NestedSwiftExhaustive")
.crashOutputMatches("'NestedSwiftEnum(rawValue: -1)'")
.code {
expectCrashLater()
switch Outer.NestedSwiftEnum.getUnexpectedValue() {
case .A, .C:
expectUnreachable()
case .B:
expectUnreachable()
}
expectUnreachable()
}
#endif
runAllTests()
| apache-2.0 | e906c9ffdea9dc647a64dea8c3edee7a | 24.06044 | 163 | 0.683622 | 3.818334 | false | true | false | false |
nerd0geek1/NSPageControl | NSPageControl/NSPageControl.swift | 1 | 3944 | //
// NSPageControl.swift
// NSPageControl
//
// Created by Kohei Tabata on 2016/03/24.
// Copyright © 2016年 Kohei Tabata. All rights reserved.
//
import Cocoa
public class NSPageControl: NSView {
public var numberOfPages: Int = 0
public var currentPage: Int = 0 {
didSet(oldValue) {
if currentPage < 0 {
currentPage = 0
}
if currentPage > numberOfPages - 1 {
currentPage = numberOfPages - 1
}
didSetCurrentPage(oldValue, newlySelectedPage: currentPage)
}
}
public var hidesForSinglePage: Bool = true
public var pageIndicatorTintColor: NSColor = NSColor.darkGray
public var currentPageIndicatorTintColor: NSColor = NSColor.white
public var animationDuration: CFTimeInterval = 0.04
public var dotLength: CGFloat = 8.0
public var dotMargin: CGFloat = 12.0
private var dotLayers: [CAShapeLayer] = []
// MARK: - lifecycle
public override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
let dotWidthSum: CGFloat = dotLength * CGFloat(numberOfPages)
let marginWidthSum: CGFloat = dotMargin * CGFloat((numberOfPages - 1))
let minimumRequiredWidth: CGFloat = dotWidthSum + marginWidthSum
let hasEnoughHeight: Bool = dirtyRect.height >= dotLength
let hasEnoughWidth: Bool = dirtyRect.width >= minimumRequiredWidth
if !hasEnoughWidth || !hasEnoughHeight {
Swift.print("dirtyRect doesn't have enough space to draw all dots")
Swift.print("current Rect :\(dirtyRect)")
Swift.print("required Size:\(CGSize(width: minimumRequiredWidth, height: dotLength))")
}
for layer in dotLayers {
layer.removeFromSuperlayer()
}
dotLayers = []
self.layer = CALayer()
self.wantsLayer = true
for i: Int in 0..<numberOfPages {
let minX: CGFloat = (dirtyRect.width - minimumRequiredWidth) / 2
let indexOffset: CGFloat = (dotLength + dotMargin) * CGFloat(i)
let x: CGFloat = minX + indexOffset
let verticalCenter: CGFloat = (dirtyRect.height - dotLength) / 2
let y: CGFloat = verticalCenter - dotLength / 2
let rect: CGRect = NSRect(x: x, y: y, width: dotLength, height: dotLength)
let cgPath: CGMutablePath = CGMutablePath()
cgPath.addEllipse(in: rect)
let fillColor: NSColor = (i == currentPage) ? currentPageIndicatorTintColor : pageIndicatorTintColor
let shapeLayer: CAShapeLayer = CAShapeLayer()
shapeLayer.path = cgPath
shapeLayer.fillColor = fillColor.cgColor
layer?.addSublayer(shapeLayer)
dotLayers.append(shapeLayer)
}
}
// MARK: - private
private func didSetCurrentPage(_ selectedPage: Int, newlySelectedPage: Int) {
if selectedPage == newlySelectedPage {
return
}
let oldPageAnimation: CABasicAnimation = fillColorAnimation(with: pageIndicatorTintColor)
dotLayers[selectedPage].add(oldPageAnimation, forKey: "oldPageAnimation")
let newPageAnimation: CABasicAnimation = fillColorAnimation(with: currentPageIndicatorTintColor)
dotLayers[newlySelectedPage].add(newPageAnimation, forKey: "newPageAnimation")
}
private func fillColorAnimation(with color: NSColor) -> CABasicAnimation {
let fillColorAnimation: CABasicAnimation = CABasicAnimation(keyPath: "fillColor")
fillColorAnimation.toValue = color.cgColor
fillColorAnimation.duration = animationDuration
fillColorAnimation.fillMode = kCAFillModeForwards
fillColorAnimation.isRemovedOnCompletion = false
return fillColorAnimation
}
}
| mit | 3cc5e58456d6a2a57d91897f75009ad5 | 38.808081 | 121 | 0.634611 | 5.158377 | false | false | false | false |
pixyzehn/Linter | Sources/LinterCore/Process+Extensions.swift | 1 | 966 | //
// Process+Extensions.swift
// LinterCore
//
// Created by pixyzehn on 10/8/17.
//
import Foundation
extension Process {
@discardableResult func launchBash(with command: String) throws -> String {
launchPath = "/bin/bash"
arguments = ["-c", command]
let outputPipe = Pipe()
standardOutput = outputPipe
launch()
let output = outputPipe.read() ?? ""
waitUntilExit()
return output
}
}
private extension Pipe {
func read() -> String? {
let data = fileHandleForReading.readDataToEndOfFile()
guard let output = String(data: data, encoding: .utf8) else {
return nil
}
guard !output.hasSuffix("\n") else {
let outputLength = output.distance(from: output.startIndex, to: output.endIndex)
return String(output[..<output.index(output.startIndex, offsetBy: outputLength - 1)])
}
return output
}
}
| mit | a44476c604c78f70c79e6d3b395bedbd | 21.465116 | 97 | 0.598344 | 4.493023 | false | false | false | false |
catloafsoft/AudioKit | AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Telephone Ringing.xcplaygroundpage/Contents.swift | 1 | 882 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Telephone Ringing
//: ### The ringing sound is also a pair of frequencies that play for 2 seconds, and repeats every 6 seconds.
import XCPlayground
import AudioKit
let ringingTone1 = AKOperation.sineWave(frequency: 480)
let ringingTone2 = AKOperation.sineWave(frequency: 440)
let ringingToneMix = mixer(ringingTone1, ringingTone2, balance: 0.5)
let ringTrigger = AKOperation.metronome(0.1666) // 1 / 6 seconds
let ringing = ringingToneMix.triggeredWithEnvelope(ringTrigger,
attack: 0.01, hold: 2, release: 0.01)
let generator = AKOperationGenerator(operation: ringing * 0.4)
AudioKit.output = generator
AudioKit.start()
generator.start()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| mit | f49c38dcd0a811cbfee91b7f2c6a3e4d | 29.413793 | 110 | 0.738095 | 3.62963 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/TableviewCells/CustomizationHeaderView.swift | 1 | 2155 | //
// CustomizationHeaderView.swift
// Habitica
//
// Created by Phillip Thelen on 24.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
class CustomizationHeaderView: UICollectionReusableView {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var currencyView: HRPGCurrencyCountView!
@IBOutlet weak var purchaseButton: UIView!
@IBOutlet weak var buyAllLabel: UILabel!
var purchaseButtonTapped: (() -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
currencyView.currency = .gem
purchaseButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(buttonTapped)))
buyAllLabel.text = L10n.buyAll
}
func configure(customizationSet: CustomizationSetProtocol, isBackground: Bool) {
if isBackground {
if customizationSet.key?.contains("incentive") == true {
label.text = L10n.plainBackgrounds
} else if customizationSet.key?.contains("timeTravel") == true {
label.text = L10n.timeTravelBackgrounds
} else if let key = customizationSet.key?.replacingOccurrences(of: "backgrounds", with: "") {
let index = key.index(key.startIndex, offsetBy: 2)
let month = Int(key[..<index]) ?? 0
let year = Int(key[index...]) ?? 0
let dateFormatter = DateFormatter()
let monthName = month > 0 ? dateFormatter.monthSymbols[month-1] : ""
label.text = "\(monthName) \(year)"
}
} else {
label.text = customizationSet.text
}
label.textColor = ThemeService.shared.theme.primaryTextColor
currencyView.amount = Int(customizationSet.setPrice)
purchaseButton.backgroundColor = ThemeService.shared.theme.windowBackgroundColor
purchaseButton.borderColor = ThemeService.shared.theme.tintColor
}
@objc
private func buttonTapped() {
if let action = purchaseButtonTapped {
action()
}
}
}
| gpl-3.0 | 8c00afb52d8603b341b2bc4f23cce175 | 34.311475 | 114 | 0.627205 | 4.884354 | false | false | false | false |
rivetlogic/liferay-mobile-directory-ios | Liferay-Screens/Themes/Default/DDL/FormScreenlet/DDLFieldRadioTableCell_default.swift | 1 | 3839 | /**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library 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 Lesser General Public License for more
* details.
*/
import UIKit
public class DDLFieldRadioTableCell_default: DDLFieldTableCell {
@IBOutlet internal var label: UILabel?
@IBOutlet internal var radioReferenceLabel: UILabel?
@IBOutlet internal var separator: UIView?
internal var radioGroup: TNRadioButtonGroup?
//MARK: DDLFieldTableCell
override public func canBecomeFirstResponder() -> Bool {
return false
}
override internal func onChangedField() {
if let stringField = field as? DDLFieldStringWithOptions {
label!.text = stringField.label
let height =
label!.frame.origin.y + label!.frame.size.height +
DDLFieldRadioGroupMarginTop + DDLFieldRadioGroupMarginBottom +
(CGFloat(stringField.options.count) *
(DDLFieldRadioButtonHeight + DDLFieldRadioButtonMargin))
formView!.setCellHeight(height, forField:stringField)
separator!.frame.origin.y = height
createRadioButtons(stringField)
if stringField.lastValidationResult != nil {
onPostValidation(stringField.lastValidationResult!)
}
}
}
override internal func onPostValidation(valid: Bool) {
super.onPostValidation(valid)
label?.textColor = valid ? UIColor.blackColor() : UIColor.redColor()
let radioColor = valid ? DefaultThemeBasicBlue : UIColor.redColor()
for radioButton in radioGroup!.radioButtons as! [TNRectangularRadioButton] {
radioButton.data.labelColor = label?.textColor
radioButton.data.borderColor = radioColor
radioButton.data.rectangleColor = radioColor
radioButton.update()
}
}
//MARK: Private methods
private func createRadioButtons(field:DDLFieldStringWithOptions) {
var radioButtons:[AnyObject] = []
for option in field.options {
let data = TNRectangularRadioButtonData()
data.labelFont = radioReferenceLabel?.font
data.labelText = option.label
data.identifier = option.value
data.borderColor = DefaultThemeBasicBlue
data.rectangleColor = DefaultThemeBasicBlue
data.rectangleHeight = 8
data.rectangleWidth = 8
data.selected = filter(field.currentValue as! [DDLFieldStringWithOptions.Option]) {
$0.name == option.name
}.count > 0
radioButtons.append(data)
}
if radioGroup != nil {
NSNotificationCenter.defaultCenter().removeObserver(self,
name: SELECTED_RADIO_BUTTON_CHANGED,
object: radioGroup!)
radioGroup!.removeFromSuperview()
}
radioGroup = TNRadioButtonGroup(radioButtonData: radioButtons,
layout: TNRadioButtonGroupLayoutVertical)
radioGroup!.identifier = field.name
radioGroup!.marginBetweenItems = Int(DDLFieldRadioButtonMargin)
radioGroup!.create()
radioGroup!.position = CGPointMake(25.0,
DDLFieldRadioGroupMarginTop + label!.frame.origin.y + label!.frame.size.height)
addSubview(radioGroup!)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "radioButtonSelected:",
name: SELECTED_RADIO_BUTTON_CHANGED,
object: radioGroup)
}
private dynamic func radioButtonSelected(notification:NSNotification) {
if let stringField = field as? DDLFieldStringWithOptions {
stringField.currentValue = radioGroup!.selectedRadioButton.data.labelText
if stringField.lastValidationResult != nil && !stringField.lastValidationResult! {
stringField.lastValidationResult = true
onPostValidation(true)
}
}
}
}
| gpl-3.0 | 29b9a6243ef6c7ad246d1f4cd022b7a6 | 29.959677 | 86 | 0.761396 | 3.965909 | false | false | false | false |
natecook1000/swift | stdlib/public/SDK/Foundation/Locale.swift | 3 | 19589 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import _SwiftFoundationOverlayShims
/**
`Locale` encapsulates information about linguistic, cultural, and technological conventions and standards. Examples of information encapsulated by a locale include the symbol used for the decimal separator in numbers and the way dates are formatted.
Locales are typically used to provide, format, and interpret information about and according to the user's customs and preferences. They are frequently used in conjunction with formatters. Although you can use many locales, you usually use the one associated with the current user.
*/
public struct Locale : Hashable, Equatable, ReferenceConvertible {
public typealias ReferenceType = NSLocale
public typealias LanguageDirection = NSLocale.LanguageDirection
fileprivate var _wrapped : NSLocale
private var _autoupdating : Bool
/// Returns a locale which tracks the user's current preferences.
///
/// If mutated, this Locale will no longer track the user's preferences.
///
/// - note: The autoupdating Locale will only compare equal to another autoupdating Locale.
public static var autoupdatingCurrent : Locale {
return Locale(adoptingReference: __NSLocaleAutoupdating() as! NSLocale, autoupdating: true)
}
/// Returns the user's current locale.
public static var current : Locale {
return Locale(adoptingReference: __NSLocaleCurrent() as! NSLocale, autoupdating: false)
}
@available(*, unavailable, message: "Consider using the user's locale or nil instead, depending on use case")
public static var system : Locale { fatalError() }
// MARK: -
//
/// Return a locale with the specified identifier.
public init(identifier: String) {
_wrapped = NSLocale(localeIdentifier: identifier)
_autoupdating = false
}
fileprivate init(reference: NSLocale) {
_wrapped = reference.copy() as! NSLocale
if __NSLocaleIsAutoupdating(reference) {
_autoupdating = true
} else {
_autoupdating = false
}
}
private init(adoptingReference reference: NSLocale, autoupdating: Bool) {
_wrapped = reference
_autoupdating = autoupdating
}
// MARK: -
//
/// Returns a localized string for a specified identifier.
///
/// For example, in the "en" locale, the result for `"es"` is `"Spanish"`.
public func localizedString(forIdentifier identifier: String) -> String? {
return _wrapped.displayName(forKey: .identifier, value: identifier)
}
/// Returns a localized string for a specified language code.
///
/// For example, in the "en" locale, the result for `"es"` is `"Spanish"`.
public func localizedString(forLanguageCode languageCode: String) -> String? {
return _wrapped.displayName(forKey: .languageCode, value: languageCode)
}
/// Returns a localized string for a specified region code.
///
/// For example, in the "en" locale, the result for `"fr"` is `"France"`.
public func localizedString(forRegionCode regionCode: String) -> String? {
return _wrapped.displayName(forKey: .countryCode, value: regionCode)
}
/// Returns a localized string for a specified script code.
///
/// For example, in the "en" locale, the result for `"Hans"` is `"Simplified Han"`.
public func localizedString(forScriptCode scriptCode: String) -> String? {
return _wrapped.displayName(forKey: .scriptCode, value: scriptCode)
}
/// Returns a localized string for a specified variant code.
///
/// For example, in the "en" locale, the result for `"POSIX"` is `"Computer"`.
public func localizedString(forVariantCode variantCode: String) -> String? {
return _wrapped.displayName(forKey: .variantCode, value: variantCode)
}
/// Returns a localized string for a specified `Calendar.Identifier`.
///
/// For example, in the "en" locale, the result for `.buddhist` is `"Buddhist Calendar"`.
public func localizedString(for calendarIdentifier: Calendar.Identifier) -> String? {
// NSLocale doesn't export a constant for this
let result = CFLocaleCopyDisplayNameForPropertyValue(unsafeBitCast(_wrapped, to: CFLocale.self), .calendarIdentifier, Calendar._toNSCalendarIdentifier(calendarIdentifier).rawValue as CFString) as String?
return result
}
/// Returns a localized string for a specified ISO 4217 currency code.
///
/// For example, in the "en" locale, the result for `"USD"` is `"US Dollar"`.
/// - seealso: `Locale.isoCurrencyCodes`
public func localizedString(forCurrencyCode currencyCode: String) -> String? {
return _wrapped.displayName(forKey: .currencyCode, value: currencyCode)
}
/// Returns a localized string for a specified ICU collation identifier.
///
/// For example, in the "en" locale, the result for `"phonebook"` is `"Phonebook Sort Order"`.
public func localizedString(forCollationIdentifier collationIdentifier: String) -> String? {
return _wrapped.displayName(forKey: .collationIdentifier, value: collationIdentifier)
}
/// Returns a localized string for a specified ICU collator identifier.
public func localizedString(forCollatorIdentifier collatorIdentifier: String) -> String? {
return _wrapped.displayName(forKey: .collatorIdentifier, value: collatorIdentifier)
}
// MARK: -
//
/// Returns the identifier of the locale.
public var identifier: String {
return _wrapped.localeIdentifier
}
/// Returns the language code of the locale, or nil if has none.
///
/// For example, for the locale "zh-Hant-HK", returns "zh".
public var languageCode: String? {
return _wrapped.object(forKey: .languageCode) as? String
}
/// Returns the region code of the locale, or nil if it has none.
///
/// For example, for the locale "zh-Hant-HK", returns "HK".
public var regionCode: String? {
// n.b. this is called countryCode in ObjC
if let result = _wrapped.object(forKey: .countryCode) as? String {
if result.isEmpty {
return nil
} else {
return result
}
} else {
return nil
}
}
/// Returns the script code of the locale, or nil if has none.
///
/// For example, for the locale "zh-Hant-HK", returns "Hant".
public var scriptCode: String? {
return _wrapped.object(forKey: .scriptCode) as? String
}
/// Returns the variant code for the locale, or nil if it has none.
///
/// For example, for the locale "en_POSIX", returns "POSIX".
public var variantCode: String? {
if let result = _wrapped.object(forKey: .variantCode) as? String {
if result.isEmpty {
return nil
} else {
return result
}
} else {
return nil
}
}
/// Returns the exemplar character set for the locale, or nil if has none.
public var exemplarCharacterSet: CharacterSet? {
return _wrapped.object(forKey: .exemplarCharacterSet) as? CharacterSet
}
/// Returns the calendar for the locale, or the Gregorian calendar as a fallback.
public var calendar: Calendar {
// NSLocale should not return nil here
if let result = _wrapped.object(forKey: .calendar) as? Calendar {
return result
} else {
return Calendar(identifier: .gregorian)
}
}
/// Returns the collation identifier for the locale, or nil if it has none.
///
/// For example, for the locale "en_US@collation=phonebook", returns "phonebook".
public var collationIdentifier: String? {
return _wrapped.object(forKey: .collationIdentifier) as? String
}
/// Returns true if the locale uses the metric system.
///
/// -seealso: MeasurementFormatter
public var usesMetricSystem: Bool {
// NSLocale should not return nil here, but just in case
if let result = (_wrapped.object(forKey: .usesMetricSystem) as? NSNumber)?.boolValue {
return result
} else {
return false
}
}
/// Returns the decimal separator of the locale.
///
/// For example, for "en_US", returns ".".
public var decimalSeparator: String? {
return _wrapped.object(forKey: .decimalSeparator) as? String
}
/// Returns the grouping separator of the locale.
///
/// For example, for "en_US", returns ",".
public var groupingSeparator: String? {
return _wrapped.object(forKey: .groupingSeparator) as? String
}
/// Returns the currency symbol of the locale.
///
/// For example, for "zh-Hant-HK", returns "HK$".
public var currencySymbol: String? {
return _wrapped.object(forKey: .currencySymbol) as? String
}
/// Returns the currency code of the locale.
///
/// For example, for "zh-Hant-HK", returns "HKD".
public var currencyCode: String? {
return _wrapped.object(forKey: .currencyCode) as? String
}
/// Returns the collator identifier of the locale.
public var collatorIdentifier: String? {
return _wrapped.object(forKey: .collatorIdentifier) as? String
}
/// Returns the quotation begin delimiter of the locale.
///
/// For example, returns `“` for "en_US", and `「` for "zh-Hant-HK".
public var quotationBeginDelimiter: String? {
return _wrapped.object(forKey: .quotationBeginDelimiterKey) as? String
}
/// Returns the quotation end delimiter of the locale.
///
/// For example, returns `”` for "en_US", and `」` for "zh-Hant-HK".
public var quotationEndDelimiter: String? {
return _wrapped.object(forKey: .quotationEndDelimiterKey) as? String
}
/// Returns the alternate quotation begin delimiter of the locale.
///
/// For example, returns `‘` for "en_US", and `『` for "zh-Hant-HK".
public var alternateQuotationBeginDelimiter: String? {
return _wrapped.object(forKey: .alternateQuotationBeginDelimiterKey) as? String
}
/// Returns the alternate quotation end delimiter of the locale.
///
/// For example, returns `’` for "en_US", and `』` for "zh-Hant-HK".
public var alternateQuotationEndDelimiter: String? {
return _wrapped.object(forKey: .alternateQuotationEndDelimiterKey) as? String
}
// MARK: -
//
/// Returns a list of available `Locale` identifiers.
public static var availableIdentifiers: [String] {
return NSLocale.availableLocaleIdentifiers
}
/// Returns a list of available `Locale` language codes.
public static var isoLanguageCodes: [String] {
return NSLocale.isoLanguageCodes
}
/// Returns a list of available `Locale` region codes.
public static var isoRegionCodes: [String] {
// This was renamed from Obj-C
return NSLocale.isoCountryCodes
}
/// Returns a list of available `Locale` currency codes.
public static var isoCurrencyCodes: [String] {
return NSLocale.isoCurrencyCodes
}
/// Returns a list of common `Locale` currency codes.
public static var commonISOCurrencyCodes: [String] {
return NSLocale.commonISOCurrencyCodes
}
/// Returns a list of the user's preferred languages.
///
/// - note: `Bundle` is responsible for determining the language that your application will run in, based on the result of this API and combined with the languages your application supports.
/// - seealso: `Bundle.preferredLocalizations(from:)`
/// - seealso: `Bundle.preferredLocalizations(from:forPreferences:)`
public static var preferredLanguages: [String] {
return NSLocale.preferredLanguages
}
/// Returns a dictionary that splits an identifier into its component pieces.
public static func components(fromIdentifier string: String) -> [String : String] {
return NSLocale.components(fromLocaleIdentifier: string)
}
/// Constructs an identifier from a dictionary of components.
public static func identifier(fromComponents components: [String : String]) -> String {
return NSLocale.localeIdentifier(fromComponents: components)
}
/// Returns a canonical identifier from the given string.
public static func canonicalIdentifier(from string: String) -> String {
return NSLocale.canonicalLocaleIdentifier(from: string)
}
/// Returns a canonical language identifier from the given string.
public static func canonicalLanguageIdentifier(from string: String) -> String {
return NSLocale.canonicalLanguageIdentifier(from: string)
}
/// Returns the `Locale` identifier from a given Windows locale code, or nil if it could not be converted.
public static func identifier(fromWindowsLocaleCode code: Int) -> String? {
return NSLocale.localeIdentifier(fromWindowsLocaleCode: UInt32(code))
}
/// Returns the Windows locale code from a given identifier, or nil if it could not be converted.
public static func windowsLocaleCode(fromIdentifier identifier: String) -> Int? {
let result = NSLocale.windowsLocaleCode(fromLocaleIdentifier: identifier)
if result == 0 {
return nil
} else {
return Int(result)
}
}
/// Returns the character direction for a specified language code.
public static func characterDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection {
return NSLocale.characterDirection(forLanguage: isoLangCode)
}
/// Returns the line direction for a specified language code.
public static func lineDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection {
return NSLocale.lineDirection(forLanguage: isoLangCode)
}
// MARK: -
@available(*, unavailable, renamed: "init(identifier:)")
public init(localeIdentifier: String) { fatalError() }
@available(*, unavailable, renamed: "identifier")
public var localeIdentifier: String { fatalError() }
@available(*, unavailable, renamed: "localizedString(forIdentifier:)")
public func localizedString(forLocaleIdentifier localeIdentifier: String) -> String { fatalError() }
@available(*, unavailable, renamed: "availableIdentifiers")
public static var availableLocaleIdentifiers: [String] { fatalError() }
@available(*, unavailable, renamed: "components(fromIdentifier:)")
public static func components(fromLocaleIdentifier string: String) -> [String : String] { fatalError() }
@available(*, unavailable, renamed: "identifier(fromComponents:)")
public static func localeIdentifier(fromComponents dict: [String : String]) -> String { fatalError() }
@available(*, unavailable, renamed: "canonicalIdentifier(from:)")
public static func canonicalLocaleIdentifier(from string: String) -> String { fatalError() }
@available(*, unavailable, renamed: "identifier(fromWindowsLocaleCode:)")
public static func localeIdentifier(fromWindowsLocaleCode lcid: UInt32) -> String? { fatalError() }
@available(*, unavailable, renamed: "windowsLocaleCode(fromIdentifier:)")
public static func windowsLocaleCode(fromLocaleIdentifier localeIdentifier: String) -> UInt32 { fatalError() }
@available(*, unavailable, message: "use regionCode instead")
public var countryCode: String { fatalError() }
@available(*, unavailable, message: "use localizedString(forRegionCode:) instead")
public func localizedString(forCountryCode countryCode: String) -> String { fatalError() }
@available(*, unavailable, renamed: "isoRegionCodes")
public static var isoCountryCodes: [String] { fatalError() }
// MARK: -
//
public var hashValue : Int {
if _autoupdating {
return 1
} else {
return _wrapped.hash
}
}
public static func ==(lhs: Locale, rhs: Locale) -> Bool {
if lhs._autoupdating || rhs._autoupdating {
return lhs._autoupdating == rhs._autoupdating
} else {
return lhs._wrapped.isEqual(rhs._wrapped)
}
}
}
extension Locale : CustomDebugStringConvertible, CustomStringConvertible, CustomReflectable {
private var _kindDescription : String {
if self == Locale.autoupdatingCurrent {
return "autoupdatingCurrent"
} else if self == Locale.current {
return "current"
} else {
return "fixed"
}
}
public var customMirror : Mirror {
var c: [(label: String?, value: Any)] = []
c.append((label: "identifier", value: identifier))
c.append((label: "kind", value: _kindDescription))
return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
}
public var description: String {
return "\(identifier) (\(_kindDescription))"
}
public var debugDescription : String {
return "\(identifier) (\(_kindDescription))"
}
}
extension Locale : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSLocale {
return _wrapped
}
public static func _forceBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) {
if !_conditionallyBridgeFromObjectiveC(input, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) -> Bool {
result = Locale(reference: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSLocale?) -> Locale {
var result: Locale?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension NSLocale : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as Locale)
}
}
extension Locale : Codable {
private enum CodingKeys : Int, CodingKey {
case identifier
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let identifier = try container.decode(String.self, forKey: .identifier)
self.init(identifier: identifier)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.identifier, forKey: .identifier)
}
}
| apache-2.0 | 1878c627af6e71ccaa7e5580d43efb61 | 38.224449 | 282 | 0.655495 | 5.060238 | false | false | false | false |
calkinssean/TIY-Assignments | Day 24/StarWarsCollectionView/APIContoller.swift | 1 | 5278 | //
// APIContoller.swift
// StarWarsCollectionView
//
// Created by Sean Calkins on 3/3/16.
// Copyright © 2016 Dape App Productions LLC. All rights reserved.
//
import Foundation
import CoreData
class APIController {
var delegate: StarWarsProtcol?
let dataController = DataController()
init(delegate: CollectionViewController) {
self.delegate = delegate
}
var characterArray = [Character]()
var vehicleArray = [Vehicle]()
func characterAPI() {
let urlString = "http://swapi.co/api/people/"
if let url = NSURL(string: urlString) {
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url, completionHandler: {
(data, response, error) in
if error != nil {
debugPrint("there was an error \(error)")
} else {
if let data = data {
do {
if let dict = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? JSONDictionary {
if let results = dict["results"] as? JSONArray {
for result in results {
self.seedPerson(result)
}
}
}
} catch {
print("couldn't parse the json")
}
}
}
})
task.resume()
}
}
func vehicleAPI() {
let urlString = "http://swapi.co/api/vehicles/"
if let url = NSURL(string: urlString) {
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url, completionHandler: {
(data, response, error) in
if error != nil {
debugPrint("there was an error \(error)")
} else {
if let data = data {
do {
if let dict = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? JSONDictionary {
if let results = dict["results"] as? JSONArray {
for result in results {
// let v = Vehicle(dict: result)
// print(v.name)
// print(v.created)
}
}
}
} catch {
print("couldn't parse the json")
}
}
}
})
task.resume()
}
}
func seedPerson(dict: JSONDictionary) {
let mom = dataController.managedObjectContext
let entity = NSEntityDescription.insertNewObjectForEntityForName("Person", inManagedObjectContext: mom) as! Person
let today = NSDate()
if let name = dict["name"] as? String {
entity.setValue(name, forKey: "name")
print(entity.name)
} else {
print("couldn't parse the name json")
}
if let gender = dict["gender"] as? String {
entity.setValue(gender, forKey: "gender")
} else {
print("couldn't parse gender json")
}
if let created = dict["created"] as? NSDate {
entity.setValue(created, forKey: "created")
} else {
print("error with created")
}
// let entityVehicle = NSEntityDescription.insertNewObjectForEntityForName("vehicle", inManagedObjectContext: mom) as! Vehicle
//
// entityVehicle.setValue("X-wing", forKey: "name")
// entityVehicle.setValue(today, forKey: "created")
//
// let vehicles = NSSet(object: entityVehicle)
// entity.setValue(vehicles, forKey: "vehicles")
//
do {
try mom.save()
} catch {
fatalError("An error occured saving Person and Vehicle \(error)")
}
}
func fetchPerson() {
let mom = dataController.managedObjectContext
let fetchPerson = NSFetchRequest(entityName: "Person")
do {
let persons = try mom.executeFetchRequest(fetchPerson) as! [Person]
for p in persons {
print(p.name)
print(p.created)
// if let vehicles = p.vehicles {
// let vehicle = Array(vehicles) as! [Vehicle]
// for v in vehicles {
// print(v.name)
// }
// }
}
} catch {
fatalError("I couldn't fetch the person \(error)")
}
}
} | cc0-1.0 | fa8c3a9543e990fb9bc0da68b45d14d9 | 36.432624 | 137 | 0.440591 | 5.773523 | false | false | false | false |
gouyz/GYZBaking | baking/Classes/Mine/View/GYZMineCell.swift | 1 | 1802 | //
// GYZMineCell.swift
// baking
// 我的 cell
// Created by gouyz on 2017/3/30.
// Copyright © 2017年 gouyz. All rights reserved.
//
import UIKit
class GYZMineCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?){
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = kWhiteColor
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI(){
contentView.addSubview(logoImgView)
contentView.addSubview(nameLab)
contentView.addSubview(rightIconView)
logoImgView.snp.makeConstraints { (make) in
make.left.equalTo(kMargin)
make.centerY.equalTo(contentView)
make.size.equalTo(CGSize.init(width: 20, height: 20))
}
nameLab.snp.makeConstraints { (make) in
make.top.bottom.equalTo(contentView)
make.left.equalTo(logoImgView.snp.right).offset(kMargin)
make.right.equalTo(rightIconView.snp.left).offset(-kMargin)
}
rightIconView.snp.makeConstraints { (make) in
make.centerY.equalTo(contentView)
make.right.equalTo(contentView).offset(-5)
make.size.equalTo(CGSize.init(width: 20, height: 20))
}
}
/// 商品图片
lazy var logoImgView : UIImageView = UIImageView()
/// 商品名称
lazy var nameLab : UILabel = {
let lab = UILabel()
lab.font = k15Font
lab.textColor = kBlackFontColor
return lab
}()
/// 右侧箭头图标
lazy var rightIconView: UIImageView = UIImageView.init(image: UIImage.init(named: "icon_right_gray"))
}
| mit | 1eb01af036c3969676fcc881b07d69bf | 29.465517 | 105 | 0.621958 | 4.395522 | false | false | false | false |
zmeyc/GRDB.swift | Tests/GRDBTests/SelectStatementTests.swift | 1 | 9962 | import XCTest
#if USING_SQLCIPHER
import GRDBCipher
#elseif USING_CUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
class SelectStatementTests : GRDBTestCase {
override func setup(_ dbWriter: DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
try db.execute(
"CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"creationDate TEXT, " +
"name TEXT NOT NULL, " +
"age INT" +
")")
try db.execute("INSERT INTO persons (name, age) VALUES (?,?)", arguments: ["Arthur", 41])
try db.execute("INSERT INTO persons (name, age) VALUES (?,?)", arguments: ["Barbara", 26])
try db.execute("INSERT INTO persons (name, age) VALUES (?,?)", arguments: ["Craig", 13])
}
try migrator.migrate(dbWriter)
}
func testArrayStatementArguments() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM persons WHERE age < ?")
let ages = [20, 30, 40, 50]
let counts = try ages.map { try Int.fetchOne(statement, arguments: [$0])! }
XCTAssertEqual(counts, [1,2,2,3])
}
}
func testStatementArgumentsSetterWithArray() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM persons WHERE age < ?")
let ages = [20, 30, 40, 50]
let counts = try ages.map { (age: Int) -> Int in
statement.arguments = [age]
return try Int.fetchOne(statement)!
}
XCTAssertEqual(counts, [1,2,2,3])
}
}
func testDictionaryStatementArguments() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM persons WHERE age < :age")
// TODO: Remove this explicit type declaration required by rdar://22357375
let ageDicts: [[String: DatabaseValueConvertible?]] = [["age": 20], ["age": 30], ["age": 40], ["age": 50]]
let counts = try ageDicts.map { dic -> Int in
// Make sure we don't trigger a failible initializer
let arguments: StatementArguments = StatementArguments(dic)
return try Int.fetchOne(statement, arguments: arguments)!
}
XCTAssertEqual(counts, [1,2,2,3])
}
}
func testStatementArgumentsSetterWithDictionary() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM persons WHERE age < :age")
// TODO: Remove this explicit type declaration required by rdar://22357375
let ageDicts: [[String: DatabaseValueConvertible?]] = [["age": 20], ["age": 30], ["age": 40], ["age": 50]]
let counts = try ageDicts.map { ageDict -> Int in
statement.arguments = StatementArguments(ageDict)
return try Int.fetchOne(statement)!
}
XCTAssertEqual(counts, [1,2,2,3])
}
}
func testDatabaseErrorThrownBySelectStatementContainSQL() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
_ = try db.makeSelectStatement("SELECT * FROM blah")
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message!, "no such table: blah")
XCTAssertEqual(error.sql!, "SELECT * FROM blah")
XCTAssertEqual(error.description, "SQLite error 1 with statement `SELECT * FROM blah`: no such table: blah")
}
}
}
func testCachedSelectStatementStepFailure() throws {
let dbQueue = try makeDatabaseQueue()
var needsThrow = false
dbQueue.add(function: DatabaseFunction("bomb", argumentCount: 0, pure: false) { _ in
if needsThrow {
throw DatabaseError(message: "boom")
}
return "success"
})
try dbQueue.inDatabase { db in
let sql = "SELECT bomb()"
needsThrow = false
XCTAssertEqual(try String.fetchAll(db.cachedSelectStatement(sql)), ["success"])
do {
needsThrow = true
_ = try String.fetchAll(db.cachedSelectStatement(sql))
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message!, "boom")
XCTAssertEqual(error.sql!, sql)
XCTAssertEqual(error.description, "SQLite error 1 with statement `\(sql)`: boom")
}
needsThrow = false
XCTAssertEqual(try String.fetchAll(db.cachedSelectStatement(sql)), ["success"])
}
}
func testSelectionInfo() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
class Observer: TransactionObserver {
private var didChange = false
private var inDoubt = false
var triggered = false
var triggeredInDoubt = false
let selectionInfo: SelectStatement.SelectionInfo
init(selectionInfo: SelectStatement.SelectionInfo) {
self.selectionInfo = selectionInfo
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
if let hasImpact = eventKind.impacts(selectionInfo) {
inDoubt = false
return hasImpact
} else {
inDoubt = true
return true
}
}
func databaseDidChange(with event: DatabaseEvent) {
didChange = true
}
func databaseWillCommit() throws { }
func databaseDidCommit(_ db: Database) {
triggered = didChange
triggeredInDoubt = inDoubt
didChange = false
inDoubt = false
}
func databaseDidRollback(_ db: Database) {
didChange = false
inDoubt = false
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) { }
#endif
}
try db.create(table: "table1") { t in
t.column("id", .integer).primaryKey()
t.column("a", .integer)
t.column("b", .integer)
}
try db.create(table: "table2") { t in
t.column("id", .integer).primaryKey()
t.column("a", .integer)
t.column("b", .integer)
}
let statements = try [
db.makeSelectStatement("SELECT * FROM table1"),
db.makeSelectStatement("SELECT id, a FROM table1"),
db.makeSelectStatement("SELECT table1.id, table1.a, table2.a FROM table1 JOIN table2 ON table1.id = table2.id"),
// This last request always triggers its observer because its selectionInfo is doubtful.
// We need SQLite support in order to avoid this doubt.
// TODO: discuss this on SQLite mailing-list.
db.makeSelectStatement("SELECT COUNT(*) FROM table1"),
]
let observers = statements.map { Observer(selectionInfo: $0.selectionInfo) }
for observer in observers {
db.add(transactionObserver: observer)
}
try db.execute("INSERT INTO table1 (id, a, b) VALUES (NULL, 0, 0)")
XCTAssertEqual(observers.map { $0.triggered }, [true, true, true, true])
XCTAssertEqual(observers.map { $0.triggeredInDoubt }, [false, false, false, true])
try db.execute("INSERT INTO table2 (id, a, b) VALUES (NULL, 0, 0)")
XCTAssertEqual(observers.map { $0.triggered }, [false, false, true, true])
XCTAssertEqual(observers.map { $0.triggeredInDoubt }, [false, false, false, true])
try db.execute("UPDATE table1 SET a = 1")
XCTAssertEqual(observers.map { $0.triggered }, [true, true, true, true])
XCTAssertEqual(observers.map { $0.triggeredInDoubt }, [false, false, false, true])
try db.execute("UPDATE table1 SET b = 1")
XCTAssertEqual(observers.map { $0.triggered }, [true, false, false, true])
XCTAssertEqual(observers.map { $0.triggeredInDoubt }, [false, false, false, true])
try db.execute("UPDATE table2 SET a = 1")
XCTAssertEqual(observers.map { $0.triggered }, [false, false, true, true])
XCTAssertEqual(observers.map { $0.triggeredInDoubt }, [false, false, false, true])
try db.execute("UPDATE table2 SET b = 1")
XCTAssertEqual(observers.map { $0.triggered }, [false, false, false, true])
XCTAssertEqual(observers.map { $0.triggeredInDoubt }, [false, false, false, true])
}
}
}
| mit | 4ef9b2eb433501df00ac9cc0f4d5f90a | 42.885463 | 128 | 0.53955 | 5.093047 | false | false | false | false |
anas-imtiaz/SwiftSensorTag | SwiftSensorTag/SensorTagTableViewCell.swift | 1 | 1698 | //
// SensorTagTableViewCell.swift
// SwiftSensorTag
//
// Created by Anas Imtiaz on 13/11/2015.
// Copyright © 2015 Anas Imtiaz. All rights reserved.
//
import UIKit
class SensorTagTableViewCell: UITableViewCell {
var sensorNameLabel = UILabel()
var sensorValueLabel = UILabel()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// sensor name
self.addSubview(sensorNameLabel)
sensorNameLabel.font = UIFont(name: "HelveticaNeue", size: 18)
sensorNameLabel.frame = CGRect(x: self.bounds.origin.x+self.layoutMargins.left*2, y: self.bounds.origin.y, width: self.frame.width, height: self.frame.height)
sensorNameLabel.textAlignment = NSTextAlignment.left
sensorNameLabel.text = "Sensor Name Label"
// sensor value
self.addSubview(sensorValueLabel)
sensorValueLabel.font = UIFont(name: "HelveticaNeue", size: 18)
sensorValueLabel.frame = CGRect(x: self.bounds.origin.x, y: self.bounds.origin.y, width: self.frame.width, height: self.frame.height)
sensorValueLabel.textAlignment = NSTextAlignment.right
sensorValueLabel.text = "Value"
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 40fbdef0e97d01709433ca74a1a01613 | 33.632653 | 166 | 0.670006 | 4.465789 | false | false | false | false |
jcsla/MusicoAudioPlayer | MusicoAudioPlayer/Classes/item/AudioItemQueue.swift | 2 | 5749 | //
// AudioItemQueue.swift
// AudioPlayer
//
// Created by Kevin DELANNOY on 11/03/16.
// Copyright © 2016 Kevin Delannoy. All rights reserved.
//
import Foundation
// MARK: - Array+Shuffe
private extension Array {
/// Shuffles the element in the array and returns the new array.
///
/// - Returns: A shuffled array.
func ap_shuffled() -> [Element] {
return sorted { element1, element2 in
arc4random() % 2 == 0
}
}
}
// MARK: - AudioItemQueue
/// `AudioItemQueue` handles queueing items with a playing mode.
class AudioItemQueue {
/// The original items, keeping the same order.
private(set) var items: [AudioItem]
/// The items stored in the way the mode requires.
private(set) var queue: [AudioItem]
/// The historic of items played in the queue.
private(set) var historic: [AudioItem]
/// The current position in the queue.
var nextPosition = 0
/// The player mode. It will affect the queue.
var mode: AudioPlayerMode {
didSet {
adaptQueue(oldMode: oldValue)
}
}
/// Initializes a queue with a list of items and the mode.
///
/// - Parameters:
/// - items: The list of items to play.
/// - mode: The mode to play items with.
init(items: [AudioItem], mode: AudioPlayerMode) {
self.items = items
self.mode = mode
queue = mode.contains(.shuffle) ? items.ap_shuffled() : items
historic = []
}
/// Adapts the queue to the new mode.
///
/// Behaviour is:
/// - `oldMode` contains .Repeat, `mode` doesn't and last item played == nextItem, we increment position.
/// - `oldMode` contains .Shuffle, `mode` doesnt. We should set the queue to `items` and set current position to the
/// current item index in the new queue.
/// - `mode` contains .Shuffle, `oldMode` doesn't. We should shuffle the leftover items in queue.
///
/// Also, the items already played should also be shuffled. Current implementation has a limitation which is that
/// the "already played items" will be shuffled at the begining of the queue while the leftovers will be shuffled at
/// the end of the array.
///
/// - Parameter oldMode: The mode before it changed.
private func adaptQueue(oldMode: AudioPlayerMode) {
//Early exit if queue is empty
guard queue.count > nextPosition else {
return
}
if oldMode.contains(.repeat) && !mode.contains(.repeat) &&
historic.last == queue[nextPosition] {
nextPosition += 1
}
if oldMode.contains(.shuffle) && !mode.contains(.shuffle) {
queue = items
if let last = historic.last, let index = queue.index(of: last) {
nextPosition = index + 1
}
} else if mode.contains(.shuffle) && !oldMode.contains(.shuffle) {
let alreadyPlayed = queue.prefix(upTo: nextPosition)
let leftovers = queue.suffix(from: nextPosition)
queue = Array(alreadyPlayed).ap_shuffled() + Array(leftovers).ap_shuffled()
}
}
/// Returns the next item in the queue.
///
/// - Returns: The next item in the queue.
func nextItem() -> AudioItem? {
//Early exit if queue is empty
guard !queue.isEmpty else {
return nil
}
if nextPosition < queue.count {
let item = queue[nextPosition]
if !mode.contains(.repeat) {
nextPosition += 1
}
historic.append(item)
return item
}
if mode.contains(.repeatAll) {
nextPosition = 0
return nextItem()
}
return nil
}
/// A boolean value indicating whether the queue has a next item to play or not.
var hasNextItem: Bool {
if !queue.isEmpty &&
(queue.count > nextPosition || mode.contains(.repeat) || mode.contains(.repeatAll)) {
return true
}
return false
}
/// Returns the previous item in the queue.
///
/// - Returns: The previous item in the queue.
func previousItem() -> AudioItem? {
//Early exit if queue is empty
guard !queue.isEmpty else {
return nil
}
let previousPosition = nextPosition - 1
if mode.contains(.repeat) {
let position = max(previousPosition, 0)
let item = queue[position]
historic.append(item)
return item
}
if previousPosition > 0 {
let item = queue[previousPosition - 1]
nextPosition = previousPosition
historic.append(item)
return item
}
if mode.contains(.repeatAll) {
nextPosition = queue.count + 1
return previousItem()
}
return nil
}
/// A boolean value indicating whether the queue has a previous item to play or not.
var hasPreviousItem: Bool {
if !queue.isEmpty &&
(nextPosition > 0 || mode.contains(.repeat) || mode.contains(.repeatAll)) {
return true
}
return false
}
/// Adds a list of items to the queue.
///
/// - Parameter items: The items to add to the queue.
func add(items: [AudioItem]) {
self.items.append(contentsOf: items)
self.queue.append(contentsOf: items)
}
/// Removes an item from the queue.
///
/// - Parameter index: The index of the item to remove.
func remove(at index: Int) {
let item = queue.remove(at: index)
if let index = items.index(of: item) {
items.remove(at: index)
}
}
}
| mit | eec586cd4ecbfa2f7de412cae8227b05 | 29.903226 | 120 | 0.57881 | 4.397858 | false | false | false | false |
Kawoou/KWDrawerController | DrawerController/Transition/DrawerFoldTransition.swift | 1 | 8905 | /*
The MIT License (MIT)
Copyright (c) 2017 Kawoou (Jungwon An)
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
open class DrawerFoldTransition: DrawerTransition {
// MARK: - Internal
private var foldList: [FoldView] = []
// MARK: - Private
private func bindView(content: DrawerContent) {
for foldView in foldList {
foldView.isHidden = false
}
content.viewController.view.isHidden = true
var transform = CATransform3DIdentity
transform.m34 = -1 / 500.0
content.contentView.layer.sublayerTransform = transform
}
private func unbindView(content: DrawerContent) {
for foldView in foldList {
foldView.isHidden = true
}
content.contentView.layer.sublayerTransform = CATransform3DIdentity
content.viewController.view.isHidden = false
}
// MARK: - Public
open override func initTransition(content: DrawerContent) {
super.initTransition(content: content)
}
open override func startTransition(content: DrawerContent, side: DrawerSide) {
super.startTransition(content: content, side: side)
unbindView(content: content)
if content.drawerSide != .none {
/// Initialize
if foldList.count == 0 {
let foldWidth = content.drawerWidth / 2
for i in 0..<2 {
let foldView = FoldView(
frame: CGRect(
x: CGFloat(-foldWidth / 2),
y: CGFloat(0),
width: CGFloat(foldWidth),
height: content.contentView.frame.height
)
)
foldView.layer.anchorPoint = CGPoint(x: Double(i % 2), y: 0.5)
foldView.layer.transform = CATransform3DMakeRotation(CGFloat(Double.pi / 2), 0, 1, 0)
if i == 0 {
foldView.shadowLayer.colors = [UIColor(white: 0.0, alpha: 0.05).cgColor, UIColor(white: 0.0, alpha: 0.6).cgColor]
} else {
foldView.shadowLayer.colors = [UIColor(white: 0.0, alpha: 0.9).cgColor, UIColor(white: 0.0, alpha: 0.55).cgColor]
}
content.contentView.addSubview(foldView)
foldList.append(foldView)
}
}
/// Capture
if let screenshot = content.screenshot(withOptimization: false) {
if screenshot.size.width <= CGFloat(content.drawerWidth) {
let foldWidth = Float(screenshot.size.width) / 2.0
for i in 0..<foldList.count {
let cropRect = CGRect(
x: CGFloat(foldWidth * Float(i) * Float(screenshot.scale)),
y: CGFloat(0.0),
width: CGFloat(foldWidth * Float(screenshot.scale)),
height: CGFloat(Float(screenshot.size.height) * Float(screenshot.scale))
)
if let imageRef: CGImage = screenshot.cgImage?.cropping(to: cropRect) {
foldList[i].layer.contents = imageRef
}
}
}
}
bindView(content: content)
}
}
open override func endTransition(content: DrawerContent, side: DrawerSide) {
super.endTransition(content: content, side: side)
unbindView(content: content)
}
open override func transition(content: DrawerContent, side: DrawerSide, percentage: CGFloat, viewRect: CGRect) {
switch content.drawerSide {
case .left:
let sidePercent = 1.0 + percentage
foldList[0].layer.transform = CATransform3DMakeRotation(CGFloat(Double.pi / 2 - asin(Double(sidePercent))), 0, 1, 0)
foldList[1].layer.transform = CATransform3DConcat(
CATransform3DMakeRotation(CGFloat(Double.pi / 2 - asin(Double(sidePercent))), 0, -1, 0),
CATransform3DMakeTranslation(foldList[0].frame.width * 2, 0, 0)
)
#if swift(>=4.2)
foldList[0].shadowView.alpha = abs(percentage)
foldList[1].shadowView.alpha = abs(percentage)
#else
foldList[0].shadowView.alpha = fabs(percentage)
foldList[1].shadowView.alpha = fabs(percentage)
#endif
let afterDelta = content.drawerWidth - Float(foldList[1].frame.maxX)
content.contentView.transform = .identity
content.contentView.frame = CGRect(
x: viewRect.width * percentage + content.drawerOffset + CGFloat(afterDelta),
y: viewRect.minY,
width: CGFloat(content.drawerWidth),
height: content.contentView.frame.height
)
case .right:
let sidePercent = 1.0 - percentage
content.contentView.transform = .identity
content.contentView.frame = CGRect(
x: viewRect.width * percentage + content.drawerOffset,
y: viewRect.minY,
width: CGFloat(content.drawerWidth),
height: content.contentView.frame.height
)
foldList[0].layer.transform = CATransform3DMakeRotation(CGFloat(Double.pi / 2 - asin(Double(sidePercent))), 0, 1, 0)
foldList[1].layer.transform = CATransform3DConcat(
CATransform3DMakeRotation(CGFloat(Double.pi / 2 - asin(Double(sidePercent))), 0, -1, 0),
CATransform3DMakeTranslation(foldList[0].frame.width * 2, 0, 0)
)
#if swift(>=4.2)
foldList[0].shadowView.alpha = abs(percentage)
foldList[1].shadowView.alpha = abs(percentage)
#else
foldList[0].shadowView.alpha = fabs(percentage)
foldList[1].shadowView.alpha = fabs(percentage)
#endif
default:
content.contentView.transform = .identity
content.contentView.frame = CGRect(
x: viewRect.width * percentage + content.drawerOffset,
y: viewRect.minY,
width: CGFloat(content.drawerWidth),
height: content.contentView.frame.height
)
}
}
public override init() {
super.init()
}
}
private class FoldView: UIView {
// MARK - Property
public var shadowView: UIView {
get {
return internalShadowView
}
}
public var shadowLayer: CAGradientLayer {
get {
return internalShadowLayer
}
}
// MARK - Private
private var internalShadowView: UIView = UIView()
private var internalShadowLayer: CAGradientLayer = CAGradientLayer()
override init(frame: CGRect) {
super.init(frame: frame)
internalShadowView.frame = bounds
addSubview(internalShadowView)
internalShadowLayer = CAGradientLayer()
internalShadowLayer.frame = shadowView.bounds
internalShadowLayer.startPoint = CGPoint(x: 0, y: 0)
internalShadowLayer.endPoint = CGPoint(x: 1, y: 0)
internalShadowView.layer.addSublayer(internalShadowLayer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | ca21f62c91866c8aeaf6e21a74856b02 | 35.646091 | 137 | 0.562942 | 5.005621 | false | false | false | false |
cdtschange/SwiftMKit | SwiftMKitDemo/SwiftMKitDemo/AppDelegate.swift | 1 | 3318 |
// AppDelegate.swift
// SwiftMKitDemo
//
// Created by Mao on 4/14/16.
// Copyright © 2016 cdts. All rights reserved.
//
import UIKit
import CocoaLumberjack
import MagicalRecord
import IQKeyboardManager
import UserNotifications
import SwiftMKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
setenv("XcodeColors", "YES", 0);
// SwiftCrashReport.install(LocalCrashLogReporter.self)
DemoNetworkConfig.Release = false
DemoNetworkConfig.Evn = .product
DDLog.setup(level: .verbose)
DDTTYLogger.sharedInstance.logFormatter = DDLogMKitFormatter()
MagicalRecord.setShouldDeleteStoreOnModelMismatch(true)
MagicalRecord.setupCoreDataStack()
IQKeyboardManager.shared().isEnabled = true
IQKeyboardManager.shared().shouldResignOnTouchOutside = true
NetworkListener.listen()
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = UserNotificationManager.sharedInstance
MKUserNotificationViewController.registerNotificationCategory()
} else {
// Fallback on earlier versions
}
//推送
PushManager.shared.addManagers([SystemPush()])
PushManager.shared.finishLaunch(application: application, didFinishLaunchingWithOptions: launchOptions)
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 96c634f96a34ebbc374a7f2a7e77ac16 | 43.173333 | 285 | 0.734078 | 5.712069 | false | false | false | false |
iOSWizards/AwesomeData | AwesomeData/Classes/Cache/AwesomeCacheManager.swift | 1 | 1794 | //
// AwesomeCacheManager.swift
// Micro Learning App
//
// Created by Evandro Harrison Hoffmann on 01/09/2016.
// Copyright © 2016 Mindvalley. All rights reserved.
//
import UIKit
open class AwesomeCacheManager: NSObject {
/*
* Sets the cache size for the application
* @param memorySize: Size of cache in memory
* @param diskSize: Size of cache in disk
*/
open static func configureCache(withMemorySize memorySize: Int = 4, diskSize: Int = 20){
let cacheSizeMemory = memorySize*1024*1024
let cacheSizeDisk = diskSize*1024*1024
let cache = URLCache(memoryCapacity: cacheSizeMemory, diskCapacity: cacheSizeDisk, diskPath: nil)
URLCache.shared = cache
}
/*
* Clears cache
*/
open static func clearCache(){
URLCache.shared.removeAllCachedResponses()
}
/*
* Get cached object for urlRequest
* @param urlRequest: Request for cached data
*/
open static func getCachedObject(_ urlRequest: URLRequest) -> Data?{
if let cachedObject = URLCache.shared.cachedResponse(for: urlRequest) {
return cachedObject.data
}
return nil
}
/*
* Set object to cache
* @param data: data to cache
*/
open static func cacheObject(_ urlRequest: URLRequest?, response: URLResponse?, data: Data?){
guard let urlRequest = urlRequest else{
return
}
guard let response = response else{
return
}
guard let data = data else{
return
}
let cachedResponse = CachedURLResponse(response: response, data: data)
URLCache.shared.storeCachedResponse(cachedResponse, for: urlRequest)
}
}
| mit | 83c5f3eaaf0af71e8530cf1720a10652 | 27.015625 | 105 | 0.616286 | 4.885559 | false | false | false | false |
BarTabs/bartabs | ios-application/Bar Tabs/AddGeotificationViewController.swift | 1 | 4325 | /**
* Copyright (c) 2016 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
import MapKit
import CoreLocation
protocol AddGeotificationsViewControllerDelegate {
func addGeotificationViewController(controller: AddGeotificationViewController, didAddCoordinate coordinate: CLLocationCoordinate2D,
name: String, radius: Double)
}
class AddGeotificationViewController: UITableViewController, MKMapViewDelegate {
@IBOutlet var addButton: UIBarButtonItem!
@IBOutlet var zoomButton: UIBarButtonItem!
@IBOutlet weak var eventTypeSegmentedControl: UISegmentedControl!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var radiusTextField: UITextField!
@IBOutlet weak var mapView: MKMapView!
var delegate: AddGeotificationsViewControllerDelegate?
var locationManager : CLLocationManager!
var currentOverlay: MKCircle = MKCircle()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItems = [addButton, zoomButton]
addButton.isEnabled = false
self.mapView.delegate = self
self.mapView.addAnnotation(_annotation!)
self.mapView.showAnnotations(self.mapView.annotations, animated: true)
self.addRadiusOverlay(annotation: _annotation!, radius: 100.0)
}
// MARK: Map overlay functions
func addRadiusOverlay(annotation: MKPointAnnotation, radius: CLLocationDistance) {
currentOverlay = MKCircle(center: annotation.coordinate, radius: radius)
self.mapView.add(currentOverlay)
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKCircle {
let circleRenderer = MKCircleRenderer(overlay: overlay)
circleRenderer.lineWidth = 1.0
circleRenderer.strokeColor = .purple
circleRenderer.fillColor = UIColor.purple.withAlphaComponent(0.4)
return circleRenderer
}
return MKOverlayRenderer(overlay: overlay)
}
func removeRadiusOverlay() {
guard let overlays = mapView?.overlays else { return }
for overlay in overlays {
guard let circleOverlay = overlay as? MKCircle else { continue }
mapView?.remove(circleOverlay)
}
}
@IBAction func nameTextFieldEditingChanged(_ sender: Any) {
addButton.isEnabled = !radiusTextField.text!.isEmpty && !nameTextField.text!.isEmpty
}
@IBAction func radiusTextDidChange(_ sender: Any) {
removeRadiusOverlay()
addRadiusOverlay(annotation: _annotation!, radius: Double(radiusTextField.text!) ?? 0.0)
}
@IBAction func onCancel(sender: AnyObject) {
dismiss(animated: true, completion: nil)
}
@IBAction private func onAdd(sender: AnyObject) {
let name = nameTextField.text ?? ""
let coordinate = _annotation!.coordinate
let radius = Double(radiusTextField.text!) ?? 0
delegate?.addGeotificationViewController(controller: self, didAddCoordinate: coordinate, name: name, radius: radius)
}
@IBAction func onZoomToCurrentLocation(_ sender: Any) {
mapView.zoomToUserLocation()
}
}
| gpl-3.0 | 5b23a6540dadcd64a46ff1903cddf02a | 39.801887 | 136 | 0.705665 | 5.124408 | false | false | false | false |
teklabs/MyTabBarApp | MyTabBarApp/CategoryPickerViewController.swift | 1 | 2479 | //
// CategoryPickerViewController.swift
// MyTabBarApp
//
// Created by teklabsco on 11/17/15.
// Copyright © 2015 Teklabs, LLC. All rights reserved.
//
import UIKit
class CategoryPickerViewController: UITableViewController {
var categories:[String] = [
"Health",
"Job",
"Wisdom",
"Faith",
"Family",
"Natural Disaster"]
var selectedCategory:String? {
didSet {
if let category = selectedCategory {
selectedCategoryIndex = categories.indexOf(category)!
}
}
}
var selectedCategoryIndex:Int?
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CategoryCell", forIndexPath: indexPath)
cell.textLabel?.text = categories[indexPath.row]
if indexPath.row == selectedCategoryIndex {
cell.accessoryType = .Checkmark
} else {
cell.accessoryType = .None
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
//Other row is selected - need to deselect it
if let index = selectedCategoryIndex {
let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: index, inSection: 0))
cell?.accessoryType = .None
}
selectedCategory = categories[indexPath.row]
//update the checkmark for the current row
let cell = tableView.cellForRowAtIndexPath(indexPath)
cell?.accessoryType = .Checkmark
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "SaveSelectedCategory" {
if let cell = sender as? UITableViewCell {
let indexPath = tableView.indexPathForCell(cell)
if let index = indexPath?.row {
selectedCategory = categories[index]
}
}
}
}
}
| gpl-3.0 | 25ed8ba024ebd33141dd4c7f4183c0f6 | 30.769231 | 118 | 0.618241 | 5.568539 | false | false | false | false |
nitrado/NitrAPI-Swift | Pod/Classes/services/fileserver/FileEntry.swift | 1 | 1536 | import ObjectMapper
open class FileEntry: Mappable {
public class FileType: Value {
/// This entry is a file.
public static let FILE = FileType("file")
/// This entry is a directory.
public static let DIR = FileType("dir")
}
// MARK: - Attributes
open fileprivate(set) var type: FileType?
open fileprivate(set) var path: String?
open fileprivate(set) var name: String?
open fileprivate(set) var size: Int?
open fileprivate(set) var owner: String?
open fileprivate(set) var group: String?
/// Access rights of this file in chmod notation.
open fileprivate(set) var chmod: String?
open fileprivate(set) var createdAt: Int? // TODO: change these to date someday?
open fileprivate(set) var modifiedAt: Int?
open fileprivate(set) var accessedAt: Int?
// MARK: - Initialization
public required init?(map: Map) {
}
public init (name: String, path: String) {
self.name = name
self.path = path
self.type = .DIR
}
open func mapping(map: Map) {
type <- (map["type"], ValueTransform<FileType>())
path <- map["path"]
name <- map["name"]
size <- map["size"]
owner <- map["owner"]
group <- map["group"]
chmod <- map["chmod"]
createdAt <- map["created_at"]
modifiedAt <- map["modified_at"]
accessedAt <- map["accessed_at"]
}
}
| mit | ab441a5a3871399b7db72defea22abb6 | 28.538462 | 84 | 0.5625 | 4.290503 | false | false | false | false |
Hunter-Li-EF/HLAlbumPickerController | HLAlbumPickerController/Classes/HLAlbumsViewController.swift | 1 | 11805 | //
// HLAlbumsViewController.swift
// Pods
//
// Created by Hunter Li on 31/8/2016.
//
//
import UIKit
import Photos
internal class HLAlbumsViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
fileprivate var captureDeviceAccessGranted: Bool = false
fileprivate var albumGroupView: HLAlbumGroupView?
fileprivate var titleView: HLAlbumGroupControl?
fileprivate let collectionViewAssetCellIdentifier = "collectionViewAssetCellIdentifier"
fileprivate let collectionViewCameraCellIdentifier = "collectionViewCameraCellIdentifier"
fileprivate var collectionView: UICollectionView?
fileprivate let imageManager = PHCachingImageManager()
fileprivate var assetGroups: [PHAssetCollection] = []
fileprivate var assets: [PHAsset?] = []
fileprivate var fetchResult: PHFetchResult<PHAsset>!{
willSet{
self.assets.removeAll()
if captureDeviceAccessGranted {
self.assets.insert(nil, at: 0)
}
newValue?.enumerateObjects({ (anyObject, index, stop) in
if let asset = anyObject as? PHAsset{
self.assets.append(asset)
}
})
}
}
override func viewDidLoad() {
super.viewDidLoad()
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo) { (granted: Bool) in
self.captureDeviceAccessGranted = granted
}
view.backgroundColor = UIColor.white
PHPhotoLibrary.shared().register(self)
setupTitleView()
setupCancelButton()
setupCollectionView()
loadAssetGroups()
}
deinit {
PHPhotoLibrary.shared().unregisterChangeObserver(self)
}
func selectAlbumGroup(_ titleView: HLAlbumGroupControl) {
titleView.isSelected = !titleView.isSelected
if !titleView.isSelected {
self.albumGroupView?.dismiss()
return
}
let albumGroupView = HLAlbumGroupView()
albumGroupView.assetGroup = assetGroups
albumGroupView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(albumGroupView)
self.albumGroupView = albumGroupView
view.addConstraint(NSLayoutConstraint(item: albumGroupView, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1.0, constant: 0))
view.addConstraint(NSLayoutConstraint(item: albumGroupView, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1.0, constant: 0))
view.addConstraint(NSLayoutConstraint(item: albumGroupView, attribute: .top, relatedBy: .equal, toItem: collectionView, attribute: .top, multiplier: 1.0, constant: 0))
view.addConstraint(NSLayoutConstraint(item: albumGroupView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0))
albumGroupView.show()
albumGroupView.assetCollectionSelected = { [weak self] (assetGroup) in
titleView.isSelected = !titleView.isSelected
guard let group = assetGroup else {
return
}
self?.loadAlbumAssets(group)
}
}
func cancel(_ button: UIButton) {
dismiss(animated: true) {
if let nav = self.navigationController as? HLAlbumPickerController{
nav.pickerDelegate?.imagePickerControllerDidCancel(picker: nav)
}
}
}
fileprivate func setupTitleView(){
let titleView = HLAlbumGroupControl(frame: CGRect(x: 0,y: 0,width: 100,height: 40))
titleView.addTarget(self, action: #selector(HLAlbumsViewController.selectAlbumGroup(_:)), for: .touchUpInside)
navigationItem.titleView = titleView
self.titleView = titleView
}
fileprivate func setupCancelButton(){
let cancelButton = UIButton(type: .custom)
cancelButton.setTitle("Cancel", for: UIControlState())
cancelButton.setTitleColor(UIColor.gray, for: UIControlState())
cancelButton.sizeToFit()
cancelButton.addTarget(self, action: #selector(HLAlbumsViewController.cancel(_:)), for: .touchUpInside)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: cancelButton)
}
fileprivate func setupCollectionView(){
let layout = UICollectionViewFlowLayout();
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(HLAssetCell.self, forCellWithReuseIdentifier: collectionViewAssetCellIdentifier)
collectionView.register(HLCaremaCell.self, forCellWithReuseIdentifier: collectionViewCameraCellIdentifier)
collectionView.backgroundColor = UIColor.clear
view.addSubview(collectionView)
self.collectionView = collectionView
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collectionView":collectionView]))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[collectionView]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collectionView":collectionView]))
}
// MARK: - load albums group
fileprivate func loadAssetGroups(){
let userLibrary = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: nil)
userLibrary.enumerateObjects ({ (anyObject, index, stop) in
if let assetCollect = anyObject as? PHAssetCollection{
self.assetGroups.append(assetCollect)
self.loadAlbumAssets(assetCollect)
}
})
let custom = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: nil)
custom.enumerateObjects({ (anyObject, index, stop) in
if let assetCollect = anyObject as? PHAssetCollection{
self.assetGroups.append(assetCollect)
}
})
}
// MARK: - load album group photos
fileprivate func loadAlbumAssets(_ assetGroup: PHAssetCollection){
let options = PHFetchOptions()
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
fetchResult = PHAsset.fetchAssets(in: assetGroup, options: options)
self.titleView?.titleLable?.text = assetGroup.localizedTitle
self.collectionView?.reloadData()
}
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return assets.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
if (indexPath as NSIndexPath).row == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionViewCameraCellIdentifier, for: indexPath) as! HLCaremaCell
cell.refreshView()
return cell
}else{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionViewAssetCellIdentifier, for: indexPath) as! HLAssetCell
if let asset = assets[indexPath.item]{
cell.refreshView(asset)
}
return cell
}
}
// MARK: - UICollectionViewDelegateFlowLayout
fileprivate let padding: CGFloat = 5
fileprivate let column = 3
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
let width = (collectionView.frame.width - CGFloat(column+1)*padding)/CGFloat(column)
return CGSize(width: width, height: width)
}
// MARK: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
if (indexPath as NSIndexPath).row == 0 {
navigationController?.pushViewController(HLCameraViewController(), animated: true)
}else{
guard let asset = assets[indexPath.item] else{
return
}
let options = PHImageRequestOptions()
options.version = .original
options.deliveryMode = .highQualityFormat
options.isSynchronous = true
PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width: view.frame.width, height: view.frame.height), contentMode: .aspectFit, options: options) { (image, mdeia) in
let controller = HLImageViewController()
controller.image = image
self.navigationController?.pushViewController(controller, animated: true)
}
}
}
}
// MARK: PHPhotoLibraryChangeObserver
extension HLAlbumsViewController: PHPhotoLibraryChangeObserver {
func photoLibraryDidChange(_ changeInstance: PHChange) {
guard let changes = changeInstance.changeDetails(for: fetchResult) else { return }
guard let collectionView = self.collectionView else { return }
DispatchQueue.main.sync {
fetchResult = changes.fetchResultAfterChanges
var shouldReload = false
if let removed = changes.removedIndexes, let changed = changes.changedIndexes {
let removedPaths = removed.map({ IndexPath(item: $0, section: 0) })
let changedPaths = changed.map({ IndexPath(item: $0, section: 0) })
for changedPath in changedPaths{
if removedPaths.contains(changedPath){
shouldReload = true
break
}
}
if let item = removedPaths.last?.item, item >= fetchResult.count{
shouldReload = true
}
}
if changes.hasIncrementalChanges && !shouldReload {
collectionView.performBatchUpdates({
let deltIndex = self.captureDeviceAccessGranted ? 1 : 0
if let inserted = changes.insertedIndexes, inserted.count > 0 {
collectionView.insertItems(at: inserted.map({ IndexPath(item: $0 + deltIndex, section: 0) }))
}
if let changed = changes.changedIndexes, changed.count > 0 {
collectionView.reloadItems(at: changed.map({ IndexPath(item: $0 + deltIndex, section: 0) }))
}
if let removed = changes.removedIndexes, removed.count > 0 {
collectionView.deleteItems(at: removed.map({ IndexPath(item: $0 + deltIndex, section: 0) }))
}
changes.enumerateMoves { fromIndex, toIndex in
collectionView.moveItem(at: IndexPath(item: fromIndex + deltIndex, section: 0),
to: IndexPath(item: toIndex + deltIndex, section: 0))
}
}, completion: nil)
}else{
collectionView.reloadData()
}
}
}
}
extension HLAlbumsViewController{
override public var preferredStatusBarStyle : UIStatusBarStyle {
return .lightContent
}
}
| mit | b25011e59fc16b0e0cdca9a2fca338ab | 42.400735 | 208 | 0.640068 | 5.725024 | false | false | false | false |
WhisperSystems/Signal-iOS | SignalMessaging/Views/ImageEditor/OWSViewController+ImageEditor.swift | 1 | 1668 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import UIKit
public extension NSObject {
func navigationBarButton(imageName: String,
selector: Selector) -> UIView {
let button = OWSButton()
button.setImage(imageName: imageName)
button.tintColor = .white
button.addTarget(self, action: selector, for: .touchUpInside)
button.layer.shadowColor = UIColor.black.cgColor
button.layer.shadowRadius = 2
button.layer.shadowOpacity = 0.66
button.layer.shadowOffset = .zero
return button
}
}
// MARK: -
public extension UIViewController {
func updateNavigationBar(navigationBarItems: [UIView]) {
guard navigationBarItems.count > 0 else {
self.navigationItem.rightBarButtonItems = []
return
}
let spacing: CGFloat = 16
let stackView = UIStackView(arrangedSubviews: navigationBarItems)
stackView.axis = .horizontal
stackView.spacing = spacing
stackView.alignment = .center
// Ensure layout works on older versions of iOS.
var stackSize = CGSize.zero
for item in navigationBarItems {
let itemSize = item.sizeThatFits(.zero)
stackSize.width += itemSize.width + spacing
stackSize.height = max(stackSize.height, itemSize.height)
}
if navigationBarItems.count > 0 {
stackSize.width -= spacing
}
stackView.frame = CGRect(origin: .zero, size: stackSize)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: stackView)
}
}
| gpl-3.0 | 468fd362e9948077e68fa08d9af5fbc3 | 30.471698 | 87 | 0.632494 | 5.116564 | false | false | false | false |
PFei-He/Project-Swift | Project/Project/AppDelegate.swift | 1 | 6474 | //
// AppDelegate.swift
// Project
//
// Created by PFei_He on 16/5/10.
// Copyright © 2016年 PFei_He. All rights reserved.
//
// ***** AppDelegate *****
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//打开调试模式
DebugMode.open(true)
//初始化登录页(初始打开为引导页)
window?.rootViewController = Initialization.initLaunch()
//初始化主机地址
Initialization.initHost("http://www.weather.com.cn/data/sk/")
//初始化接口
Initialization.initApi()
//初始化用户文件
Initialization.initUserFile()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.PF-Lib.Project" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Project", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | 140cb022ca9ff71cb3b81d19535481b7 | 50.524194 | 291 | 0.708562 | 5.719785 | false | false | false | false |
raphibolliger/SwiftOpenCV | SwiftOpenCV/ViewController.swift | 1 | 4459 | //
// ViewController.swift
// SwiftOpenCV
//
// Created by Lee Whitney on 10/28/14.
// Copyright (c) 2014 WhitneyLand. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate {
@IBOutlet weak var imageView: UIImageView!
var selectedImage : UIImage!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onTakePictureTapped(sender: AnyObject) {
var sheet: UIActionSheet = UIActionSheet();
let title: String = "Please choose an option";
sheet.title = title;
sheet.delegate = self;
sheet.addButtonWithTitle("Choose Picture");
sheet.addButtonWithTitle("Take Picture");
sheet.addButtonWithTitle("Cancel");
sheet.cancelButtonIndex = 2;
sheet.showInView(self.view);
}
func actionSheet(sheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int) {
var imagePicker = UIImagePickerController()
imagePicker.delegate = self
switch buttonIndex{
case 0:
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.allowsEditing = false
imagePicker.delegate = self
self.presentViewController(imagePicker, animated: true, completion: nil)
break;
case 1:
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
imagePicker.allowsEditing = false
imagePicker.delegate = self
self.presentViewController(imagePicker, animated: true, completion: nil)
break;
default:
break;
}
}
@IBAction func onDetectTapped(sender: AnyObject) {
var progressHud = MBProgressHUD.showHUDAddedTo(view, animated: true)
progressHud.labelText = "Detecting..."
progressHud.mode = MBProgressHUDModeIndeterminate
var ocr = SwiftOCR(fromImage: selectedImage)
ocr.recognize()
imageView.image = ocr.groupedImage
progressHud.hide(true);
}
@IBAction func onRecognizeTapped(sender: AnyObject) {
if((self.selectedImage) != nil){
var progressHud = MBProgressHUD.showHUDAddedTo(view, animated: true)
progressHud.labelText = "Detecting..."
progressHud.mode = MBProgressHUDModeIndeterminate
dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in
var ocr = SwiftOCR(fromImage: self.selectedImage)
ocr.recognize()
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
self.imageView.image = ocr.groupedImage
progressHud.hide(true);
var dprogressHud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
dprogressHud.labelText = "Recognizing..."
dprogressHud.mode = MBProgressHUDModeIndeterminate
var text = ocr.recognizedText
self.performSegueWithIdentifier("ShowRecognition", sender: text);
dprogressHud.hide(true)
})
})
}else {
var alert = UIAlertView(title: "SwiftOCR", message: "Please select image", delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!) {
selectedImage = image;
picker.dismissViewControllerAnimated(true, completion: nil);
imageView.image = selectedImage;
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
picker.dismissViewControllerAnimated(true, completion: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var vc = segue.destinationViewController as! DetailViewController
vc.recognizedText = sender as! String!
}
}
| mit | 7824e0d1a826c20442232fbb64f953e8 | 34.388889 | 133 | 0.606863 | 5.945333 | false | false | false | false |
RylynnLai/V2EX_sf | V2EX/View/RLNodesHeadView.swift | 1 | 1196 | //
// RLNodesHeadView.swift
// V2EX
//
// Created by LLZ on 16/3/15.
// Copyright © 2016年 ucs. All rights reserved.
//
import UIKit
class RLNodesHeadView: UIView {
@IBOutlet weak var _titleLable: UILabel!
@IBOutlet weak var _iconImgV: UIImageView!
@IBOutlet weak var _startsNumLable: UILabel!
@IBOutlet weak var _topicsNumLable: UILabel!
@IBOutlet weak var _descriptionLable: UILabel!
// MARk:setter方法
var nodeModel:Node? {
didSet{
//标题
_titleLable.text = nodeModel!.title;
//icon
_iconImgV.sd_setImageWithURL(NSURL(string: "https:\(nodeModel!.avatar_normal ?? "")"), placeholderImage: UIImage.init(named: "icon_rayps_64@2x"))
//话题数
_topicsNumLable.text = nodeModel?.topics?.stringValue
//星
if nodeModel!.stars != nil {
_startsNumLable.text = "★\(nodeModel!.stars!)"
}
//描述
_descriptionLable.text = nodeModel?.header
}
}
override func layoutSubviews() {
//更新高度
self.mj_h = _descriptionLable.frame.maxY + 10
}
}
| mit | 5eb5f92f9c4c4664a784f199f2d24c23 | 26.046512 | 157 | 0.571797 | 3.982877 | false | false | false | false |
telip007/ChatFire | Pods/ALCameraViewController/ALCameraViewController/Utilities/Utilities.swift | 2 | 3927 | //
// ALUtilities.swift
// ALCameraViewController
//
// Created by Alex Littlejohn on 2015/06/25.
// Copyright (c) 2015 zero. All rights reserved.
//
import UIKit
import AVFoundation
internal func radians(degrees: Double) -> Double {
return degrees / 180 * M_PI
}
internal func localizedString(key: String) -> String {
return NSLocalizedString(key, tableName: CameraGlobals.shared.stringsTable, bundle: CameraGlobals.shared.bundle, comment: key)
}
internal func currentRotation(oldOrientation: UIInterfaceOrientation, newOrientation: UIInterfaceOrientation) -> Double {
switch oldOrientation {
case .Portrait:
switch newOrientation {
case .LandscapeLeft: return 90
case .LandscapeRight: return -90
case .PortraitUpsideDown: return 180
default: return 0
}
case .LandscapeLeft:
switch newOrientation {
case .Portrait: return -90
case .LandscapeRight: return 180
case .PortraitUpsideDown: return 90
default: return 0
}
case .LandscapeRight:
switch newOrientation {
case .Portrait: return 90
case .LandscapeLeft: return 180
case .PortraitUpsideDown: return -90
default: return 0
}
default: return 0
}
}
internal func largestPhotoSize() -> CGSize {
let scale = UIScreen.mainScreen().scale
let screenSize = UIScreen.mainScreen().bounds.size
let size = CGSize(width: screenSize.width * scale, height: screenSize.height * scale)
return size
}
internal func errorWithKey(key: String, domain: String) -> NSError {
let errorString = localizedString(key)
let errorInfo = [NSLocalizedDescriptionKey: errorString]
let error = NSError(domain: domain, code: 0, userInfo: errorInfo)
return error
}
internal func normalizedRect(rect: CGRect, orientation: UIImageOrientation) -> CGRect {
let normalizedX = rect.origin.x
let normalizedY = rect.origin.y
let normalizedWidth = rect.width
let normalizedHeight = rect.height
var normalizedRect: CGRect
switch orientation {
case .Up, .UpMirrored:
normalizedRect = CGRect(x: normalizedX, y: normalizedY, width: normalizedWidth, height: normalizedHeight)
case .Down, .DownMirrored:
normalizedRect = CGRect(x: 1-normalizedX-normalizedWidth, y: 1-normalizedY-normalizedHeight, width: normalizedWidth, height: normalizedHeight)
case .Left, .LeftMirrored:
normalizedRect = CGRect(x: 1-normalizedY-normalizedHeight, y: normalizedX, width: normalizedHeight, height: normalizedWidth)
case .Right, .RightMirrored:
normalizedRect = CGRect(x: normalizedY, y: 1-normalizedX-normalizedWidth, width: normalizedHeight, height: normalizedWidth)
}
return normalizedRect
}
internal func flashImage(mode: AVCaptureFlashMode) -> String {
let image: String
switch mode {
case .Auto:
image = "flashAutoIcon"
case .On:
image = "flashOnIcon"
case .Off:
image = "flashOffIcon"
}
return image
}
struct ScreenSize {
static let SCREEN_WIDTH = UIScreen.mainScreen().bounds.size.width
static let SCREEN_HEIGHT = UIScreen.mainScreen().bounds.size.height
static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}
struct DeviceConfig {
static let SCREEN_MULTIPLIER : CGFloat = {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
switch ScreenSize.SCREEN_MAX_LENGTH {
case 568.0: return 1.5
case 667.0: return 2.0
case 736.0: return 4.0
default: return 1.0
}
} else {
return 1.0
}
}()
}
| apache-2.0 | 43a1afc5328b2007f183d347c9136316 | 32 | 150 | 0.640438 | 4.794872 | false | false | false | false |
brentsimmons/Frontier | BeforeTheRename/UserTalk/UserTalk/Runtime/LangEvaluator.swift | 1 | 8661 | //
// Lang.swift
// UserTalk
//
// Created by Brent Simmons on 4/23/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import FrontierData
public class LangEvaluator {
fileprivate var lineNumber = 0
fileprivate var characterIndex = 0
fileprivate var errorNode: CodeTreeNode?
fileprivate var flreturn = false
fileprivate var flbreak = false
fileprivate var flcontinue = false
public func runCode(codeTreeNode: CodeTreeNode, context: HashTable?) throws -> Value {
guard let firstNode = codeTreeNode.param1 else {
return false //TODO: empty script error, perhaps
}
do {
return try evaluateList(firstNode)
}
catch { throw error }
}
public func evaluateList(_ codeTreeNode: CodeTreeNode) throws -> Value {
var programCounter: CodeTreeNode? = codeTreeNode
var val = emptyValue
do {
while true {
if programCounter == nil {
break
}
setErrorLine(programCounter!)
// TODO: check if user killed script
// TODO: check if debugger killed script
val = try evaluateTree(programCounter!)
if flbreak || flreturn || flcontinue {
break
}
if let next = programCounter!.link {
programCounter = next
}
}
}
catch let e as LangError {
if let _ = e.lineNumber {
throw e
}
else {
throw langError(e.errorType)
}
}
catch { throw error }
return val
}
public func evaluateTree(_ node: CodeTreeNode) throws -> Value {
let op = node.nodeType
let ctParams = node.ctParams
var val1 = emptyValue
var val2 = emptyValue
do {
if ctParams > 0 && op.shouldEvaluateParam1 {
val1 = try evaluateTree(node.param1!)
if flreturn {
return true
}
}
if ctParams > 1 && op.shouldEvaluateParam2 {
val2 = try evaluateTree(node.param2!)
if flreturn {
return true
}
}
setErrorLine(node)
switch op {
// case noOp:
// return true
case .localOp:
return addLocals(node)
case .moduleOp:
return addHandler(node)
case .identifierOp, .bracketOp:
return idvalue(node)
case .dotOp:
return dotValue(node)
case .addressOfOp:
return addressOfValue(node.param1!)
case .dereferenceOp:
return dereferenceValue(node.param1!)
case .arrayOp:
return arrayValue(node)
case .constOp:
return copyValue(node.value!)
case .assignOp:
if !assignValue(node.param1!, val2) {
return false
}
if val2.valueType == .external || !needAssignmentResult(node) {
return true
}
return copyValue(val2)
case .functionOp:
return functionValue(node.param1!, node.param2!)
case .addOp:
return try val1.add(val2)
case .subtractOp:
return try val1.subtract(val2)
case .unaryOp:
return try val1.unaryMinusValue()
case .multiplyOp:
return try val1.multiply(val2)
case .divideOp:
return try val1.divide(val2)
case .addValueOp:
return modifyAssignValue(node.param1!, val2, .addOp, needAssignmentResult(node))
case .subtractValueOp:
return modifyAssignValue(node.param1!, val2, .subtractOp, needAssignmentResult(node))
case .multiplyValueOp:
return modifyAssignValue(node.param1!, val2, .multiplyOp, needAssignmentResult(node))
case .divideValueOp:
return modifyAssignValue(node.param1!, val2, .divideOp, needAssignmentResult(node))
case .modOp:
return try val1.mod(val2)
case .notOp:
return try val1.not()
// case equalsOp:
// return try val1.equals(val2)
//
// case notEqualsOp:
// return try !(val1.equals(val2))
//
// case greaterThanOp:
// return try val1.greaterThan(val2)
//
// case lessThanOp:
// return try val1.lessThan(val2)
//
// case greaterThanEqualsOp:
// return try val1.greaterThanEqual(val2)
//
// case lessThanEqualsOp:
// return try val1.lessThanEqual(val2)
//
// case beginsWithOp:
// return try val1.beginsWith(val2)
//
// case containsOp:
// return try val1.contains(val2)
// case orOrOp:
// return orOrValue(val1, node.param2!)
//
// case andAndOp:
// return andAndValue(val1, node.param2!)
// case breakOp:
// flbreak = true
// return true
// case continueOp:
// flcontinue = true
// return true
//
// case withOp:
// return evaluateWith(node)
// case returnOp:
// flreturn = true
// if val1.valueType == .none {
// return true
// }
// return val1
// case bundleOp:
// return try evaluateList(node.param1!)
// case ifOp: //{
// let fl = try val1.asBool()
// if let ifNode = fl ? node.param2 : node.param3 {
// return try evaluateList(ifNode)
// }
// else {
// return true
// }
// //}
// case caseOp:
// return evaluateCase(node)
case .loopOp:
return evaluateLoop(node)
case .fileLoopOp:
return evaluateFileLoop(node)
case .forLoopOp:
return evaluateForLoop(node, val1, val2, 1)
case .forDownLoopOp:
return evaluateForLoop(node, val1, val2, -1)
case .incrementPreOp:
return try incrementValue(node.param1!, increment: true, pre: true)
case .incrementPostOp:
return try incrementValue(node.param1!, increment: true, pre: false)
case .decrementPreOp:
return try incrementValue(node.param1!, increment: false, pre: true)
case .decrementPostOp:
return try incrementValue(node.param1!, increment: false, pre: false)
// case tryOp:
// return evaluateTry(node)
case .rangeOp:
throw langError(.badRangeOperation)
case .fieldOp:
throw langError(.badFieldOperation)
case .listOp:
return makeList(node.param1!)
case .recordOp:
return makeRecord(node.param1!)
case .forInLoopOp:
return evaluateForInLoop(node, val1)
default:
break
}
throw langError(.unexpectedOpCode)
}
catch let e as LangError {
if let _ = e.lineNumber {
throw e
}
else {
throw langError(e.errorType)
}
}
catch {
throw error
}
}
}
private extension LangEvaluator {
func langError(_ errorType: LangError.LangErrorType) -> LangError {
return LangError(errorType, lineNumber: lineNumber, characterIndex: characterIndex)
}
func setErrorLine(_ node: CodeTreeNode) {
if let lineNumber = node.lineNumber {
self.lineNumber = lineNumber
}
if let characterIndex = node.characterIndex {
self.characterIndex = characterIndex
}
errorNode = node
}
}
private extension LangEvaluator {
func addLocals(_ node: CodeTreeNode) -> Bool {
return true
}
func addHandler(_ node: CodeTreeNode) -> Bool {
return true
}
func idvalue(_ node: CodeTreeNode) -> Bool {
return true
}
func dotValue(_ node: CodeTreeNode) -> Bool {
return true
}
func addressOfValue(_ node: CodeTreeNode) -> Bool {
return true
}
func dereferenceValue(_ node: CodeTreeNode) -> Bool {
return true
}
func arrayValue(_ node: CodeTreeNode) -> Bool {
return true
}
func copyValue(_ value: Value) -> Bool {
return true
}
func assignValue(_ node: CodeTreeNode, _ value: Value) -> Bool {
return true
}
func needAssignmentResult(_ node: CodeTreeNode) -> Bool {
return true
}
func functionValue(_ node: CodeTreeNode, _ node2: CodeTreeNode) -> Bool {
return true
}
func orOrValue(_ value: Value, _ node: CodeTreeNode) -> Bool {
return true
}
func andAndValue(_ value: Value, _ node: CodeTreeNode) -> Bool {
return true
}
func evaluateWith(_ node: CodeTreeNode) -> Bool {
return true
}
func evaluateCase(_ node: CodeTreeNode) -> Bool {
return true
}
func evaluateLoop(_ node: CodeTreeNode) -> Bool {
return true
}
func evaluateFileLoop(_ node: CodeTreeNode) -> Bool {
return true
}
func evaluateForLoop(_ node: CodeTreeNode, _ val1: Value, _ val2: Value, _ increment: Int) -> Value {
return true
}
func incrementValue(_ node: CodeTreeNode, increment: Bool, pre: Bool) throws -> Value {
return true
}
func evaluateTry(_ node: CodeTreeNode) -> Bool {
return true
}
func makeList(_ node: CodeTreeNode) -> Bool {
return true
}
func makeRecord(_ node: CodeTreeNode) -> Bool {
return true
}
func evaluateForInLoop(_ node: CodeTreeNode, _ value: Value) -> Bool {
return true
}
func modifyAssignValue(_ node: CodeTreeNode, _ value: Value, _ operation: CodeTreeNodeType, _ needResult: Bool) -> Bool {
return true
}
}
| gpl-2.0 | c2e406d64ed9bf56714e7178a3a16479 | 18.548533 | 122 | 0.638684 | 3.304082 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Tree/101_Symmetric Tree.swift | 1 | 2280 | // 101_Symmetric Tree
// https://leetcode.com/problems/symmetric-tree/
//
// Created by Honghao Zhang on 9/21/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
//
//For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
//
// 1
// / \
// 2 2
// / \ / \
//3 4 4 3
//
//
//But the following [1,2,2,null,3,null,3] is not:
//
// 1
// / \
// 2 2
// \ \
// 3 3
//
//
//Note:
//Bonus points if you could solve it both recursively and iteratively.
//
import Foundation
class Num101 {
/// Recursive way, to check if the root.left and root.right is mirror
func isSymmetric_recursive(_ root: TreeNode?) -> Bool {
return isMirror(root?.left, root?.right)
}
private func isMirror(_ root1: TreeNode?, _ root2: TreeNode?) -> Bool {
if root1 == nil, root2 == nil {
return true
}
if root1 == nil, root2 != nil {
return false
}
if root1 != nil, root2 == nil {
return false
}
return root1!.val == root2!.val &&
isMirror(root1!.left, root2!.right) &&
isMirror(root1!.right, root2!.left)
}
/// Iterative, BFS with queue
func isSymmetric_iterative(_ root: TreeNode?) -> Bool {
if root == nil {
return true
}
var queue: [TreeNode] = [root!, root!]
while !queue.isEmpty {
let node1 = queue.removeFirst()
let node2 = queue.removeFirst()
// node1 and node2 should be same
guard node1.val == node2.val else {
return false
}
// and node1.left should be equal to node2.right
if let node1Left = node1.left, let node2Right = node2.right {
queue.append(node1Left)
queue.append(node2Right)
}
else if let _ = node1.left {
return false
}
else if let _ = node2.right {
return false
}
// and node1.right should be equal to node2.left
if let node1Right = node1.right, let node2Left = node2.left {
queue.append(node1Right)
queue.append(node2Left)
}
else if let _ = node1.right {
return false
}
else if let _ = node2.left {
return false
}
}
return queue.isEmpty
}
}
| mit | aaba0cb688cfd9808e1df1cc8e553d02 | 23.244681 | 97 | 0.581834 | 3.361357 | false | false | false | false |
tqtifnypmb/SwiftyImage | Framenderer/Sources/Filters/TwoPassFilter.swift | 2 | 1936 | //
// TwoPassFilter.swift
// Framenderer
//
// Created by tqtifnypmb on 11/12/2016.
// Copyright © 2016 tqitfnypmb. All rights reserved.
//
import Foundation
import OpenGLES.ES3.gl
import OpenGLES.ES3.glext
open class TwoPassFilter: BaseFilter {
var _program2: Program!
private var _isProgram2Setup = false
func bindAttributes2(context: Context) {
let attr = [kVertexPositionAttribute, kTextureCoorAttribute]
_program2.bind(attributes: attr)
}
func setUniformAttributs2(context: Context) {
_program2.setUniform(name: kFirstInputSampler, value: GLint(1))
}
deinit {
if _program2 != nil {
ProgramObjectsCacher.shared.release(program: _program2)
_program2 = nil
}
}
func prepareSecondPass(context: Context) throws {}
override public func apply(context ctx: Context) throws {
try super.apply(context: ctx)
do {
try prepareSecondPass(context: ctx)
glActiveTexture(GLenum(GL_TEXTURE1))
// enable input/output toggle, in case disbaled by frame stream
let old = ctx.enableInputOutputToggle
ctx.enableInputOutputToggle = true
ctx.toggleInputOutputIfNeeded()
ctx.enableInputOutputToggle = old
if !_isProgram2Setup {
_isProgram2Setup = true
bindAttributes2(context: ctx)
try _program2.link()
ctx.setCurrent(program: _program2)
setUniformAttributs2(context: ctx)
} else {
ctx.setCurrent(program: _program2)
}
try feedDataAndDraw(context: ctx, program: _program2)
} catch {
throw FilterError.filterError(name: self.name, error: error.localizedDescription)
}
}
}
| mit | 48bba62756f3274fbe3a8b7e50a3577a | 28.769231 | 93 | 0.588114 | 4.51049 | false | false | false | false |
movabletype/smartphone-app | MT_iOS/MT_iOS/Classes/Model/UploadItemPreview.swift | 1 | 1284 | //
// UploadItemPreview.swift
// MT_iOS
//
// Created by CHEEBOW on 2016/02/26.
// Copyright © 2016年 Six Apart, Ltd. All rights reserved.
//
import UIKit
import SwiftyJSON
class UploadItemPreview: UploadItemPost {
override func upload(progress progress: ((Int64!, Int64!, Int64!) -> Void)? = nil, success: (JSON! -> Void)!, failure: (JSON! -> Void)!) {
let json = itemList.makeParams(true)
let isEntry = itemList.object is Entry
let blogID = itemList.blog.id
var id: String? = nil
if !itemList.object.id.isEmpty {
id = itemList.object.id
}
let api = DataAPI.sharedInstance
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let authInfo = app.authInfo
api.authenticationV2(authInfo.username, password: authInfo.password, remember: true,
success:{_ in
if isEntry {
api.previewEntry(siteID: blogID, entryID: id, entry: json, success: success, failure: failure)
} else {
api.previewPage(siteID: blogID, pageID: id, entry: json, success: success, failure: failure)
}
},
failure: failure
)
}
}
| mit | 68d5620a709f5e94ba615dc6f04bf585 | 31.846154 | 142 | 0.578454 | 4.342373 | false | false | false | false |
ShaneQi/SQITools | Sources/UIColor+Cooking.swift | 1 | 941 | //
// UIColor+Cooking.swift
// SQITools
//
// Created by Shane Qi on 3/22/17.
// Copyright © 2017 Shane Qi. All rights reserved.
//
import UIKit
import Cooking
extension UIColor: Edible {}
public extension Cooking where Ingredient: UIColor {
static func new(red: Int, green: Int, blue: Int, alpha: CGFloat = 1) -> Ingredient {
let newRed = CGFloat(red)/255
let newGreen = CGFloat(green)/255
let newBlue = CGFloat(blue)/255
return Ingredient.init(red: newRed, green: newGreen, blue: newBlue, alpha: alpha)
}
func pixel() -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, 0)
let context = UIGraphicsGetCurrentContext()!
context.saveGState()
context.setFillColor(ingredient.cgColor)
context.fill(CGRect(x: 0, y: 0, width: 1, height: 1 ))
context.restoreGState()
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
| apache-2.0 | cbf17704368f758311dc470cfc2f8747 | 25.111111 | 85 | 0.720213 | 3.533835 | false | false | false | false |
AdaptiveMe/adaptive-arp-api-lib-darwin | Pod/Classes/Sources.Api/ServiceResultCallbackImpl.swift | 1 | 3837 | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 . Unless required by appli-
-cable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing
permissions and limitations under the License.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:[email protected]>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:[email protected]>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
Interface for Managing the Services operations
Auto-generated implementation of IServiceResultCallback specification.
*/
public class ServiceResultCallbackImpl : BaseCallbackImpl, IServiceResultCallback {
/**
Constructor with callback id.
@param id The id of the callback.
*/
public override init(id : Int64) {
super.init(id: id)
}
/**
This method is called on Error
@param error returned by the platform
@since v2.0
*/
public func onError(error : IServiceResultCallbackError) {
let param0 : String = "Adaptive.IServiceResultCallbackError.toObject(JSON.parse(\"{ \\\"value\\\": \\\"\(error.toString())\\\"}\"))"
var callbackId : Int64 = -1
if (getId() != nil) {
callbackId = getId()!
}
AppRegistryBridge.sharedInstance.getPlatformContextWeb().executeJavaScript("Adaptive.handleServiceResultCallbackError( \(callbackId), \(param0))")
}
/**
This method is called on Result
@param response data
@since v2.0
*/
public func onResult(response : ServiceResponse) {
let param0 : String = "Adaptive.ServiceResponse.toObject(JSON.parse(\"\(JSONUtil.escapeString(ServiceResponse.Serializer.toJSON(response)))\"))"
var callbackId : Int64 = -1
if (getId() != nil) {
callbackId = getId()!
}
AppRegistryBridge.sharedInstance.getPlatformContextWeb().executeJavaScript("Adaptive.handleServiceResultCallbackResult( \(callbackId), \(param0))")
}
/**
This method is called on Warning
@param response data
@param warning returned by the platform
@since v2.0
*/
public func onWarning(response : ServiceResponse, warning : IServiceResultCallbackWarning) {
let param0 : String = "Adaptive.ServiceResponse.toObject(JSON.parse(\"\(JSONUtil.escapeString(ServiceResponse.Serializer.toJSON(response)))\"))"
let param1 : String = "Adaptive.IServiceResultCallbackWarning.toObject(JSON.parse(\"{ \\\"value\\\": \\\"\(warning.toString())\\\"}\"))"
var callbackId : Int64 = -1
if (getId() != nil) {
callbackId = getId()!
}
AppRegistryBridge.sharedInstance.getPlatformContextWeb().executeJavaScript("Adaptive.handleServiceResultCallbackWarning( \(callbackId), \(param0), \(param1))")
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
| apache-2.0 | 0efd49a8cead549914a0b2c1f8c4f58d | 36.598039 | 167 | 0.62086 | 4.7699 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.