repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
SaberVicky/LoveStory
|
LoveStory/Feature/Login/LSLoginAndRegisterViewController.swift
|
1
|
10358
|
//
// LSLoginViewController.swift
// LoveStory
//
// Created by songlong on 2016/12/27.
// Copyright © 2016年 com.Saber. All rights reserved.
//
import UIKit
import SnapKit
import SVProgressHUD
import HyphenateLite
class LSLoginAndRegisterViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var pageControl : UIPageControl!
var firstIcon: UIImageView!
var secondIcon: UIImageView!
var thirdIcon: UIImageView!
var forthIcon: UIImageView!
let dataList = [["top": "情侣专属", "bottom": "直属于你和你的另一半的私密空间"],
["top": "私密聊天", "bottom": "用最平凡的文字说出动人的语言"],
["top": "记录生活", "bottom": "记录你们日常生活中的每一个时刻"],
["top": "更多", "bottom": "快乐彼此,不再让你孤单"]]
let imgList = ["start-up-1", "start-up-2", "start-up-3", "start-up-4"]
var count = 0
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = UIScreen.main.bounds.size
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: UIScreen.main.bounds, collectionViewLayout: layout)
collectionView.isPagingEnabled = true
collectionView.backgroundColor = .clear
collectionView.delegate = self
collectionView.dataSource = self
collectionView.showsHorizontalScrollIndicator = false
collectionView.bounces = false
return collectionView
}()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if count == 0 {
if LSUser.isRegisteredNotPaired() {
let nav = CustionNavigationViewController(rootViewController: LSInviteViewController())
present(nav, animated: false, completion: nil)
count = count + 1
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
private func setupUI() {
view.backgroundColor = .lightGray
forthIcon = UIImageView(image: UIImage(named: imgList[3]))
forthIcon.frame = UIScreen.main.bounds
view.addSubview(forthIcon)
thirdIcon = UIImageView(image: UIImage(named: imgList[2]))
thirdIcon.frame = UIScreen.main.bounds
view.addSubview(thirdIcon)
secondIcon = UIImageView(image: UIImage(named: imgList[1]))
secondIcon.frame = UIScreen.main.bounds
view.addSubview(secondIcon)
firstIcon = UIImageView(image: UIImage(named: imgList[0]))
firstIcon.frame = UIScreen.main.bounds
view.addSubview(firstIcon)
let tempView = UIView(frame: UIScreen.main.bounds)
tempView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.2)
view.addSubview(tempView)
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "loginCell")
view.addSubview(collectionView)
pageControl = UIPageControl()
pageControl.currentPageIndicatorTintColor = .white
pageControl.pageIndicatorTintColor = .lightGray
pageControl.numberOfPages = dataList.count
view.addSubview(pageControl)
pageControl.snp.makeConstraints { (make) in
make.centerX.equalTo(view)
make.bottom.equalTo(-66)
}
let registerButton = UIButton()
registerButton.addTarget(self, action: #selector(clickRegister), for: .touchUpInside)
registerButton.setTitle("注册", for: .normal)
registerButton.setTitleColor(.white, for: .normal)
registerButton.backgroundColor = .green
registerButton.layer.cornerRadius = 5
registerButton.layer.masksToBounds = true
view.addSubview(registerButton)
registerButton.snp.makeConstraints { (make) in
make.centerX.equalTo(self.view).offset(-UIScreen.main.bounds.size.width / 4)
make.height.equalTo(50)
make.width.equalTo(self.view).multipliedBy(0.45)
make.bottom.equalTo(self.view).offset(-10)
}
let loginButton = UIButton()
loginButton.addTarget(self, action: #selector(clickLogin), for: .touchUpInside)
loginButton.setTitle("登录", for: .normal)
loginButton.setTitleColor(.lightGray, for: .normal)
loginButton.backgroundColor = .white
loginButton.layer.cornerRadius = 5
loginButton.layer.masksToBounds = true
view.addSubview(loginButton)
loginButton.snp.makeConstraints { (make) in
make.centerX.equalTo(self.view).offset(UIScreen.main.bounds.size.width / 4)
make.height.equalTo(50)
make.width.equalTo(self.view).multipliedBy(0.45)
make.bottom.equalTo(self.view).offset(-10)
}
}
func clickLogin() {
let vc = LSLoginViewController()
let nav = CustionNavigationViewController(rootViewController: vc)
self.present(nav, animated: true, completion: nil)
}
func clickRegister() {
let vc = LSRegisterViewController()
let nav = CustionNavigationViewController(rootViewController: vc)
self.present(nav, animated: true, completion: nil)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "loginCell", for: indexPath)
cell.backgroundColor = .clear
cell.contentView.backgroundColor = .clear
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let topLabel = UILabel()
topLabel.text = dataList[indexPath.item]["top"]
topLabel.textColor = .white
topLabel.font = UIFont.systemFont(ofSize: 14)
cell.contentView.addSubview(topLabel)
topLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(cell.contentView)
make.bottom.equalTo(-130)
}
let bottomLabel = UILabel()
bottomLabel.text = dataList[indexPath.item]["bottom"]
bottomLabel.textColor = .white
bottomLabel.font = UIFont.systemFont(ofSize: 13)
cell.contentView.addSubview(bottomLabel)
bottomLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(cell.contentView)
make.top.equalTo(topLabel.snp.bottom).offset(5)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
pageControl.currentPage = (collectionView.indexPathsForVisibleItems.first?.item)!
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
firstIcon.alpha = 1 - scrollView.contentOffset.x / LSWidth
secondIcon.alpha = 1 - abs(scrollView.contentOffset.x - 1 * LSWidth) / LSWidth
thirdIcon.alpha = 1 - abs(scrollView.contentOffset.x - 2 * LSWidth) / LSWidth
forthIcon.alpha = 1 - abs(scrollView.contentOffset.x - 3 * LSWidth) / LSWidth
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
// func toRegister() {
// view.endEditing(true)
//
// SVProgressHUD.show()
// LSNetworking.sharedInstance.request(method: .POST, URLString: API_REGISTER, parameters: ["user_account": accountTextField.text, "user_password" : passwordTextField.text], success: { (task, responseObject) in
// SVProgressHUD.dismiss()
//
// let dic = responseObject as! NSDictionary
// let ret : NSInteger = dic["ret"] as! NSInteger
// ret==1 ? SVProgressHUD.showSuccess(withStatus: "注册成功") : SVProgressHUD.showError(withStatus: "注册失败")
// if ret==1 {
// self.backToLogin()
// let error = EMClient.shared().register(withUsername: self.accountTextField.text, password: HuanXinPassword)
// if error == nil {
// LSPrint("注册环信成功")
// } else {
// LSPrint("注册环信失败")
// }
// }
//
// }, failure: { (task, error) in
// SVProgressHUD.dismiss()
// SVProgressHUD.showError(withStatus: "注册失败")
// })
// }
//
// func clickLogin() {
// view.endEditing(true)
//
// SVProgressHUD.show()
// LSNetworking.sharedInstance.request(method: .POST, URLString: API_LOGIN, parameters: ["user_account": accountTextField.text, "user_password" : passwordTextField.text], success: { (task, responseObject) in
// SVProgressHUD.dismiss()
//
// let dic = responseObject as! NSDictionary
// let ret : NSInteger = dic["ret"] as! NSInteger
// ret==1 ? SVProgressHUD.showSuccess(withStatus: "登录成功") : SVProgressHUD.showError(withStatus: "登录失败")
// if ret==1 {
// LSGlobal.setUserAccount(account: self.accountTextField.text)
// self.loginSuccess()
// }
//
// }, failure: { (task, error) in
// SVProgressHUD.dismiss()
// SVProgressHUD.showError(withStatus: "登录失败")
// })
// }
//
// func loginSuccess() {
//
// loginHuanXin()
//
// UIApplication.shared.keyWindow?.rootViewController = CustomTabBarViewController()
// }
//
// private func loginHuanXin() {
//
// let error = EMClient.shared().login(withUsername: accountTextField.text, password: HuanXinPassword)
// if error == nil {
// LSPrint("登录成功")
// EMClient.shared().setApnsNickname("张老师")
// } else {
// LSPrint("登录失败")
// }
// }
//}
|
mit
|
6219b6ecc5e4d3047b53dd45851d59e6
| 36.60223 | 217 | 0.62086 | 4.654855 | false | false | false | false |
liuguya/TestKitchen_1606
|
TestKitchen/Pods/Kingfisher/Sources/ImageDownloader.swift
|
5
|
21507
|
//
// ImageDownloader.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2016 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(OSX)
import AppKit
#else
import UIKit
#endif
/// Progress update block of downloader.
public typealias ImageDownloaderProgressBlock = DownloadProgressBlock
/// Completion block of downloader.
public typealias ImageDownloaderCompletionHandler = ((image: Image?, error: NSError?, imageURL: NSURL?, originalData: NSData?) -> ())
/// Download task.
public struct RetrieveImageDownloadTask {
let internalTask: NSURLSessionDataTask
/// Downloader by which this task is intialized.
public private(set) weak var ownerDownloader: ImageDownloader?
/**
Cancel this download task. It will trigger the completion handler with an NSURLErrorCancelled error.
*/
public func cancel() {
ownerDownloader?.cancelDownloadingTask(self)
}
/// The original request URL of this download task.
public var URL: NSURL? {
return internalTask.originalRequest?.URL
}
/// The relative priority of this download task.
/// It represents the `priority` property of the internal `NSURLSessionTask` of this download task.
/// The value for it is between 0.0~1.0. Default priority is value of 0.5.
/// See documentation on `priority` of `NSURLSessionTask` for more about it.
public var priority: Float {
get {
return internalTask.priority
}
set {
internalTask.priority = newValue
}
}
}
private let defaultDownloaderName = "default"
private let downloaderBarrierName = "com.onevcat.Kingfisher.ImageDownloader.Barrier."
private let imageProcessQueueName = "com.onevcat.Kingfisher.ImageDownloader.Process."
private let instance = ImageDownloader(name: defaultDownloaderName)
/**
The error code.
- BadData: The downloaded data is not an image or the data is corrupted.
- NotModified: The remote server responsed a 304 code. No image data downloaded.
- InvalidURL: The URL is invalid.
*/
public enum KingfisherError: Int {
case BadData = 10000
case NotModified = 10001
case InvalidURL = 20000
}
/// Protocol of `ImageDownloader`.
@objc public protocol ImageDownloaderDelegate {
/**
Called when the `ImageDownloader` object successfully downloaded an image from specified URL.
- parameter downloader: The `ImageDownloader` object finishes the downloading.
- parameter image: Downloaded image.
- parameter URL: URL of the original request URL.
- parameter response: The response object of the downloading process.
*/
optional func imageDownloader(downloader: ImageDownloader, didDownloadImage image: Image, forURL URL: NSURL, withResponse response: NSURLResponse)
}
/// Protocol indicates that an authentication challenge could be handled.
public protocol AuthenticationChallengeResponable: class {
/**
Called when an session level authentication challenge is received.
This method provide a chance to handle and response to the authentication challenge before downloading could start.
- parameter downloader: The downloader which receives this challenge.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call.
- Note: This method is a forward from `URLSession(:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `NSURLSessionDelegate`.
*/
func downloader(downloader: ImageDownloader, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)
}
extension AuthenticationChallengeResponable {
func downloader(downloader: ImageDownloader, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
if let trustedHosts = downloader.trustedHosts where trustedHosts.contains(challenge.protectionSpace.host) {
let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)
completionHandler(.UseCredential, credential)
return
}
}
completionHandler(.PerformDefaultHandling, nil)
}
}
/// `ImageDownloader` represents a downloading manager for requesting the image with a URL from server.
public class ImageDownloader: NSObject {
class ImageFetchLoad {
var callbacks = [CallbackPair]()
var responseData = NSMutableData()
var options: KingfisherOptionsInfo?
var downloadTaskCount = 0
var downloadTask: RetrieveImageDownloadTask?
}
// MARK: - Public property
/// This closure will be applied to the image download request before it being sent. You can modify the request for some customizing purpose, like adding auth token to the header or do a url mapping.
public var requestModifier: (NSMutableURLRequest -> Void)?
/// The duration before the download is timeout. Default is 15 seconds.
public var downloadTimeout: NSTimeInterval = 15.0
/// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this set will be ignored. You can use this set to specify the self-signed site. It only will be used if you don't specify the `authenticationChallengeResponder`. If `authenticationChallengeResponder` is set, this property will be ignored and the implemention of `authenticationChallengeResponder` will be used instead.
public var trustedHosts: Set<String>?
/// Use this to set supply a configuration for the downloader. By default, NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used. You could change the configuration before a downloaing task starts. A configuration without persistent storage for caches is requsted for downloader working correctly.
public var sessionConfiguration = NSURLSessionConfiguration.ephemeralSessionConfiguration() {
didSet {
session = NSURLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: NSOperationQueue.mainQueue())
}
}
/// Whether the download requests should use pipeling or not. Default is false.
public var requestsUsePipeling = false
private let sessionHandler: ImageDownloaderSessionHandler
private var session: NSURLSession?
/// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more.
public weak var delegate: ImageDownloaderDelegate?
/// A responder for authentication challenge.
/// Downloader will forward the received authentication challenge for the downloading session to this responder.
public weak var authenticationChallengeResponder: AuthenticationChallengeResponable?
// MARK: - Internal property
let barrierQueue: dispatch_queue_t
let processQueue: dispatch_queue_t
typealias CallbackPair = (progressBlock: ImageDownloaderProgressBlock?, completionHander: ImageDownloaderCompletionHandler?)
var fetchLoads = [NSURL: ImageFetchLoad]()
// MARK: - Public method
/// The default downloader.
public class var defaultDownloader: ImageDownloader {
return instance
}
/**
Init a downloader with name.
- parameter name: The name for the downloader. It should not be empty.
- returns: The downloader object.
*/
public init(name: String) {
if name.isEmpty {
fatalError("[Kingfisher] You should specify a name for the downloader. A downloader with empty name is not permitted.")
}
barrierQueue = dispatch_queue_create(downloaderBarrierName + name, DISPATCH_QUEUE_CONCURRENT)
processQueue = dispatch_queue_create(imageProcessQueueName + name, DISPATCH_QUEUE_CONCURRENT)
sessionHandler = ImageDownloaderSessionHandler()
super.init()
// Provide a default implement for challenge responder.
authenticationChallengeResponder = sessionHandler
session = NSURLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: NSOperationQueue.mainQueue())
}
func fetchLoadForKey(key: NSURL) -> ImageFetchLoad? {
var fetchLoad: ImageFetchLoad?
dispatch_sync(barrierQueue, { () -> Void in
fetchLoad = self.fetchLoads[key]
})
return fetchLoad
}
}
// MARK: - Download method
extension ImageDownloader {
/**
Download an image with a URL.
- parameter URL: Target URL.
- parameter progressBlock: Called when the download progress updated.
- parameter completionHandler: Called when the download progress finishes.
- returns: A downloading task. You could call `cancel` on it to stop the downloading process.
*/
public func downloadImageWithURL(URL: NSURL,
progressBlock: ImageDownloaderProgressBlock?,
completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask?
{
return downloadImageWithURL(URL, options: nil, progressBlock: progressBlock, completionHandler: completionHandler)
}
/**
Download an image with a URL and option.
- parameter URL: Target URL.
- parameter options: The options could control download behavior. See `KingfisherOptionsInfo`.
- parameter progressBlock: Called when the download progress updated.
- parameter completionHandler: Called when the download progress finishes.
- returns: A downloading task. You could call `cancel` on it to stop the downloading process.
*/
public func downloadImageWithURL(URL: NSURL,
options: KingfisherOptionsInfo?,
progressBlock: ImageDownloaderProgressBlock?,
completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask?
{
return downloadImageWithURL(URL,
retrieveImageTask: nil,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
internal func downloadImageWithURL(URL: NSURL,
retrieveImageTask: RetrieveImageTask?,
options: KingfisherOptionsInfo?,
progressBlock: ImageDownloaderProgressBlock?,
completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask?
{
if let retrieveImageTask = retrieveImageTask where retrieveImageTask.cancelledBeforeDownloadStarting {
return nil
}
let timeout = self.downloadTimeout == 0.0 ? 15.0 : self.downloadTimeout
// We need to set the URL as the load key. So before setup progress, we need to ask the `requestModifier` for a final URL.
let request = NSMutableURLRequest(URL: URL, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: timeout)
request.HTTPShouldUsePipelining = requestsUsePipeling
self.requestModifier?(request)
// There is a possiblility that request modifier changed the url to `nil` or empty.
if request.URL == nil || request.URL!.absoluteString.isEmpty {
completionHandler?(image: nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.InvalidURL.rawValue, userInfo: nil), imageURL: nil, originalData: nil)
return nil
}
var downloadTask: RetrieveImageDownloadTask?
setupProgressBlock(progressBlock, completionHandler: completionHandler, forURL: request.URL!) {(session, fetchLoad) -> Void in
if fetchLoad.downloadTask == nil {
let dataTask = session.dataTaskWithRequest(request)
fetchLoad.downloadTask = RetrieveImageDownloadTask(internalTask: dataTask, ownerDownloader: self)
fetchLoad.options = options
dataTask.priority = options?.downloadPriority ?? NSURLSessionTaskPriorityDefault
dataTask.resume()
// Hold self while the task is executing.
self.sessionHandler.downloadHolder = self
}
fetchLoad.downloadTaskCount += 1
downloadTask = fetchLoad.downloadTask
retrieveImageTask?.downloadTask = downloadTask
}
return downloadTask
}
// A single key may have multiple callbacks. Only download once.
internal func setupProgressBlock(progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?, forURL URL: NSURL, started: ((NSURLSession, ImageFetchLoad) -> Void)) {
dispatch_barrier_sync(barrierQueue, { () -> Void in
let loadObjectForURL = self.fetchLoads[URL] ?? ImageFetchLoad()
let callbackPair = (progressBlock: progressBlock, completionHander: completionHandler)
loadObjectForURL.callbacks.append(callbackPair)
self.fetchLoads[URL] = loadObjectForURL
if let session = self.session {
started(session, loadObjectForURL)
}
})
}
func cancelDownloadingTask(task: RetrieveImageDownloadTask) {
dispatch_barrier_sync(barrierQueue) { () -> Void in
if let URL = task.internalTask.originalRequest?.URL, imageFetchLoad = self.fetchLoads[URL] {
imageFetchLoad.downloadTaskCount -= 1
if imageFetchLoad.downloadTaskCount == 0 {
task.internalTask.cancel()
}
}
}
}
func cleanForURL(URL: NSURL) {
dispatch_barrier_sync(barrierQueue, { () -> Void in
self.fetchLoads.removeValueForKey(URL)
return
})
}
}
// MARK: - NSURLSessionDataDelegate
// See https://github.com/onevcat/Kingfisher/issues/235
/// Delegate class for `NSURLSessionTaskDelegate`.
/// The session object will hold its delegate until it gets invalidated.
/// If we use `ImageDownloader` as the session delegate, it will not be released.
/// So we need an additional handler to break the retain cycle.
class ImageDownloaderSessionHandler: NSObject, NSURLSessionDataDelegate, AuthenticationChallengeResponable {
// The holder will keep downloader not released while a data task is being executed.
// It will be set when the task started, and reset when the task finished.
var downloadHolder: ImageDownloader?
/**
This method is exposed since the compiler requests. Do not call it.
*/
internal func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
completionHandler(NSURLSessionResponseDisposition.Allow)
}
/**
This method is exposed since the compiler requests. Do not call it.
*/
internal func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
guard let downloader = downloadHolder else {
return
}
if let URL = dataTask.originalRequest?.URL, fetchLoad = downloader.fetchLoadForKey(URL) {
fetchLoad.responseData.appendData(data)
for callbackPair in fetchLoad.callbacks {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
callbackPair.progressBlock?(receivedSize: Int64(fetchLoad.responseData.length), totalSize: dataTask.response!.expectedContentLength)
})
}
}
}
/**
This method is exposed since the compiler requests. Do not call it.
*/
internal func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let URL = task.originalRequest?.URL {
if let error = error { // Error happened
callbackWithImage(nil, error: error, imageURL: URL, originalData: nil)
} else { //Download finished without error
processImageForTask(task, URL: URL)
}
}
}
/**
This method is exposed since the compiler requests. Do not call it.
*/
internal func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
guard let downloader = downloadHolder else {
return
}
downloader.authenticationChallengeResponder?.downloader(downloader, didReceiveChallenge: challenge, completionHandler: completionHandler)
}
private func callbackWithImage(image: Image?, error: NSError?, imageURL: NSURL, originalData: NSData?) {
guard let downloader = downloadHolder else {
return
}
if let callbackPairs = downloader.fetchLoadForKey(imageURL)?.callbacks {
let options = downloader.fetchLoadForKey(imageURL)?.options ?? KingfisherEmptyOptionsInfo
downloader.cleanForURL(imageURL)
for callbackPair in callbackPairs {
dispatch_async_safely_to_queue(options.callbackDispatchQueue, { () -> Void in
callbackPair.completionHander?(image: image, error: error, imageURL: imageURL, originalData: originalData)
})
}
if downloader.fetchLoads.isEmpty {
downloadHolder = nil
}
}
}
private func processImageForTask(task: NSURLSessionTask, URL: NSURL) {
guard let downloader = downloadHolder else {
return
}
// We are on main queue when receiving this.
dispatch_async(downloader.processQueue, { () -> Void in
if let fetchLoad = downloader.fetchLoadForKey(URL) {
let options = fetchLoad.options ?? KingfisherEmptyOptionsInfo
if let image = Image.kf_imageWithData(fetchLoad.responseData, scale: options.scaleFactor, preloadAllGIFData: options.preloadAllGIFData) {
downloader.delegate?.imageDownloader?(downloader, didDownloadImage: image, forURL: URL, withResponse: task.response!)
if options.backgroundDecode {
self.callbackWithImage(image.kf_decodedImage(scale: options.scaleFactor), error: nil, imageURL: URL, originalData: fetchLoad.responseData)
} else {
self.callbackWithImage(image, error: nil, imageURL: URL, originalData: fetchLoad.responseData)
}
} else {
// If server response is 304 (Not Modified), inform the callback handler with NotModified error.
// It should be handled to get an image from cache, which is response of a manager object.
if let res = task.response as? NSHTTPURLResponse where res.statusCode == 304 {
self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.NotModified.rawValue, userInfo: nil), imageURL: URL, originalData: nil)
return
}
self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.BadData.rawValue, userInfo: nil), imageURL: URL, originalData: nil)
}
} else {
self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.BadData.rawValue, userInfo: nil), imageURL: URL, originalData: nil)
}
})
}
}
|
mit
|
4d1f9bb74c792e3993aab316bcb007d5
| 44.08805 | 429 | 0.674013 | 5.719947 | false | false | false | false |
alexth/CDVDictionary
|
Dictionary/DictionaryTests/Utils/PlistReaderUtilsTests.swift
|
1
|
1016
|
//
// PlistReaderUtilsTests.swift
// Dictionary
//
// Created by Alex Golub on 9/27/16.
// Copyright © 2016 Alex Golub. All rights reserved.
//
import XCTest
@testable import Dictionary
class PlistReaderUtilsTests: XCTestCase {
private var sut: PlistReaderUtils!
override func setUp() {
super.setUp()
sut = PlistReaderUtils()
}
override func tearDown() {
sut = nil
super.tearDown()
}
func testReadingPlist() {
let result = sut.read("DICT_R-S")
let sourceArrayCount = result?.sourceArray.count
let displayDictionaryCount = result?.displayDictionary.count
XCTAssertNotNil(result, "should have result after reading plist")
XCTAssertTrue(sourceArrayCount! > 0, "source array should not be empty")
XCTAssertTrue(displayDictionaryCount! > 0, "display dictionary should not be empty")
XCTAssertEqual(sourceArrayCount, displayDictionaryCount, "collections should have equal number of items")
}
}
|
mit
|
298644c95b840c7df050e91d74191207
| 27.194444 | 113 | 0.682759 | 4.49115 | false | true | false | false |
oleander/bitbar
|
Tests/PluginTests/IntervalTests.swift
|
1
|
11097
|
import Quick
import Nimble
import Async
import PathKit
@testable import Plugin
@testable import SharedTests
class IntervalTests: QuickSpec {
override func spec() {
var plugin: IntervalHost!
var output: [IntervalHost.Event]!
describe("no arguments") {
beforeEach {
output = [.stdout("A\nB\n")]
plugin = IntervalHost()
}
describe("start") {
it("starts") {
plugin.start()
after(3) {
expect(plugin.events).to(equal(output))
}
}
it("only reports once on multiply starts") {
after(2) {
plugin.start()
}
after(3) {
expect(plugin.events).to(equal(output + output))
}
}
it("does autostart") {
expect(plugin.events).toEventually(equal(output))
}
it("aborts when deallocated") {
plugin.deallocate()
after(2) {
expect(plugin.events).to(beEmpty())
}
}
}
describe("stop") {
it("stops") {
plugin.stop()
after(3) {
expect(plugin.events).to(beEmpty())
}
}
it("does nothing on multiply stops") {
plugin.stop()
plugin.stop()
after(2) {
expect(plugin.events).to(beEmpty())
}
}
it("aborts when deallocated") {
plugin.stop()
plugin.deallocate()
after(2) {
expect(plugin.events).to(beEmpty())
}
}
}
describe("invoke") {
it("invokes") {
after(2) {
plugin.invoke(["1", "2"])
}
after(4) {
expect(plugin.events).to(equal([
.stdout("A\nB\n"),
.stdout("1\n2\n")
]))
}
}
describe("restart") {
it("does persit arguments on restart") {
after(1) {
plugin.invoke(["1", "2"])
}
after(3) {
plugin.restart()
}
after(4) {
expect(plugin.events).to(equal([
.stdout("A\nB\n"),
.stdout("1\n2\n"),
.stdout("1\n2\n")
]))
}
}
}
describe("stop") {
it("aborts on stop") {
after(1) {
plugin.invoke(["1", "2"])
}
after(3) {
plugin.stop()
}
after(4) {
expect(plugin.events).to(equal([
.stdout("A\nB\n"),
.stdout("1\n2\n")
]))
}
}
}
describe("start") {
it("aborts on start") {
after(1) {
plugin.invoke(["1", "2"])
}
after(2) {
plugin.start()
}
after(4) {
expect(plugin.events).to(equal([
.stdout("A\nB\n"),
.stdout("1\n2\n"),
.stdout("1\n2\n")
]))
}
}
}
}
describe("restart") {
it("restart") {
plugin.restart()
after(3) {
expect(plugin.events).to(equal([.stdout("A\nB\n")]))
}
}
it("only reports once on multiply restarts") {
after(1) {
plugin.restart()
plugin.restart()
}
after(3) {
expect(plugin.events).to(equal([.stdout("A\nB\n"), .stdout("A\nB\n")]))
}
}
it("aborts when deallocated") {
after(1) {
plugin.restart()
plugin.deallocate()
}
after(3) {
expect(plugin.events).to(equal([.stdout("A\nB\n")]))
}
}
}
}
describe("arguments") {
beforeEach {
output = [.stdout("X\nY\n")]
plugin = IntervalHost(args: ["X", "Y"])
}
describe("start") {
it("starts") {
plugin.start()
after(3) {
expect(plugin.events).to(equal(output))
}
}
it("only reports once on multiply starts") {
after(2) {
plugin.start()
plugin.start()
}
after(4) {
expect(plugin.events).to(equal(output + output))
}
}
it("does autostart") {
expect(plugin.events).toEventually(equal(output))
}
it("aborts when deallocated") {
after(1) {
plugin.start()
plugin.deallocate()
}
after(3) {
expect(plugin.events).to(equal(output))
}
}
}
describe("stop") {
it("stops") {
plugin.stop()
after(3) {
expect(plugin.events).to(beEmpty())
}
}
it("does nothing on multiply stops") {
after(1) {
plugin.stop()
plugin.stop()
}
after(3) {
expect(plugin.events).to(equal(output))
}
}
it("aborts when deallocated") {
plugin.stop()
after(0.5) {
plugin.deallocate()
}
after(3) {
expect(plugin.events).to(beEmpty())
}
}
}
describe("invoke") {
it("invokes") {
plugin.invoke(["1", "2"])
after(3) {
expect(plugin.events).to(equal([.stdout("1\n2\n")]))
}
}
describe("restart") {
it("does not persit arguments on restart") {
after(1) {
plugin.invoke(["1", "2"])
}
after(2) {
plugin.restart()
}
after(4) {
expect(plugin.events).to(equal(output + [.stdout("1\n2\n"), .stdout("1\n2\n")]))
}
}
}
describe("stop") {
it("aborts on stop") {
after(1) {
plugin.invoke(["1", "2"])
plugin.stop()
}
after(3) {
expect(plugin.events).to(equal(output))
}
}
}
describe("start") {
it("aborts on start") {
after(1) {
plugin.invoke(["1", "2"])
plugin.start()
}
after(3) {
expect(plugin.events).to(equal(output + [.stdout("1\n2\n")]))
}
}
}
}
describe("restart") {
it("restart") {
plugin.restart()
after(3) {
expect(plugin.events).to(equal(output))
}
}
it("only reports once on multiply restarts") {
after(1) {
plugin.restart()
plugin.restart()
}
after(3) {
expect(plugin.events).to(equal(output + output))
}
}
it("aborts when deallocated") {
after(1) {
plugin.restart()
plugin.deallocate()
}
after(3) {
expect(plugin.events).to(equal(output))
}
}
}
}
describe("env") {
beforeEach {
output = [.stdout("P\nQ\n")]
plugin = IntervalHost(env: ["ENV1": "P", "ENV2": "Q"])
}
describe("start") {
it("starts") {
after(1) {
plugin.start()
}
after(3) {
expect(plugin.events).to(equal(output + output))
}
}
it("only reports once on multiply starts") {
after(1) {
plugin.start()
plugin.start()
}
after(3) {
expect(plugin.events).to(equal(output + output))
}
}
it("does autostart") {
expect(plugin.events).toEventually(equal(output))
}
it("aborts when deallocated") {
after(1) {
plugin.start()
plugin.deallocate()
}
after(3) {
expect(plugin.events).to(equal(output))
}
}
}
describe("stop") {
it("stops") {
plugin.stop()
after(3) {
expect(plugin.events).to(beEmpty())
}
}
it("does nothing on multiply stops") {
after(1) {
plugin.stop()
plugin.stop()
}
after(3) {
expect(plugin.events).to(equal(output))
}
}
it("aborts when deallocated") {
plugin.stop()
after(0.5) {
plugin.deallocate()
}
after(3) {
expect(plugin.events).to(beEmpty())
}
}
}
describe("invoke") {
it("invokes") {
after(1) {
plugin.invoke(["1", "2"])
}
after(3) {
expect(plugin.events).to(equal(output + [.stdout("1\n2\n")]))
}
}
describe("restart") {
it("does not persit arguments on restart") {
after(1) {
plugin.invoke(["1", "2"])
plugin.restart()
}
after(3) {
expect(plugin.events).to(equal(output + [.stdout("1\n2\n")]))
}
}
}
describe("stop") {
it("aborts on stop") {
after(0.5) {
plugin.invoke(["1", "2"])
plugin.stop()
}
after(3) {
expect(plugin.events).to(equal(output))
}
}
}
describe("start") {
it("aborts on start") {
after(1) {
plugin.invoke(["1", "2"])
plugin.start()
}
after(3) {
expect(plugin.events).to(equal(output + [.stdout("1\n2\n")]))
}
}
}
}
describe("restart") {
it("restart") {
after(1) {
plugin.restart()
}
after(3) {
expect(plugin.events).to(equal(output + output))
}
}
it("only reports once on multiply restarts") {
after(1) {
plugin.restart()
plugin.restart()
}
after(3) {
expect(plugin.events).to(equal(output + output))
}
}
it("aborts when deallocated") {
after(1) {
plugin.restart()
plugin.deallocate()
}
after(3) {
expect(plugin.events).to(equal(output))
}
}
}
}
describe("error") {
beforeEach {
plugin = IntervalHost(path: .streamError)
}
xit("should output stderr and stdout") {
expect(plugin.events).toEventually(contain(.stderr("ERROR")))
expect(plugin.events).toEventually(contain(.stdout("A\n")))
expect(plugin.events).toEventually(contain(.stdout("B\n")))
}
}
}
}
|
mit
|
514d9336b44775ca7cbb397da49e7640
| 20.547573 | 94 | 0.400198 | 4.312864 | false | false | false | false |
yuezaixz/UPillow
|
Pods/iOSDFULibrary/iOSDFULibrary/Classes/Implementation/SecureDFU/Characteristics/SecureDFUPacket.swift
|
1
|
8886
|
/*
* Copyright (c) 2016, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import CoreBluetooth
internal class SecureDFUPacket {
static fileprivate let UUID = CBUUID(string: "8EC90002-F315-4F60-9FB8-838830DAEA50")
static func matches(_ characteristic: CBCharacteristic) -> Bool {
return characteristic.uuid.isEqual(UUID)
}
private let packetSize: UInt32
private var characteristic: CBCharacteristic
private var logger: LoggerHelper
/// Number of bytes of firmware already sent.
private(set) var bytesSent: UInt32 = 0
/// Number of bytes sent at the last progress notification. This value is used to calculate the current speed.
private var totalBytesSentSinceProgessNotification: UInt32 = 0
private var totalBytesSentWhenDfuStarted: UInt32 = 0
/// Current progress in percents (0-99).
private var progress: UInt8 = 0
private var startTime: CFAbsoluteTime?
private var lastTime: CFAbsoluteTime?
internal var valid: Bool {
return characteristic.properties.contains(.writeWithoutResponse)
}
init(_ characteristic: CBCharacteristic, _ logger: LoggerHelper) {
self.characteristic = characteristic
self.logger = logger
if #available(iOS 9.0, macOS 10.12, *) {
packetSize = UInt32(characteristic.service.peripheral.maximumWriteValueLength(for: .withoutResponse))
if packetSize > 20 {
logger.v("MTU set to \(packetSize + 3)") // MTU is 3 bytes larger than payload (1 octet for Op-Code and 2 octets for Att Handle)
}
} else {
packetSize = 20 // Default MTU is 23
}
}
// MARK: - Characteristic API methods
/**
Sends the whole content of the data object.
- parameter data: the data to be sent
*/
func sendInitPacket(_ data: Data){
// Get the peripheral object
let peripheral = characteristic.service.peripheral
// Data may be sent in up-to-20-bytes packets
var offset: UInt32 = 0
var bytesToSend = UInt32(data.count)
repeat {
let packetLength = min(bytesToSend, packetSize)
let packet = data.subdata(in: Int(offset) ..< Int(offset + packetLength))
logger.v("Writing to characteristic \(characteristic.uuid.uuidString)...")
logger.d("peripheral.writeValue(0x\(packet.hexString), for: \(characteristic.uuid.uuidString), type: .withoutResponse)")
peripheral.writeValue(packet, for: characteristic, type: .withoutResponse)
offset += packetLength
bytesToSend -= packetLength
} while bytesToSend > 0
}
/**
Sends a given range of data from given firmware over DFU Packet characteristic. If the whole object is
completed the completition callback will be called.
*/
func sendNext(_ aPRNValue: UInt16, packetsFrom aRange: Range<Int>, of aFirmware: DFUFirmware,
andReportProgressTo aProgressDelegate: DFUProgressDelegate?, andCompletionTo aCompletion: @escaping Callback) {
let peripheral = characteristic.service.peripheral
let objectData = aFirmware.data.subdata(in: aRange)
let objectSizeInBytes = UInt32(objectData.count)
let objectSizeInPackets = (objectSizeInBytes + packetSize - 1) / packetSize
let packetsSent = (bytesSent + packetSize - 1) / packetSize
let packetsLeft = objectSizeInPackets - packetsSent
// Calculate how many packets should be sent before EOF or next receipt notification
var packetsToSendNow = min(UInt32(aPRNValue), packetsLeft)
if aPRNValue == 0 {
packetsToSendNow = objectSizeInPackets
}
// This is called when we no longer have data to send (PRN received after the whole object was sent)
// Fixes issue IDFU-9
if packetsToSendNow == 0 {
aCompletion()
return
}
// Initialize timers
if startTime == nil {
startTime = CFAbsoluteTimeGetCurrent()
lastTime = startTime
totalBytesSentWhenDfuStarted = UInt32(aRange.lowerBound)
totalBytesSentSinceProgessNotification = totalBytesSentWhenDfuStarted
// Notify progress delegate that upload has started (0%)
DispatchQueue.main.async(execute: {
aProgressDelegate?.dfuProgressDidChange(
for: aFirmware.currentPart,
outOf: aFirmware.parts,
to: 0,
currentSpeedBytesPerSecond: 0.0,
avgSpeedBytesPerSecond: 0.0)
})
}
let originalPacketsToSendNow = packetsToSendNow
while packetsToSendNow > 0 {
let bytesLeft = objectSizeInBytes - bytesSent
let packetLength = min(bytesLeft, packetSize)
let packet = objectData.subdata(in: Int(bytesSent) ..< Int(packetLength + bytesSent))
peripheral.writeValue(packet, for: characteristic, type: .withoutResponse)
bytesSent += packetLength
packetsToSendNow -= 1
// Calculate the total progress of the firmware, presented to the delegate
let totalBytesSent = UInt32(aRange.lowerBound) + bytesSent
let totalProgress = UInt8(totalBytesSent * 100 / UInt32(aFirmware.data.count))
// Notify progress listener only if current progress has increased since last time
if totalProgress > progress {
// Calculate current transfer speed in bytes per second
let now = CFAbsoluteTimeGetCurrent()
let currentSpeed = Double(totalBytesSent - totalBytesSentSinceProgessNotification) / (now - lastTime!)
let avgSpeed = Double(totalBytesSent - totalBytesSentWhenDfuStarted) / (now - startTime!)
lastTime = now
totalBytesSentSinceProgessNotification = totalBytesSent
// Notify progress delegate of overall progress
DispatchQueue.main.async(execute: {
aProgressDelegate?.dfuProgressDidChange(
for: aFirmware.currentPart,
outOf: aFirmware.parts,
to: Int(totalProgress),
currentSpeedBytesPerSecond: currentSpeed,
avgSpeedBytesPerSecond: avgSpeed)
})
progress = totalProgress
}
// Notify handler of current object progress to start sending next one
if bytesSent == objectSizeInBytes {
if aPRNValue == 0 || originalPacketsToSendNow < UInt32(aPRNValue) {
aCompletion()
} else {
// The whole object has been sent but the DFU target will
// send a PRN notification as expected.
// The sendData method will be called again
// with packetsLeft = 0 (see line 112)
// Do nothing
}
}
}
}
func resetCounters() {
bytesSent = 0
}
}
|
gpl-3.0
|
552ea548f66d50e29b83ff634965f19d
| 45.041451 | 144 | 0.634481 | 5.298748 | false | false | false | false |
jeffcollier/FirebaseSwiftExample
|
FirebaseSwiftExample/AppDelegate.swift
|
1
|
3346
|
//
// AppDelegate.swift
// FirebaseSwiftExample
//
// Created by Collier, Jeff on 12/18/16.
// Copyright © 2016 Collierosity, LLC. All rights reserved.
//
import AdSupport
import Firebase
import FirebaseAnalytics
import FirebaseAuth
import FirebaseFirestore
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
// TODO: Make buttons (shapes and transparent) dynamically adjust for Accessibility just like labels (which have IB property)
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Initialize Firebase
FirebaseApp.configure()
// Initialize Cloud Firestore
/* None of this is necessary because offlien persistence is enabled by default
let settings = FirestoreSettings()
settings.isPersistenceEnabled = true
let db = Firestore.firestore()
db.settings = settings */
// If the user has disabled advertising tracking, configure Firebase Analytics to not use the iOS AdSupport for data such as age and demographic
if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
let idfa = ASIdentifierManager.shared().advertisingIdentifier // ?? UUID() With the left side no longer optional, this is not required
print("Firebase Analytics will include demographic data as the user has not disabled advertising tracking. IDFA=\(idfa)")
} else {
AnalyticsConfiguration.shared().setAnalyticsCollectionEnabled(false)
}
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 invalidate graphics rendering callbacks. 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 active 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
|
27bf515e2fcbe91e07c99c3eed4e147c
| 46.785714 | 285 | 0.736622 | 5.631313 | false | false | false | false |
kzin/swift-design-patterns
|
Design Patterns.playground/Pages/Template Method.xcplaygroundpage/Contents.swift
|
1
|
1407
|
protocol Beverage {
var customerWantsCondiments: Bool { get }
func prepareRecipe()
func boilWater()
func brew()
func pourInCup()
func addCondiments()
}
extension Beverage {
func prepareRecipe() {
boilWater()
brew()
pourInCup()
if customerWantsCondiments {
addCondiments()
}
}
func boilWater() {
print("Boiling water")
}
func pourInCup() {
print("Pouring into cup")
}
}
class Tea: Beverage {
var condiments: Bool = false
var customerWantsCondiments: Bool {
get {
return condiments
}
}
init(wantCondiment: Bool) {
condiments = wantCondiment
}
func brew() {
print("Steeping the tea")
}
func addCondiments() {
print("Adding Lemon")
}
}
class Coffee: Beverage {
var condiments: Bool = false
var customerWantsCondiments: Bool {
get {
return condiments
}
}
init(wantCondiment: Bool) {
condiments = wantCondiment
}
func brew() {
print("Dripping coffee through filter")
}
func addCondiments() {
print("Adding sugar and milk")
}
}
let tea = Tea(wantCondiment: true)
tea.prepareRecipe()
let coffee = Coffee(wantCondiment: false)
coffee.prepareRecipe()
|
mit
|
179d11ad1869ec4d7cd423909ded7b15
| 16.5875 | 47 | 0.548685 | 4.263636 | false | false | false | false |
IsaScience/ListerAProductivityAppObj-CandSwift
|
original-src/ListerAProductivityAppObj-CandSwift/Swift/ListerTodayOSX/TodayViewController.swift
|
1
|
5589
|
/*
Copyright (C) 2014 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `TodayViewController` class handles display of the Today view. It leverages iCloud for seamless interaction between devices.
*/
import Cocoa
import NotificationCenter
import ListerKitOSX
class TodayViewController: NSViewController, NCWidgetProviding, NCWidgetListViewDelegate, ListRowViewControllerDelegate, ListDocumentDelegate {
// MARK: Properties
@IBOutlet var listViewController: NCWidgetListViewController!
var document: ListDocument!
var list: List {
return document.list
}
// Override the nib name to make sure that the view controller opens the correct nib.
override var nibName: String {
return "TodayViewController"
}
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
updateWidgetContents()
}
override func viewWillAppear() {
super.viewWillAppear()
listViewController.delegate = self
listViewController.hasDividerLines = false
listViewController.contents = []
updateWidgetContents()
}
// MARK: NCWidgetProviding
func widgetPerformUpdateWithCompletionHandler(completionHandler: NCUpdateResult -> Void) {
updateWidgetContents(completionHandler)
}
func widgetMarginInsetsForProposedMarginInsets(defaultMarginInset: NSEdgeInsets) -> NSEdgeInsets {
return NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
func widgetAllowsEditing() -> Bool {
return false
}
// MARK: NCWidgetListViewDelegate
func widgetList(_: NCWidgetListViewController, viewControllerForRow row: Int) -> NSViewController {
let representedObjectForRow: AnyObject = listViewController.contents[row]
// First check to see if it's a straightforward row to return a view controller for.
if let todayWidgetRowPurpose = representedObjectForRow as? TodayWidgetRowPurposeBox {
switch todayWidgetRowPurpose.purpose {
case .OpenLister: return OpenListerRowViewController()
case .NoItemsInList: return NoItemsRowViewController()
case .RequiresCloud: return TodayWidgetRequiresCloudViewController()
}
}
let listRowViewController = ListRowViewController()
listRowViewController.representedObject = representedObjectForRow
listRowViewController.delegate = self
return listRowViewController
}
// MARK: ListRowViewControllerDelegate
func listRowViewControllerDidChangeRepresentedObjectState(listRowViewController: ListRowViewController) {
let indexOfListRowViewController = listViewController.rowForViewController(listRowViewController)
let item = list[indexOfListRowViewController - 1]
list.toggleItem(item)
document.updateChangeCount(.ChangeDone)
// Make sure the rows are reordered appropriately.
listViewController.contents = listRowRepresentedObjectsForList(list)
}
// MARK: ListDocumentDelegate
func listDocumentDidChangeContents(document: ListDocument) {
listViewController.contents = listRowRepresentedObjectsForList(list)
}
// MARK: Convenience
func listRowRepresentedObjectsForList(aList: List) -> [AnyObject] {
var representedObjects = [AnyObject]()
let listColor = list.color.colorValue
// The "Open in Lister" has a representedObject as an NSColor, representing the text color.
representedObjects += [TodayWidgetRowPurposeBox(purpose: .OpenLister, userInfo: listColor)]
for item in aList.items {
representedObjects += [ListRowRepresentedObject(item: item, color: listColor)]
}
// Add a sentinel NSNull value to represent the "No Items" represented object.
if list.isEmpty {
// No items in the list.
representedObjects += [TodayWidgetRowPurposeBox(purpose: .NoItemsInList)]
}
return representedObjects
}
func updateWidgetContents(completionHandler: (NCUpdateResult -> Void)? = nil) {
TodayListManager.fetchTodayDocumentURLWithCompletionHandler { todayDocumentURL in
dispatch_async(dispatch_get_main_queue()) {
if todayDocumentURL == nil {
self.listViewController.contents = [TodayWidgetRowPurposeBox(purpose: .RequiresCloud)]
completionHandler?(.Failed)
return
}
var error: NSError?
let newDocument = ListDocument(contentsOfURL: todayDocumentURL!, makesCustomWindowControllers: false, error: &error)
if error != nil {
completionHandler?(.Failed)
}
else {
if self.document != nil && self.list == newDocument.list {
completionHandler?(.NoData)
}
else {
self.document = newDocument
self.document.delegate = self
self.listViewController.contents = self.listRowRepresentedObjectsForList(newDocument.list)
completionHandler?(.NewData)
}
}
}
}
}
}
|
apache-2.0
|
bcae88bb6ad84372ca79e0289cbece50
| 33.487654 | 144 | 0.64131 | 5.862539 | false | false | false | false |
mapzen/ios
|
MapzenSDK/MapzenManager.swift
|
1
|
1685
|
//
// MapzenManager.swift
// ios-sdk
//
// Created by Matt Smollinger on 1/12/17.
// Copyright © 2017 Mapzen. All rights reserved.
//
import Foundation
import Pelias
import OnTheRoad
protocol MapzenManagerProtocol {
var apiKey: String? { set get }
}
/**
`MapzenManager` is a singleton object used for managing state between the various dependencies. Right now, it only manages the API key system.
*/
open class MapzenManager: NSObject, MapzenManagerProtocol {
/// The single object to be used for all access
open static let sharedManager = MapzenManager()
static let SDK_VERSION_KEY = "sdk_version"
/// The Mapzen API key. If this is not set, exceptions will get raised by the various objects in use.
dynamic open var apiKey: String?
fileprivate override init(){
super.init()
}
//MARK: - Http Headers
func httpHeaders() -> [String:String] {
var headers = [String:String]()
headers["User-Agent"] = buildUserAgent()
return headers
}
fileprivate func buildUserAgent() -> String {
let systemVersion = UIDevice.current.systemVersion
var sdkVersion = "0"
//Now for the fun - we grab the current bundle
let bundle = Bundle(for: MapzenManager.self)
// Assuming cocoapods did its thing and ran setup_version.swift, there will be a version.plist in our bundle
if let pathForVersionPlist = bundle.path(forResource: "version", ofType: "plist") {
if let versionDict = NSDictionary(contentsOfFile: pathForVersionPlist) {
if let version = versionDict[MapzenManager.SDK_VERSION_KEY] {
sdkVersion = version as! String
}
}
}
return "ios-sdk;\(sdkVersion),\(systemVersion)"
}
}
|
apache-2.0
|
e79daac5e7b9c36443b9ab48193f80f7
| 30.185185 | 143 | 0.699525 | 4.067633 | false | false | false | false |
jum/Charts
|
Tests/Charts/PieChartTests.swift
|
1
|
2478
|
import XCTest
import FBSnapshotTestCase
@testable import Charts
class PieChartTests: FBSnapshotTestCase
{
var chart: PieChartView!
var dataSet: PieChartDataSet!
override func setUp()
{
super.setUp()
// Set to `true` to re-capture all snapshots
self.recordMode = false
// Sample data
let values: [Double] = [11, 33, 81, 52, 97, 101, 75]
var entries: [PieChartDataEntry] = Array()
for value in values
{
entries.append(PieChartDataEntry(value: value, icon: UIImage(named: "icon", in: Bundle(for: self.classForCoder), compatibleWith: nil)))
}
dataSet = PieChartDataSet(entries: entries, label: "First unit test data")
dataSet.drawIconsEnabled = false
dataSet.iconsOffset = CGPoint(x: 0, y: 20.0)
dataSet.colors = ChartColorTemplates.vordiplom()
+ ChartColorTemplates.joyful()
+ ChartColorTemplates.colorful()
+ ChartColorTemplates.liberty()
+ ChartColorTemplates.pastel()
+ [UIColor(red: 51/255, green: 181/255, blue: 229/255, alpha: 1)]
chart = PieChartView(frame: CGRect(x: 0, y: 0, width: 480, height: 350))
chart.backgroundColor = NSUIColor.clear
chart.centerText = "PieChart Unit Test"
chart.data = PieChartData(dataSet: dataSet)
}
override func tearDown()
{
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testDefaultValues()
{
ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance)
}
func testHidesValues()
{
dataSet.drawValuesEnabled = false
ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance)
}
func testDrawIcons()
{
dataSet.drawIconsEnabled = true
ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance)
}
func testHideCenterLabel()
{
chart.drawCenterTextEnabled = false
ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance)
}
}
|
apache-2.0
|
f776663ad0d99537bc9cb2a0a214d73c
| 32.945205 | 147 | 0.641243 | 4.897233 | false | true | false | false |
debugsquad/Hyperborea
|
Hyperborea/View/Favorites/VFavoritesBar.swift
|
1
|
3887
|
import UIKit
class VFavoritesBar:UIView
{
private weak var controller:CFavorites!
private let kBorderHeight:CGFloat = 1
private let kImageWidth:CGFloat = 50
private let kLabelWidth:CGFloat = 100
private let kCornerRadius:CGFloat = 5
private let kCancelMarginVertical:CGFloat = 14
private let kCancelRight:CGFloat = -10
private let kCancelWidth:CGFloat = 100
init(controller:CFavorites)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.white
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let border:VBorder = VBorder(color:UIColor(white:0, alpha:0.3))
let imageView:UIImageView = UIImageView()
imageView.isUserInteractionEnabled = false
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.clipsToBounds = true
imageView.contentMode = UIViewContentMode.center
imageView.image = #imageLiteral(resourceName: "assetGenericFavorites")
let label:UILabel = UILabel()
label.isUserInteractionEnabled = false
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.clear
label.font = UIFont.regular(size:16)
label.textColor = UIColor.black
label.text = NSLocalizedString("VFavoritesBar_label", comment:"")
let buttonCancel:UIButton = UIButton()
buttonCancel.translatesAutoresizingMaskIntoConstraints = false
buttonCancel.clipsToBounds = true
buttonCancel.backgroundColor = UIColor.hyperOrange
buttonCancel.layer.cornerRadius = kCornerRadius
buttonCancel.setTitle(
NSLocalizedString("VFavoritesBar_buttonCancel", comment:""),
for:UIControlState.normal)
buttonCancel.setTitleColor(
UIColor.white,
for:UIControlState.normal)
buttonCancel.setTitleColor(
UIColor(white:1, alpha:0.2),
for:UIControlState.highlighted)
buttonCancel.addTarget(
self,
action:#selector(actionCancel(sender:)),
for:UIControlEvents.touchUpInside)
buttonCancel.titleLabel!.font = UIFont.bold(size:14)
addSubview(border)
addSubview(imageView)
addSubview(label)
addSubview(buttonCancel)
NSLayoutConstraint.bottomToBottom(
view:border,
toView:self)
NSLayoutConstraint.height(
view:border,
constant:kBorderHeight)
NSLayoutConstraint.equalsHorizontal(
view:border,
toView:self)
NSLayoutConstraint.equalsVertical(
view:imageView,
toView:self)
NSLayoutConstraint.leftToLeft(
view:imageView,
toView:self)
NSLayoutConstraint.width(
view:imageView,
constant:kImageWidth)
NSLayoutConstraint.equalsVertical(
view:label,
toView:self)
NSLayoutConstraint.leftToRight(
view:label,
toView:imageView)
NSLayoutConstraint.width(
view:label,
constant:kLabelWidth)
NSLayoutConstraint.equalsVertical(
view:buttonCancel,
toView:self,
margin:kCancelMarginVertical)
NSLayoutConstraint.rightToRight(
view:buttonCancel,
toView:self,
constant:kCancelRight)
NSLayoutConstraint.width(
view:buttonCancel,
constant:kCancelWidth)
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: actions
func actionCancel(sender button:UIButton)
{
controller.viewFavorites.animateHide()
}
}
|
mit
|
a93ff2e1bfe0b65327193cfc32248def
| 31.940678 | 78 | 0.629534 | 5.767062 | false | false | false | false |
marceloreis13/MRTableViewManager
|
Example/MRTableViewManager/EmptyExampleTableViewController.swift
|
1
|
3238
|
//
// EmptyExampleTableViewController.swift
// MRTableViewManager
//
// Created by Marcelo Reis on 6/25/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import MRTableViewManager
// MARK: - Life Cycle
final class EmptyExampleTableViewController: UITableViewController {
// MARK: - Attributes
// Privates
fileprivate let _tableViewManager:TableViewManager = TableViewManager()
//XIBs
private let MRContentTVC = "MRContentTableViewCell"
private let MREmptyTVC = "MREmptyTableViewCell"
private let MRPreloadTVC = "MRPreloadTableViewCell"
override func viewDidLoad() {
super.viewDidLoad()
// TableViewManager Delegate
self._tableViewManager.delegate = self
//Update tableView data
self._updateTableView()
// Register XIBs
self.tableView.register(UINib(nibName: self.MRContentTVC, bundle: nil), forCellReuseIdentifier: self.MRContentTVC)
self.tableView.register(UINib(nibName: self.MREmptyTVC, bundle: nil), forCellReuseIdentifier: self.MREmptyTVC)
self.tableView.register(UINib(nibName: self.MRPreloadTVC, bundle: nil), forCellReuseIdentifier: self.MRPreloadTVC)
//Auto Layout
self.tableView.rowHeight = UITableViewAutomaticDimension
}
func refreshTableView(){
self._tableViewManager.clear()
self._updateTableView()
}
// MARK: - Private functions
fileprivate func _updateTableView(){
//Add section with a empty feed data
let _ = self._tableViewManager.addSection([] as AnyObject)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - TableViewManager Delegate
extension EmptyExampleTableViewController: TableViewManagerDelegate {
func getTableView() -> UITableView {
return self.tableView
}
func next(_ callback: (TableViewManager.Callback)?) {
self._tableViewManager.currentPage += 1
self._updateTableView()
}
}
// MARK: - UITableViewDataSource, UITableViewDelegate
extension EmptyExampleTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return self._tableViewManager.total()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self._tableViewManager.total(section)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var _cell:TableViewCell
let _sectionType = self._tableViewManager.sectionType(indexPath.section)
switch _sectionType {
case .empty:
_cell = tableView.dequeueReusableCell(withIdentifier: MREmptyTableViewCell.storyboardId) as! MREmptyTableViewCell
case .preload:
_cell = tableView.dequeueReusableCell(withIdentifier: MRPreloadTableViewCell.storyboardId) as! MRPreloadTableViewCell
case .content:
_cell = tableView.dequeueReusableCell(withIdentifier: MRContentTableViewCell.storyboardId) as! MRContentTableViewCell
case .unknow:
fatalError("Application requested for a non-existent item")
}
_cell.row = self._tableViewManager.get(indexPath)
_cell.updateViewData()
return _cell
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
}
|
mit
|
7050c468fcc4f43bd5444dcc2056a885
| 29.252336 | 120 | 0.76645 | 4.298805 | false | false | false | false |
KiranJasvanee/KJExpandableTableTree
|
Example_Static_Init/KJExpandableTableTree/TableviewCells/Childs3rdStageTableViewCell.swift
|
1
|
2335
|
//
// Childs3rdStageTableViewCell.swift
// Expandable3
//
// Created by MAC241 on 11/05/17.
// Copyright © 2017 KiranJasvanee. All rights reserved.
//
import UIKit
class Childs3rdStageTableViewCell: UITableViewCell {
@IBOutlet weak var imageviewBackground: UIImageView!
@IBOutlet weak var constraintLabelTitle: NSLayoutConstraint!
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var labelSubTitle: UILabel!
@IBOutlet weak var labelIndex: UILabel!
@IBOutlet weak var buttonState: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
labelTitle.font = UIFont(name: "HelveticaNeue-Bold", size: 15)
labelSubTitle.font = UIFont(name: "HelveticaNeue-Bold", size: 15)
labelIndex.font = UIFont(name: "HelveticaNeue-Bold", size: 14)
imageviewBackground.layer.cornerRadius = 2.0
imageviewBackground.layer.masksToBounds = true
}
func cellFillUp(indexParam: String, tupleCount: NSInteger) {
if tupleCount == 5 {
imageviewBackground.backgroundColor = UIColor(red: 11.0/255.0, green: 186/255.0, blue: 255.0/255.0, alpha: 1.0)
constraintLabelTitle.constant = 94
}else if tupleCount == 6 {
imageviewBackground.backgroundColor = UIColor(red: 11.0/255.0, green: 186/255.0, blue: 255.0/255.0, alpha: 1.0)
constraintLabelTitle.constant = 112
}else if tupleCount == 7 {
imageviewBackground.backgroundColor = UIColor(red: 11.0/255.0, green: 186/255.0, blue: 255.0/255.0, alpha: 1.0)
constraintLabelTitle.constant = 136
}else{
imageviewBackground.backgroundColor = UIColor(red: 255.0/255.0, green: 105.0/255.0, blue: 105.0/255.0, alpha: 1.0)
constraintLabelTitle.constant = 56
}
labelTitle.textColor = UIColor.white
labelSubTitle.textColor = UIColor.white
labelIndex.textColor = UIColor.white
labelTitle.text = "Child custom cell"
labelSubTitle.text = "Index of:"
labelIndex.text = indexParam
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
bb3663d9685909534c9074b4a4413706
| 36.645161 | 126 | 0.654242 | 4.153025 | false | false | false | false |
monisun/yowl
|
Yelp/BusinessCell.swift
|
1
|
1640
|
//
// BusinessCell.swift
// Yelp
//
// Created by Monica Sun on 5/16/15.
// Copyright (c) 2015 Monica Sun. All rights reserved.
//
import UIKit
class BusinessCell: UITableViewCell {
@IBOutlet weak var thumbView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var distance: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var rating: UIImageView!
@IBOutlet weak var addr: UILabel!
@IBOutlet weak var type: UILabel!
@IBOutlet weak var reviews: UILabel!
var business: Business! {
didSet {
nameLabel.text = business.name
thumbView.setImageWithURL(business.imageURL)
type.text = business.categories
addr.text = business.address
reviews.text = "\(business.reviewCount!) Reviews"
rating.setImageWithURL(business.ratingImageURL)
distance.text = business.distance
}
}
override func awakeFromNib() {
super.awakeFromNib()
thumbView.layer.cornerRadius = 5
thumbView.clipsToBounds = true
thumbView.contentMode = UIViewContentMode.ScaleAspectFill
nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width
}
override func layoutSubviews() {
super.layoutSubviews()
nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
26332c41ee1378af22e0f03446c482e5
| 24.625 | 70 | 0.634146 | 5.141066 | false | false | false | false |
inaka/Jolly
|
Sources/RepoSpecProvider.swift
|
1
|
3208
|
// RepoSpecProvider.swift
// Jolly
//
// Copyright 2016 Erlang Solutions, Ltd. - http://erlang-solutions.com/
//
// 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
class RepoSpecProvider {
let urlSession: URLSession
let parser: RepoSpecParser
init(urlSession: URLSession = .shared, parser: RepoSpecParser = RepoSpecParser()) {
self.urlSession = urlSession
self.parser = parser
}
enum Error: Swift.Error {
case responseError
case dataError
case parsingError
case corruptedResponse
}
func fetchSpecs(for repos: [Repo]) -> Future<[RepoSpec], Error> {
// ⛔️ FIXME: This is not thread-safe
return Future() { completion in
var left = repos.count
if left == 0 {
completion(.success([RepoSpec]()))
return
}
var specs = [RepoSpec]()
for repo in repos {
self.fetchSpec(for: repo).start() { result in
left -= 1
if case .success(let spec) = result {
specs += [spec]
}
if left == 0 {
completion(.success(specs.sorted { $0.fullName.lowercased() < $1.fullName.lowercased() }))
}
}
}
}
}
func fetchSpec(for repo: Repo) -> Future<RepoSpec, Error> {
let url = URL(string: "https://api.github.com/repos/\(repo.organization)/\(repo.name)")!
let request = URLRequest.githubGETRequest(for: url)
return Future() { completion in
self.urlSession.dataTask(with: request) { data, response, error in
if error != nil {
completion(.failure(.responseError))
return
}
guard
let data = data,
let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments),
let dict = json as? [String: Any],
let spec = self.parser.repoSpec(from: dict)
else {
completion(.failure(.dataError)); return
}
completion(.success(spec))
}.resume()
}
}
}
extension URLRequest {
static func githubGETRequest(for url: URL) -> URLRequest {
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/vnd.github.v3+json", forHTTPHeaderField: "Accept")
return request
}
}
|
apache-2.0
|
6c17dac197d83394fd4bcdd80cec7896
| 33.826087 | 114 | 0.55774 | 4.854545 | false | false | false | false |
emilianoeloi/ios-estudosGerais
|
ios-estudosGerais/DozeViewController.swift
|
1
|
1575
|
//
// DozeViewController.swift
// ios-estudosGerais
//
// Created by Emiliano Barbosa on 1/9/16.
// Copyright © 2016 Emiliano E. S. Barbosa. All rights reserved.
//
import UIKit
class DozeViewController : UIViewController{
@IBOutlet weak var webview: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let mainUrl = NSURL(string: "http://www.stackoverflow.com")
let task = NSURLSession.sharedSession().dataTaskWithURL(mainUrl!) { (data, response, error) -> Void in
if let urlContent = data {
let web = NSString(data:urlContent, encoding:NSUTF8StringEncoding)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.webview.loadHTMLString(String(web), baseURL: nil);
})
}else{
}
}
task.resume()
}
func randomCode() -> Void{
var str = "Emiliano"
var newString = "Hello " + str
for chars in newString.characters{
print(chars)
}
var newTypeString = NSString(string:newString)
newTypeString.substringFromIndex(5)
newTypeString.substringToIndex(5)
newTypeString.substringWithRange(NSRange(location: 5, length: 2))
if (newTypeString.containsString("Emiliano")){
print("YES")
}else{
print("NO")
}
newTypeString.componentsSeparatedByString(" ")
newTypeString.uppercaseString
}
}
|
mit
|
02c77fff1e69384cda0e3c8e198b9437
| 27.636364 | 110 | 0.571156 | 4.726727 | false | false | false | false |
melsomino/unified-ios
|
Unified/Interfaces/Cloud/Converters/CloudApiFieldConverter.swift
|
1
|
691
|
//
// Created by Власов М.Ю. on 12.05.16.
// Copyright (c) 2016 Tensor. All rights reserved.
//
import Foundation
public class CloudApiFieldConverter<StructType> {
public typealias FieldSetter = (StructType, AnyObject) -> Void
public typealias FieldGetter = (StructType) -> AnyObject
public let cloudName: String
public let cloudTypeName: String
public let fieldSetter: FieldSetter
public let fieldGetter: FieldGetter
public init(_ cloudName: String, _ cloudTypeName: String, _ fieldSetter: FieldSetter, _ fieldGetter: FieldGetter) {
self.cloudName = cloudName
self.cloudTypeName = cloudTypeName
self.fieldSetter = fieldSetter
self.fieldGetter = fieldGetter
}
}
|
mit
|
cbc7a68b7bcad648165b9b1ba2695887
| 27.458333 | 116 | 0.762811 | 3.73224 | false | false | false | false |
marty-suzuki/QiitaApiClient
|
QiitaApiClient/Model/QiitaUser.swift
|
1
|
2232
|
//
// QiitaUser.swift
// QiitaApiClient
//
// Created by Taiki Suzuki on 2016/08/20.
//
//
import Foundation
public class QiitaUser: QiitaModel {
public let description: String?
public let facebookId: String?
public let followeesCount: Int
public let followersCount: Int
public let githubLoginName: String?
public let id: String
public let itemsCount: Int
public let linkedinId: String?
public let location: String?
public let name: String?
public let organization: String?
public let permanentId: Int
public let profileImageUrl: NSURL
public let twitterScreenName: String?
public let websiteUrl: NSURL?
public required init?(dictionary: [String : NSObject]) {
guard
let followeesCount = dictionary["followees_count"] as? Int,
let followersCount = dictionary["followers_count"] as? Int,
let id = dictionary["id"] as? String,
let itemsCount = dictionary["items_count"] as? Int,
let permanentId = dictionary["permanent_id"] as? Int,
let rawProfileImageUrl = dictionary["profile_image_url"] as? String,
let profileImageUrl = NSURL(string: rawProfileImageUrl)
else {
return nil
}
self.description = dictionary["description"] as? String
self.facebookId = dictionary["facebook_id"] as? String
self.followeesCount = followeesCount
self.followersCount = followersCount
self.githubLoginName = dictionary["github_login_name"] as? String
self.id = id
self.itemsCount = itemsCount
self.linkedinId = dictionary["linkedin_id"] as? String
self.location = dictionary["location"] as? String
self.name = dictionary["name"] as? String
self.organization = dictionary["organization"] as? String
self.permanentId = permanentId
self.profileImageUrl = profileImageUrl
self.twitterScreenName = dictionary["twitter_screen_name"] as? String
if let rawWebsiteUrl = dictionary["website_url"] as? String {
self.websiteUrl = NSURL(string: rawProfileImageUrl)
} else {
self.websiteUrl = nil
}
}
}
|
mit
|
983d7610c15c664f4f26b0d4210daef8
| 35.590164 | 80 | 0.649642 | 4.621118 | false | false | false | false |
rpowelll/GameBro
|
Sources/GameBro/Memory.swift
|
1
|
4487
|
public typealias Address = UInt16
extension Address {
/// Construct a byte from a page and offset
///
/// - parameter page: an 8-bit page number
/// - parameter offset: an 8-bit offset
///
/// - returns: a 16-bit address with the provided page and offset
init(page: UInt8, offset: UInt8) {
self = UInt16(page) << 8 | UInt16(offset)
}
/// The page (first 8 bits) of the address
var page: UInt8 {
return UInt8(self >> 8)
}
/// The offset (last 8 bits) of the address
var offset: UInt8 {
return UInt8(self & 0xFF)
}
}
/// An implementation of the Game Boy's mapped memory
///
/// ## Memory Layout
///
/// +-----------------+------------------------------+
/// | 0x0000..<0x4000 | 16k cart ROM bank #0 |
/// | 0x4000..<0x8000 | 16k switchable cart ROM bank |
/// | 0x8000..<0xA000 | 8k VRAM |
/// | 0xA000..<0xC000 | 8k switchable RAM bank |
/// | 0xC000..<0xE000 | 8k internal RAM |
/// | 0xE000..<0xFE00 | Echo of 8k internal RAM |
/// | 0xFE00..<0xFEA0 | Sprite attrib memory (OAM) |
/// | 0xFF00..<0xFF4C | I/O Ports |
/// | 0xFF80..<0xFFFF | Zero-page RAM |
/// | 0xFFFF | Interrupt enable register |
/// +-----------------+------------------------------+
public struct Memory {
/// 8kb of main RAM
private var RAM = Array<UInt8>(repeating: 0x00, count: 0x2000)
/// Read the byte at `address`
///
/// - parameter address: the address of the byte to be read
///
/// - returns: the byte at `address`
public func read(_ address: Address) -> UInt8 {
switch address {
case 0x0000..<0x4000: // 16k cart ROM bank #0
break
case 0x4000..<0x8000: // 16k switchable cart ROM bank
break
case 0x8000..<0xA000: // 8k VRAM
break
case 0xA000..<0xC000: // 8k switchable RAM bank
break
case 0xC000..<0xE000: // 8k internal RAM
return RAM[Int(address % 0x2000)]
case 0xE000..<0xFE00: // Echo of 8k internal RAM
return RAM[Int(address % 0x2000)]
case 0xFE00..<0xFEA0: // Sprite attrib memory (OAM)
break
case 0xFF00..<0xFF4C: // I/O Ports
break
case 0xFF80..<0xFFFF: // Zero-page RAM
return RAM[Int(address % 0x2000)]
case 0xFFFF: // Interrupt enable register
break
default:
fatalError("Not yet implemented")
}
return 0x00
}
/// Read two bytes at `address`
///
/// - parameter address: the address of the bytes to be read
///
/// - returns: the two bytes at `address`
public func read16(_ address: Address) -> UInt16 {
let low = read(address)
let high = read(address + 1)
return UInt16(high) << 8 | UInt16(low)
}
/// Write a byte to `address`
///
/// - parameter address: the address to be written to
/// - parameter value: the value to be written
public mutating func write(_ address: Address, _ value: UInt8) {
switch address {
case 0x0000..<0x4000: // 16k cart ROM bank #0
break
case 0x4000..<0x8000: // 16k switchable cart ROM bank
break
case 0x8000..<0xA000: // 8k VRAM
break
case 0xA000..<0xC000: // 8k switchable RAM bank
break
case 0xC000..<0xE000: // 8k internal RAM
RAM[Int(address % 0x2000)] = value
case 0xE000..<0xFE00: // Echo of 8k internal RAM
RAM[Int(address % 0x2000)] = value
case 0xFE00..<0xFEA0: // Sprite attrib memory (OAM)
break
case 0xFF00..<0xFF4C: // I/O Ports
break
case 0xFF80..<0xFFFF: // Zero-page RAM
RAM[Int(address % 0x2000)] = value
case 0xFFFF: // Interrupt enable register
break
default:
fatalError("Not yet implemented")
}
}
/// Write a 16-bit value to `address`
///
/// - parameter address: the address to be written to
/// - parameter value: the 16-bit value to be written
public mutating func write16(_ address: Address, _ value: UInt16) {
let low = UInt8(value & 0x00FF)
let high = UInt8(value >> 8)
write(address, low)
write(address + 1, high)
}
}
|
mit
|
fbe3febee1a2bb6ffe455c4240d530a5
| 32.485075 | 71 | 0.52797 | 3.789696 | false | false | false | false |
erikmartens/NearbyWeather
|
NearbyWeather/Scenes/Weather List Error Scene/WeatherListErrorViewModel.swift
|
1
|
4055
|
//
// ListErrorViewModel.swift
// NearbyWeather
//
// Created by Erik Maximilian Martens on 15.02.22.
// Copyright © 2022 Erik Maximilian Martens. All rights reserved.
//
import RxSwift
import RxCocoa
import RxFlow
import CoreLocation
// MARK: - Domain Specific Types
extension WeatherListErrorViewModel {
enum ListErrorType: Int {
case network
case apiKey
case noData
static func mapToErrorType(isApiKeyValid: Bool, isNetworkReachable: Bool) -> Self {
if !isNetworkReachable {
return .network
} else if !isApiKeyValid {
return .apiKey
}
return .noData
}
var title: String {
switch self {
case .network:
return R.string.localizable.no_weather_data() // TODO: write different descriptions for different error
case .apiKey:
return R.string.localizable.no_weather_data()
case .noData:
return R.string.localizable.no_weather_data()
}
}
var message: String {
switch self {
case .network:
return R.string.localizable.no_data_description() // TODO: write different descriptions for different error
case .apiKey:
return R.string.localizable.no_data_description()
case .noData:
return R.string.localizable.no_data_description()
}
}
}
}
// MARK: - Dependencies
extension WeatherListErrorViewModel {
struct Dependencies {
let apiKeyService: ApiKeyReading
let weatherInformationService: WeatherInformationUpdating
let networkReachabilityService: NetworkReachability
}
}
// MARK: - Class Definition
final class WeatherListErrorViewModel: NSObject, Stepper, BaseViewModel {
// MARK: - Routing
let steps = PublishRelay<Step>()
// MARK: - Assets
private let disposeBag = DisposeBag()
// MARK: - Properties
private let dependencies: Dependencies
// MARK: - Events
let onDidTapRefreshButtonSubject = PublishSubject<Void>()
private let isRefreshingSubject = PublishSubject<Bool>()
// MARK: - Drivers
lazy var isRefreshingDriver = isRefreshingSubject.asDriver(onErrorJustReturn: false)
lazy var errorTypeDriver: Driver<ListErrorType> = Observable
.combineLatest(
isApiKeyValidObservable,
isNetworkReachableObservable,
resultSelector: ListErrorType.mapToErrorType
)
.asDriver(onErrorJustReturn: .network)
// MARK: - Observables
private lazy var isApiKeyValidObservable: Observable<Bool> = { [dependencies] in
dependencies.apiKeyService
.createApiKeyIsValidObservable()
.map { $0.isValid }
.share(replay: 1)
}()
private lazy var isNetworkReachableObservable: Observable<Bool> = { [dependencies] in
dependencies.networkReachabilityService
.createIsNetworkReachableObservable()
.share(replay: 1)
}()
// MARK: - Initialization
required init(dependencies: Dependencies) {
self.dependencies = dependencies
super.init()
}
deinit {
printDebugMessage(
domain: String(describing: self),
message: "was deinitialized",
type: .info
)
}
// MARK: - Functions
func observeEvents() {
observeDataSource()
observeUserTapEvents()
}
}
// MARK: - Observations
extension WeatherListErrorViewModel {
func observeDataSource() {
// nothing to do
}
func observeUserTapEvents() {
onDidTapRefreshButtonSubject
.do(onNext: { [weak isRefreshingSubject] in isRefreshingSubject?.onNext(true) })
.flatMapLatest { [unowned self] _ -> Observable<Void> in
Completable
.zip([
dependencies.weatherInformationService.createUpdateNearbyWeatherInformationCompletable(),
dependencies.weatherInformationService.createUpdateBookmarkedWeatherInformationCompletable()
])
.do(onCompleted: { [weak isRefreshingSubject] in isRefreshingSubject?.onNext(false) })
.asObservable()
.map { _ in () }
}
.subscribe()
.disposed(by: disposeBag)
}
}
|
mit
|
c81299c81b6fd6a3d6cd1e32e972fe1c
| 24.180124 | 115 | 0.675876 | 4.78066 | false | false | false | false |
erikmartens/NearbyWeather
|
NearbyWeather/Scenes/Settings Scene/Table View Cells/Settings Imaged Single Label Cell/SettingsImagedSingleLabelCellModel.swift
|
1
|
809
|
//
// SettingsImagedSingleLabelCellModel.swift
// NearbyWeather
//
// Created by Erik Maximilian Martens on 06.03.22.
// Copyright © 2022 Erik Maximilian Martens. All rights reserved.
//
import UIKit
struct SettingsImagedSingleLabelCellModel {
let symbolImageBackgroundColor: UIColor?
let symbolImageName: String?
let labelText: String?
let isSelectable: Bool?
let isDisclosable: Bool?
init(
symbolImageBackgroundColor: UIColor? = nil,
symbolImageName: String? = nil,
labelText: String? = nil,
selectable: Bool? = nil,
disclosable: Bool? = nil
) {
self.symbolImageBackgroundColor = symbolImageBackgroundColor
self.symbolImageName = symbolImageName
self.labelText = labelText
self.isSelectable = selectable
self.isDisclosable = disclosable
}
}
|
mit
|
5d39620c6b5745c0247c02956fcc631b
| 25.064516 | 66 | 0.732673 | 4.415301 | false | false | false | false |
mamaral/MATextFieldCell
|
MATextFieldCell Example/MATextFieldCell Example/ShortFormExampleTableViewController.swift
|
1
|
2398
|
//
// ShortFormExampleTableViewController.swift
// MATextFieldCell Example
//
// Created by Mike on 6/14/14.
// Copyright (c) 2014 Mike Amaral. All rights reserved.
//
import UIKit
class ShortFormExampleTableViewController: UITableViewController {
let firstNameCell: MATextFieldCell = MATextFieldCell(type: MATextFieldType.Name, action: MATextFieldActionType.Next)
let lastNameCell: MATextFieldCell = MATextFieldCell(type: MATextFieldType.Name, action: MATextFieldActionType.Next)
let phoneCell: MATextFieldCell = MATextFieldCell(type: MATextFieldType.Phone, action: MATextFieldActionType.Done)
var cells = []
required init(coder: NSCoder) {
fatalError("NSCoding not supported")
}
override init(style: UITableViewStyle) {
super.init(style: style)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func viewDidLoad() {
super.viewDidLoad()
generateCells()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
firstNameCell.textField.becomeFirstResponder()
}
func generateCells() {
firstNameCell.textField.placeholder = "First name"
firstNameCell.actionBlock = {
self.lastNameCell.textField.becomeFirstResponder()
return
}
lastNameCell.textField.placeholder = "Last name"
lastNameCell.actionBlock = {
self.phoneCell.textField.becomeFirstResponder()
return
}
phoneCell.textField.placeholder = "Phone"
phoneCell.actionBlock = {
self.phoneCell.textField.resignFirstResponder()
return
}
cells = [firstNameCell, lastNameCell, phoneCell];
}
// #pragma mark - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
return 1
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
return cells.count
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
return cells[indexPath!.row] as MATextFieldCell
}
}
|
mit
|
2a928a87079c9a56cb68966cf4388d2c
| 30.142857 | 121 | 0.661802 | 5.113006 | false | false | false | false |
mahuiying0126/MDemo
|
BangDemo/BangDemo/Modules/Personal/Down/control/MDownViewController.swift
|
1
|
4316
|
//
// MDownViewController.swift
// BangDemo
//
// Created by yizhilu on 2017/5/9.
// Copyright © 2017年 Magic. All rights reserved.
//
import UIKit
class MDownViewController: UIViewController,playViedoDelegate,MPlayerViewDelegate {
///初始化一个下载单例,为了使控制器不走声明周期,做下载
static let shareInstance = MDownViewController()
/** *播放器视图 */
private var playerView : MPlayerView?
private var segmetControl : UISegmentedControl?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = Whit
self.title = "离线下载"
self.downLoadTable.reloadData()
let segTile = ["下载中","已完成"]
segmetControl = UISegmentedControl.init(items: segTile)
segmetControl?.frame = .init(x: 20, y: Spacing10, width: Screen_width - 40, height: 30)
self.view.addSubview(segmetControl!)
segmetControl?.selectedSegmentIndex = 0
segmetControl?.addTarget(self, action: #selector(segmetEvent(sender:)), for: .valueChanged)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if MFMDBTool.shareInstance.listDataFromDownloaingTable().count > 0 {
self.downLoadTable.updataTableForData(true)
segmetControl?.selectedSegmentIndex = 0
}else{
if MFMDBTool.shareInstance.listDataFromFinshTable().count > 0 {
self.downLoadTable.updataTableForData(false)
segmetControl?.selectedSegmentIndex = 1
}else{
self.downLoadTable.updataTableForData(true)
segmetControl?.selectedSegmentIndex = 0
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
//消失关闭播放器
self.playerView?.closPlaer()
self.playerView = nil
}
func playVideoWithVideoModel(model : DownloadingModel){
let url = LibraryFor96k + "/\(model.videoUrl!)"
ParsingEncrypteString.parseStringWith(urlString: url, fileType: model.fileType!, isLocal: true) {[weak self] (videoUrl) in
if self?.playerView != nil {
self?.playerView?.removeFromSuperview()
self?.playerView?.currentTime = 0
self?.playerView?.exchangeWithURL(videoURLStr: videoUrl)
}else{
self?.navigationController?.setNavigationBarHidden(true, animated: false)
self?.playerView = MPlayerView.shared.initWithFrame(frame: CGRect.init(x: 0, y: 0, width: Screen_width, height: Screen_width * 9/16), videoUrl: videoUrl, type: model.fileType!)
self?.downLoadTable.frame = CGRect.init(x: 0, y: Screen_width * 9/16, width: Screen_width, height: Screen_height - Screen_width * 9/16)
self?.playerView?.mPlayerDelegate = self
}
self?.playerView?.videoParseCode = url
self?.view.addSubview((self?.playerView)!)
}
}
func closePlayer(){
self.playerView = nil
self.navigationController?.setNavigationBarHidden(false, animated: false)
self.downLoadTable.frame = CGRect.init(x: 0, y: 50, width: Screen_width, height: Screen_height - 64 - 50)
}
@objc func segmetEvent(sender:UISegmentedControl){
if sender.selectedSegmentIndex == 0 {
///下载中
self.downLoadTable.updataTableForData(true)
}else{
///已完成
self.downLoadTable.updataTableForData(false)
}
}
lazy var downLoadTable : MDownloadingTable = {
let tableView = MDownloadingTable.init(frame:CGRect.init(x: 0, y: 50 , width: Screen_width, height: Screen_height - 64 - 50), style: .plain)
tableView.playLocalVidelDelgate = self
tableView.viewControlM = self
self.view.addSubview(tableView)
return tableView
}()
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
MYLog("下载页面消失了")
}
}
|
mit
|
bb47e28ec626f150c615de1e0b12d9ab
| 35.478261 | 192 | 0.62789 | 4.411146 | false | false | false | false |
OlexaBoyko/SwiftAI
|
SwiftAI/SAIPerceptron.swift
|
1
|
2131
|
//
// SAIPerceptron.swift
// SwiftAI
//
// Created by Olexa Boyko on 2/12/17.
// Copyright © 2017 Lviv National University. All rights reserved.
//
import Foundation
open class SAIPerceptron {
public var studyingCoefficient: Double {
didSet{
if studyingCoefficient <= 0 {
studyingCoefficient = Double.leastNormalMagnitude
return
}
}
}
//public var inputWeights: Array<Double>
//internal var delegates: Array<SAIPerceptronDelegate> = []
public var activationFunc: (Double) -> Double
public var inputSource: [SAIPerceptronInput] = []
///Get input from input source
public var inputValues: [Double] {
var result = [Double]()
for inputEdge in self.inputSource {
let input = inputEdge.input.output
result.append(input)
}
return result
}
public init(studyingCoefficient: Double,
inputSource: [SAIPerceptronInput],
activationFunc: @escaping (Double) -> Double) {
self.studyingCoefficient = studyingCoefficient
self.inputSource = inputSource
self.activationFunc = activationFunc
}
public func calculate() -> Double {
var result = 0.0
for edge in inputSource {
result.add(edge.input.output*edge.weight)
}
let output = activationFunc(result)
return output
}
public func educate(expectingResult d: Double) {
let output = self.calculate()
for edge in self.inputSource {
edge.weight = edge.weight + self.studyingCoefficient * (d - output) * edge.input.output
}
}
}
extension SAIPerceptron: SAIOutputValue {
public var output: Double{
return self.calculate()
}
}
public class SAIPerceptronInput {
var weight: Double
var input: SAIOutputValue
init(weight: Double, input: SAIOutputValue) {
self.weight = weight
self.input = input
}
}
public protocol SAIOutputValue {
var output: Double {
get
}
}
|
mit
|
95e853b3a1b4f78153ce3f7075f47d13
| 23.767442 | 99 | 0.604225 | 4.285714 | false | false | false | false |
mattdaw/SwiftBoard
|
SwiftBoard/CollectionViewLayouts/DroppableCollectionViewLayout.swift
|
1
|
800
|
//
// DroppableCollectionViewLayout.swift
// SwiftBoard
//
// Created by Matt Daw on 2014-11-12.
// Copyright (c) 2014 Matt Daw. All rights reserved.
//
import Foundation
class DroppableCollectionViewLayout: UICollectionViewLayout {
var itemsPerRow = 1
func indexToMoveSourceIndexLeftOfDestIndex(sourceIndex: Int, destIndex: Int) -> Int {
let column = destIndex % itemsPerRow
var offset = 0
if sourceIndex < destIndex && column != 0 {
offset = -1
}
return destIndex + offset
}
func indexToMoveSourceIndexRightOfDestIndex(sourceIndex: Int, destIndex: Int) -> Int {
var offset = 1
if sourceIndex < destIndex {
offset = 0
}
return destIndex + offset
}
}
|
mit
|
b7d40df8aa117cc24f2b32c6ecabd1ea
| 24.03125 | 90 | 0.615 | 4.519774 | false | false | false | false |
onevcat/Kingfisher
|
Demo/Demo/Kingfisher-Demo/ViewControllers/TransitionViewController.swift
|
2
|
3940
|
//
// TransitionViewController.swift
// Kingfisher
//
// Created by onevcat on 2018/11/18.
//
// Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Kingfisher
class TransitionViewController: UIViewController {
enum PickerComponent: Int, CaseIterable {
case transitionType
case duration
}
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var transitionPickerView: UIPickerView!
let durations: [TimeInterval] = [0.5, 1, 2, 4, 10]
let transitions: [String] = ["none", "fade", "flip - left", "flip - right", "flip - top", "flip - bottom"]
override func viewDidLoad() {
super.viewDidLoad()
title = "Transition"
setupOperationNavigationBar()
imageView.kf.indicatorType = .activity
}
func makeTransition(type: String, duration: TimeInterval) -> ImageTransition {
switch type {
case "none": return .none
case "fade": return .fade(duration)
case "flip - left": return .flipFromLeft(duration)
case "flip - right": return .flipFromRight(duration)
case "flip - top": return .flipFromTop(duration)
case "flip - bottom": return .flipFromBottom(duration)
default: return .none
}
}
func reloadImageView() {
let typeIndex = transitionPickerView.selectedRow(inComponent: PickerComponent.transitionType.rawValue)
let transitionType = transitions[typeIndex]
let durationIndex = transitionPickerView.selectedRow(inComponent: PickerComponent.duration.rawValue)
let duration = durations[durationIndex]
let t = makeTransition(type: transitionType, duration: duration)
let url = ImageLoader.sampleImageURLs[0]
KF.url(url)
.forceTransition()
.transition(t)
.set(to: imageView)
}
}
extension TransitionViewController: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch PickerComponent(rawValue: component)! {
case .transitionType: return transitions[row]
case .duration: return String(durations[row])
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
reloadImageView()
}
}
extension TransitionViewController: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return PickerComponent.allCases.count
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch PickerComponent(rawValue: component)! {
case .transitionType: return transitions.count
case .duration: return durations.count
}
}
}
|
mit
|
41001600347fa374f7bb783308f0f22e
| 37.252427 | 111 | 0.686548 | 4.810745 | false | false | false | false |
ayanonagon/LinguisticsSample
|
LinguisticsSample/NaiveBayesClassifier.swift
|
1
|
3197
|
//
// NaiveBayesClassifier.swift
// LinguisticsSample
//
// Created by Ayaka Nonaka on 3/9/15.
// Copyright (c) 2015 Ayaka Nonaka. All rights reserved.
//
import Foundation
public class NaiveBayesClassifier {
public typealias Category = String
private let tokenizer: String -> [String]
private var categoryOccurrences: [Category: Int] = [:]
private var tokenOccurrences: [String: [Category: Int]] = [:]
private var trainingCount = 0
private var tokenCount = 0
private let smoothingParameter = 1.0
public init(tokenizer: (String -> [String])) {
self.tokenizer = tokenizer
}
// MARK: - Training
public func trainWithText(text: String, category: Category) {
trainWithTokens(tokenizer(text), category: category)
}
public func trainWithTokens(tokens: [String], category: Category) {
let tokens = Set(tokens)
for token in tokens {
incrementToken(token, category: category)
}
incrementCategory(category)
trainingCount++
}
// MARK: - Classifying
public func classifyText(text: String) -> Category? {
return classifyTokens(tokenizer(text))
}
public func classifyTokens(tokens: [String]) -> Category? {
// Compute argmax_cat [log(P(C=cat)) + sum_token(log(P(W=token|C=cat)))]
var maxCategory: Category?
var maxCategoryScore = -Double.infinity
for (category, _) in categoryOccurrences {
let pCategory = P(category)
let score = tokens.reduce(log(pCategory)) { (total, token) in
// P(W=token|C=cat) = P(C=cat, W=token) / P(C=cat)
total + log((P(category, token) + smoothingParameter) / (pCategory + smoothingParameter * Double(tokenCount)))
}
if score > maxCategoryScore {
maxCategory = category
maxCategoryScore = score
}
}
return maxCategory
}
// MARK: - Probabilites
private func P(category: Category, _ token: String) -> Double {
return Double(tokenOccurrences[token]?[category] ?? 0) / Double(trainingCount)
}
private func P(category: Category) -> Double {
return Double(totalOccurrencesOfCategory(category)) / Double(trainingCount)
}
// MARK: - Counting
private func incrementToken(token: String, category: Category) {
if tokenOccurrences[token] == nil {
tokenCount++
tokenOccurrences[token] = [:]
}
// Force unwrap to crash instead of providing faulty results.
let count = tokenOccurrences[token]![category] ?? 0
tokenOccurrences[token]![category] = count + 1
}
private func incrementCategory(category: Category) {
categoryOccurrences[category] = totalOccurrencesOfCategory(category) + 1
}
private func totalOccurrencesOfToken(token: String) -> Int {
if let occurrences = tokenOccurrences[token] {
return reduce(occurrences.values, 0, +)
}
return 0
}
private func totalOccurrencesOfCategory(category: Category) -> Int {
return categoryOccurrences[category] ?? 0
}
}
|
mit
|
bcdc304478ecba0c8bd479ee4ed2bfae
| 30.038835 | 126 | 0.624023 | 4.279786 | false | false | false | false |
paramaggarwal/tictactoe
|
TicTacToe/ViewController.swift
|
1
|
4103
|
//
// ViewController.swift
// TicTacToe
//
// Created by Param Aggarwal on 22/09/14.
// Copyright (c) 2014 Assignment. All rights reserved.
//
import UIKit
class ViewController: UICollectionViewController {
var cellState = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
var isOtherPlayer = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return cellState.count;
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cellState[section].count;
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let row = self.cellState[indexPath.section]
let item = row[indexPath.row]
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell-empty", forIndexPath: indexPath) as UICollectionViewCell
if item == 1 {
cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell-o", forIndexPath: indexPath) as UICollectionViewCell
} else if item == 2 {
cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell-x", forIndexPath: indexPath) as UICollectionViewCell
}
return cell;
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
var row = self.cellState[indexPath.section]
var cell = row[indexPath.row]
// if not yet selected
if row[indexPath.row] == 0 {
if self.isOtherPlayer {
row[indexPath.row] = 1
} else {
row[indexPath.row] = 2
}
self.cellState[indexPath.section] = row
collectionView.reloadData()
self.isOtherPlayer = !self.isOtherPlayer
let winner = self.checkForWinner()
if winner == "o" || winner == "x" {
self.alertWinner(winner)
NSLog("Winner %@", winner)
}
}
}
func checkForWinner() -> String {
// check for rows
for (var i=0; i<3; i++) {
let row = self.cellState[i]
if (row[0] == 1 && row[1] == 1 && row[2] == 1) {
return "o"
// o WINS
} else if (row[0] == 2 && row[1] == 2 && row[2] == 2) {
// x wins
return "x"
}
}
// check for columns
let row1 = self.cellState[0];
let row2 = self.cellState[1];
let row3 = self.cellState[2];
for (var i=0; i<3; i++) {
let item1 = row1[i]
let item2 = row2[i]
let item3 = row3[i]
if (item1 == 1 && item2 == 1 && item3 == 1) {
// o WINS
return "o"
} else if (item1 == 2 && item2 == 2 && item3 == 2) {
// x wins
return "x"
}
}
// check diagonals
if (self.cellState[0][0] == 1 && self.cellState[1][1] == 1 && self.cellState[2][2] == 1) {
// o WINS
return "o"
} else if (self.cellState[0][0] == 2 && self.cellState[1][1] == 2 && self.cellState[2][2] == 2) {
// x wins
return "x"
}
return ""
}
func alertWinner(winner : String) {
var alert = UIAlertController(title: "We have a winner!", message: "...and it is: " + winner, preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(alert, animated: true, completion: nil)
}
}
|
mit
|
585e6eeb8c00bd9fae4ac992ad5b6301
| 31.563492 | 147 | 0.537899 | 4.558889 | false | false | false | false |
TotalDigital/People-iOS
|
Pods/p2.OAuth2/Sources/iOS/OAuth2WebViewController.swift
|
2
|
7487
|
//
// OAuth2WebViewController.swift
// OAuth2
//
// Created by Pascal Pfiffner on 7/15/14.
// Copyright 2014 Pascal Pfiffner
//
// 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.
//
#if os(iOS)
import UIKit
import WebKit
#if !NO_MODULE_IMPORT
import Base
#endif
/**
A simple iOS web view controller that allows you to display the login/authorization screen.
*/
open class OAuth2WebViewController: UIViewController, WKNavigationDelegate {
/// Handle to the OAuth2 instance in play, only used for debug lugging at this time.
var oauth: OAuth2?
/// The URL to load on first show.
open var startURL: URL? {
didSet(oldURL) {
if nil != startURL && nil == oldURL && isViewLoaded {
load(url: startURL!)
}
}
}
/// The URL string to intercept and respond to.
var interceptURLString: String? {
didSet(oldURL) {
if nil != interceptURLString {
if let url = URL(string: interceptURLString!) {
interceptComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)
}
else {
oauth?.logger?.debug("OAuth2", msg: "Failed to parse URL \(interceptURLString), discarding")
interceptURLString = nil
}
}
else {
interceptComponents = nil
}
}
}
var interceptComponents: URLComponents?
/// Closure called when the web view gets asked to load the redirect URL, specified in `interceptURLString`. Return a Bool indicating
/// that you've intercepted the URL.
var onIntercept: ((URL) -> Bool)?
/// Called when the web view is about to be dismissed. The Bool indicates whether the request was (user-)cancelled.
var onWillDismiss: ((_ didCancel: Bool) -> Void)?
/// Assign to override the back button, shown when it's possible to go back in history. Will adjust target/action accordingly.
open var backButton: UIBarButtonItem? {
didSet {
if let backButton = backButton {
backButton.target = self
backButton.action = #selector(OAuth2WebViewController.goBack(_:))
}
}
}
var showCancelButton = true
var cancelButton: UIBarButtonItem?
/// Our web view.
var webView: WKWebView?
/// An overlay view containing a spinner.
var loadingView: UIView?
init() {
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - View Handling
override open func loadView() {
edgesForExtendedLayout = .all
extendedLayoutIncludesOpaqueBars = true
automaticallyAdjustsScrollViewInsets = true
super.loadView()
view.backgroundColor = UIColor.white
if showCancelButton {
cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(OAuth2WebViewController.cancel(_:)))
navigationItem.rightBarButtonItem = cancelButton
}
// create a web view
let web = WKWebView()
web.translatesAutoresizingMaskIntoConstraints = false
web.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal
web.navigationDelegate = self
view.addSubview(web)
let views = ["web": web]
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[web]|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[web]|", options: [], metrics: nil, views: views))
webView = web
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let web = webView, !web.canGoBack {
if nil != startURL {
load(url: startURL!)
}
else {
web.loadHTMLString("There is no `startURL`", baseURL: nil)
}
}
}
func showHideBackButton(_ show: Bool) {
if show {
let bb = backButton ?? UIBarButtonItem(barButtonSystemItem: .rewind, target: self, action: #selector(OAuth2WebViewController.goBack(_:)))
navigationItem.leftBarButtonItem = bb
}
else {
navigationItem.leftBarButtonItem = nil
}
}
func showLoadingIndicator() {
// TODO: implement
}
func hideLoadingIndicator() {
// TODO: implement
}
func showErrorMessage(_ message: String, animated: Bool) {
NSLog("Error: \(message)")
}
// MARK: - Actions
open func load(url: URL) {
let _ = webView?.load(URLRequest(url: url))
}
func goBack(_ sender: AnyObject?) {
let _ = webView?.goBack()
}
func cancel(_ sender: AnyObject?) {
dismiss(asCancel: true, animated: (nil != sender) ? true : false)
}
override open func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
dismiss(asCancel: false, animated: flag, completion: completion)
}
func dismiss(asCancel: Bool, animated: Bool, completion: (() -> Void)? = nil) {
webView?.stopLoading()
if nil != self.onWillDismiss {
self.onWillDismiss!(asCancel)
}
super.dismiss(animated: animated, completion: completion)
}
// MARK: - Web View Delegate
open func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void) {
guard let onIntercept = onIntercept else {
decisionHandler(.allow)
return
}
let request = navigationAction.request
// we compare the scheme and host first, then check the path (if there is any). Not sure if a simple string comparison
// would work as there may be URL parameters attached
if let url = request.url, url.scheme == interceptComponents?.scheme && url.host == interceptComponents?.host {
let haveComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)
if let hp = haveComponents?.path, let ip = interceptComponents?.path, hp == ip || ("/" == hp + ip) {
if onIntercept(url) {
decisionHandler(.cancel)
}
else {
decisionHandler(.allow)
}
}
}
decisionHandler(.allow)
}
open func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
if "file" != webView.url?.scheme {
showLoadingIndicator()
}
}
open func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if let scheme = interceptComponents?.scheme, "urn" == scheme {
if let path = interceptComponents?.path, path.hasPrefix("ietf:wg:oauth:2.0:oob") {
if let title = webView.title, title.hasPrefix("Success ") {
oauth?.logger?.debug("OAuth2", msg: "Creating redirect URL from document.title")
let qry = title.replacingOccurrences(of: "Success ", with: "")
if let url = URL(string: "http://localhost/?\(qry)") {
_ = onIntercept?(url)
return
}
oauth?.logger?.warn("OAuth2", msg: "Failed to create a URL with query parts \"\(qry)\"")
}
}
}
hideLoadingIndicator()
showHideBackButton(webView.canGoBack)
}
open func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
if NSURLErrorDomain == error._domain && NSURLErrorCancelled == error._code {
return
}
// do we still need to intercept "WebKitErrorDomain" error 102?
if nil != loadingView {
showErrorMessage(error.localizedDescription, animated: true)
}
}
}
#endif
|
apache-2.0
|
bff502c97b16facbba20e55f6361b747
| 28.592885 | 165 | 0.698544 | 3.944679 | false | false | false | false |
Albertorizzoli/ioscreator
|
IOS8SwiftDrawingCirclesTutorial/IOS8SwiftDrawingCirclesTutorial/ViewController.swift
|
37
|
1092
|
//
// ViewController.swift
// IOS8SwiftDrawingCirclesTutorial
//
// Created by Arthur Knopper on 12/10/14.
// Copyright (c) 2014 Arthur Knopper. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.lightGrayColor()
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if let touch = touches as? Set<UITouch> {
// Set the Center of the Circle
var circleCenter = touch.first!.locationInView(view)
// Set a random Circle Radius
var circleWidth = CGFloat(25 + (arc4random() % 50))
var circleHeight = circleWidth
// Create a new CircleView
var circleView = CircleView(frame: CGRectMake(circleCenter.x, circleCenter.y, circleWidth, circleHeight))
view.addSubview(circleView)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
c3a7ff814b6049e620ec29f9a757767d
| 24.395349 | 113 | 0.665751 | 4.727273 | false | false | false | false |
FuckBoilerplate/RxCache
|
watchOS/Pods/RxSwift/RxSwift/Observables/Implementations/Debunce.swift
|
6
|
2774
|
//
// Debunce.swift
// Rx
//
// Created by Krunoslav Zaher on 9/11/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import Foundation
class DebounceSink<O: ObserverType>
: Sink<O>
, ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Element = O.E
typealias ParentType = Debounce<Element>
private let _parent: ParentType
let _lock = NSRecursiveLock()
// state
private var _id = 0 as UInt64
private var _value: Element? = nil
let cancellable = SerialDisposable()
init(parent: ParentType, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let subscription = _parent._source.subscribe(self)
return Disposables.create(subscription, cancellable)
}
func on(_ event: Event<Element>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
switch event {
case .next(let element):
_id = _id &+ 1
let currentId = _id
_value = element
let scheduler = _parent._scheduler
let dueTime = _parent._dueTime
let d = SingleAssignmentDisposable()
self.cancellable.disposable = d
d.setDisposable(scheduler.scheduleRelative(currentId, dueTime: dueTime, action: self.propagate))
case .error:
_value = nil
forwardOn(event)
dispose()
case .completed:
if let value = _value {
_value = nil
forwardOn(.next(value))
}
forwardOn(.completed)
dispose()
}
}
func propagate(_ currentId: UInt64) -> Disposable {
_lock.lock(); defer { _lock.unlock() } // {
let originalValue = _value
if let value = originalValue, _id == currentId {
_value = nil
forwardOn(.next(value))
}
// }
return Disposables.create()
}
}
class Debounce<Element> : Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _dueTime: RxTimeInterval
fileprivate let _scheduler: SchedulerType
init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) {
_source = source
_dueTime = dueTime
_scheduler = scheduler
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = DebounceSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
|
mit
|
e5f9a68389917840b06abfb5a705137a
| 25.663462 | 144 | 0.592499 | 4.684122 | false | false | false | false |
Nihility-Ming/Design_Patterns_In_Objective-C
|
创建型模式/简单工厂模式/Example_02/SimpleFactory/main.swift
|
1
|
321
|
//
// main.swift
// SimpleFactory
//
// Created by Bi Weiming on 15/5/14.
// Copyright (c) 2015年 Bi Weiming. All rights reserved.
//
import Foundation
var op:Operation = OperationFactory.createOperate("+")!
op.numberA = 10.0
op.numberB = 20.0
var result:Double = op.getResult()
println("10.0 + 20.0 = \(result)")
|
apache-2.0
|
909f1e91b9a16a3fa13888bd8cbdad12
| 20.266667 | 56 | 0.677116 | 2.981308 | false | false | false | false |
practicalswift/swift
|
test/SILGen/indirect_enum.swift
|
2
|
25604
|
// RUN: %target-swift-emit-silgen -module-name indirect_enum -Xllvm -sil-print-debuginfo %s | %FileCheck %s
indirect enum TreeA<T> {
case Nil
case Leaf(T)
case Branch(left: TreeA<T>, right: TreeA<T>)
}
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum11TreeA_cases_1l1ryx_AA0C1AOyxGAGtlF : $@convention(thin) <T> (@in_guaranteed T, @guaranteed TreeA<T>, @guaranteed TreeA<T>) -> () {
func TreeA_cases<T>(_ t: T, l: TreeA<T>, r: TreeA<T>) {
// CHECK: bb0([[ARG1:%.*]] : $*T, [[ARG2:%.*]] : @guaranteed $TreeA<T>, [[ARG3:%.*]] : @guaranteed $TreeA<T>):
// CHECK: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type
// CHECK-NEXT: [[NIL:%.*]] = enum $TreeA<T>, #TreeA.Nil!enumelt
// CHECK-NOT: destroy_value [[NIL]]
let _ = TreeA<T>.Nil
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type
// CHECK-NEXT: [[T_BUF:%.*]] = alloc_stack $T
// CHECK-NEXT: copy_addr [[ARG1]] to [initialization] [[T_BUF]] : $*T
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <T>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: copy_addr [take] [[T_BUF]] to [initialization] [[PB]]
// CHECK-NEXT: [[LEAF:%.*]] = enum $TreeA<T>, #TreeA.Leaf!enumelt.1, [[BOX]]
// CHECK-NEXT: destroy_value [[LEAF]]
// CHECK-NEXT: dealloc_stack [[T_BUF]] : $*T
let _ = TreeA<T>.Leaf(t)
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type
// CHECK-NEXT: [[ARG2_COPY:%.*]] = copy_value [[ARG2]]
// CHECK-NEXT: [[ARG3_COPY:%.*]] = copy_value [[ARG3]]
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] : $*(left: TreeA<T>, right: TreeA<T>), 0
// CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] : $*(left: TreeA<T>, right: TreeA<T>), 1
// CHECK-NEXT: store [[ARG2_COPY]] to [init] [[LEFT]]
// CHECK-NEXT: store [[ARG3_COPY]] to [init] [[RIGHT]]
// CHECK-NEXT: [[BRANCH:%.*]] = enum $TreeA<T>, #TreeA.Branch!enumelt.1, [[BOX]]
// CHECK-NEXT: destroy_value [[BRANCH]]
let _ = TreeA<T>.Branch(left: l, right: r)
}
// CHECK: // end sil function '$s13indirect_enum11TreeA_cases_1l1ryx_AA0C1AOyxGAGtlF'
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum16TreeA_reabstractyyS2icF : $@convention(thin) (@guaranteed @callee_guaranteed (Int) -> Int) -> () {
func TreeA_reabstract(_ f: @escaping (Int) -> Int) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed (Int) -> Int):
// CHECK: [[METATYPE:%.*]] = metatype $@thin TreeA<(Int) -> Int>.Type
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <(Int) -> Int>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK: [[THUNK:%.*]] = function_ref @$sS2iIegyd_S2iIegnr_TR
// CHECK-NEXT: [[FN:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[ARG_COPY]])
// CHECK-NEXT: store [[FN]] to [init] [[PB]]
// CHECK-NEXT: [[LEAF:%.*]] = enum $TreeA<(Int) -> Int>, #TreeA.Leaf!enumelt.1, [[BOX]]
// CHECK-NEXT: destroy_value [[LEAF]]
// CHECK: return
let _ = TreeA<(Int) -> Int>.Leaf(f)
}
// CHECK: } // end sil function '$s13indirect_enum16TreeA_reabstractyyS2icF'
enum TreeB<T> {
case Nil
case Leaf(T)
indirect case Branch(left: TreeB<T>, right: TreeB<T>)
}
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum11TreeB_cases_1l1ryx_AA0C1BOyxGAGtlF
func TreeB_cases<T>(_ t: T, l: TreeB<T>, r: TreeB<T>) {
// CHECK: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type
// CHECK: [[NIL:%.*]] = alloc_stack $TreeB<T>
// CHECK-NEXT: inject_enum_addr [[NIL]] : $*TreeB<T>, #TreeB.Nil!enumelt
// CHECK-NEXT: destroy_addr [[NIL]]
// CHECK-NEXT: dealloc_stack [[NIL]]
let _ = TreeB<T>.Nil
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type
// CHECK-NEXT: [[T_BUF:%.*]] = alloc_stack $T
// CHECK-NEXT: copy_addr %0 to [initialization] [[T_BUF]]
// CHECK-NEXT: [[LEAF:%.*]] = alloc_stack $TreeB<T>
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[LEAF]] : $*TreeB<T>, #TreeB.Leaf!enumelt.1
// CHECK-NEXT: copy_addr [take] [[T_BUF]] to [initialization] [[PAYLOAD]]
// CHECK-NEXT: inject_enum_addr [[LEAF]] : $*TreeB<T>, #TreeB.Leaf!enumelt
// CHECK-NEXT: destroy_addr [[LEAF]]
// CHECK-NEXT: dealloc_stack [[LEAF]]
// CHECK-NEXT: dealloc_stack [[T_BUF]]
let _ = TreeB<T>.Leaf(t)
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type
// CHECK-NEXT: [[ARG1_COPY:%.*]] = alloc_stack $TreeB<T>
// CHECK-NEXT: copy_addr %1 to [initialization] [[ARG1_COPY]] : $*TreeB<T>
// CHECK-NEXT: [[ARG2_COPY:%.*]] = alloc_stack $TreeB<T>
// CHECK-NEXT: copy_addr %2 to [initialization] [[ARG2_COPY]] : $*TreeB<T>
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var (left: TreeB<τ_0_0>, right: TreeB<τ_0_0>) } <T>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]]
// CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]]
// CHECK-NEXT: copy_addr [take] [[ARG1_COPY]] to [initialization] [[LEFT]] : $*TreeB<T>
// CHECK-NEXT: copy_addr [take] [[ARG2_COPY]] to [initialization] [[RIGHT]] : $*TreeB<T>
// CHECK-NEXT: [[BRANCH:%.*]] = alloc_stack $TreeB<T>
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[BRANCH]]
// CHECK-NEXT: store [[BOX]] to [init] [[PAYLOAD]]
// CHECK-NEXT: inject_enum_addr [[BRANCH]] : $*TreeB<T>, #TreeB.Branch!enumelt.1
// CHECK-NEXT: destroy_addr [[BRANCH]]
// CHECK-NEXT: dealloc_stack [[BRANCH]]
// CHECK-NEXT: dealloc_stack [[ARG2_COPY]]
// CHECK-NEXT: dealloc_stack [[ARG1_COPY]]
let _ = TreeB<T>.Branch(left: l, right: r)
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum13TreeInt_cases_1l1rySi_AA0cD0OAFtF : $@convention(thin) (Int, @guaranteed TreeInt, @guaranteed TreeInt) -> ()
func TreeInt_cases(_ t: Int, l: TreeInt, r: TreeInt) {
// CHECK: bb0([[ARG1:%.*]] : $Int, [[ARG2:%.*]] : @guaranteed $TreeInt, [[ARG3:%.*]] : @guaranteed $TreeInt):
// CHECK: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type
// CHECK-NEXT: [[NIL:%.*]] = enum $TreeInt, #TreeInt.Nil!enumelt
// CHECK-NOT: destroy_value [[NIL]]
let _ = TreeInt.Nil
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type
// CHECK-NEXT: [[LEAF:%.*]] = enum $TreeInt, #TreeInt.Leaf!enumelt.1, [[ARG1]]
// CHECK-NOT: destroy_value [[LEAF]]
let _ = TreeInt.Leaf(t)
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type
// CHECK-NEXT: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] : $TreeInt
// CHECK-NEXT: [[ARG3_COPY:%.*]] = copy_value [[ARG3]] : $TreeInt
// CHECK-NEXT: [[BOX:%.*]] = alloc_box ${ var (left: TreeInt, right: TreeInt) }
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]]
// CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]]
// CHECK-NEXT: store [[ARG2_COPY]] to [init] [[LEFT]]
// CHECK-NEXT: store [[ARG3_COPY]] to [init] [[RIGHT]]
// CHECK-NEXT: [[BRANCH:%.*]] = enum $TreeInt, #TreeInt.Branch!enumelt.1, [[BOX]]
// CHECK-NEXT: destroy_value [[BRANCH]]
let _ = TreeInt.Branch(left: l, right: r)
}
// CHECK: } // end sil function '$s13indirect_enum13TreeInt_cases_1l1rySi_AA0cD0OAFtF'
enum TreeInt {
case Nil
case Leaf(Int)
indirect case Branch(left: TreeInt, right: TreeInt)
}
enum TrivialButIndirect {
case Direct(Int)
indirect case Indirect(Int)
}
func a() {}
func b<T>(_ x: T) {}
func c<T>(_ x: T, _ y: T) {}
func d() {}
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum11switchTreeAyyAA0D1AOyxGlF : $@convention(thin) <T> (@guaranteed TreeA<T>) -> () {
func switchTreeA<T>(_ x: TreeA<T>) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $TreeA<T>):
// -- x +0
// CHECK: switch_enum [[ARG]] : $TreeA<T>,
// CHECK: case #TreeA.Nil!enumelt: [[NIL_CASE:bb1]],
// CHECK: case #TreeA.Leaf!enumelt.1: [[LEAF_CASE:bb2]],
// CHECK: case #TreeA.Branch!enumelt.1: [[BRANCH_CASE:bb3]],
switch x {
// CHECK: [[NIL_CASE]]:
// CHECK: function_ref @$s13indirect_enum1ayyF
// CHECK: br [[OUTER_CONT:bb[0-9]+]]
case .Nil:
a()
// CHECK: [[LEAF_CASE]]([[LEAF_BOX:%.*]] : @guaranteed $<τ_0_0> { var τ_0_0 } <T>):
// CHECK: [[VALUE:%.*]] = project_box [[LEAF_BOX]]
// CHECK: copy_addr [[VALUE]] to [initialization] [[X:%.*]] : $*T
// CHECK: function_ref @$s13indirect_enum1b{{[_0-9a-zA-Z]*}}F
// CHECK: destroy_addr [[X]]
// CHECK: dealloc_stack [[X]]
// -- x +0
// CHECK: br [[OUTER_CONT]]
case .Leaf(let x):
b(x)
// CHECK: [[BRANCH_CASE]]([[NODE_BOX:%.*]] : @guaranteed $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>):
// CHECK: [[TUPLE_ADDR:%.*]] = project_box [[NODE_BOX]]
// CHECK: [[TUPLE:%.*]] = load_borrow [[TUPLE_ADDR]]
// CHECK: ([[LEFT:%.*]], [[RIGHT:%.*]]) = destructure_tuple [[TUPLE]]
// CHECK: switch_enum [[LEFT]] : $TreeA<T>,
// CHECK: case #TreeA.Leaf!enumelt.1: [[LEAF_CASE_LEFT:bb[0-9]+]],
// CHECK: default [[FAIL_LEFT:bb[0-9]+]]
// CHECK: [[LEAF_CASE_LEFT]]([[LEFT_LEAF_BOX:%.*]] : @guaranteed $<τ_0_0> { var τ_0_0 } <T>):
// CHECK: [[LEFT_LEAF_VALUE:%.*]] = project_box [[LEFT_LEAF_BOX]]
// CHECK: switch_enum [[RIGHT]] : $TreeA<T>,
// CHECK: case #TreeA.Leaf!enumelt.1: [[LEAF_CASE_RIGHT:bb[0-9]+]],
// CHECK: default [[FAIL_RIGHT:bb[0-9]+]]
// CHECK: [[LEAF_CASE_RIGHT]]([[RIGHT_LEAF_BOX:%.*]] : @guaranteed $<τ_0_0> { var τ_0_0 } <T>):
// CHECK: [[RIGHT_LEAF_VALUE:%.*]] = project_box [[RIGHT_LEAF_BOX]]
// CHECK: copy_addr [[LEFT_LEAF_VALUE]]
// CHECK: copy_addr [[RIGHT_LEAF_VALUE]]
// -- x +1
// CHECK: br [[OUTER_CONT]]
// CHECK: [[FAIL_RIGHT]]([[DEFAULT_VAL:%.*]] : @guaranteed
// CHECK: br [[DEFAULT:bb[0-9]+]]
// CHECK: [[FAIL_LEFT]]([[DEFAULT_VAL:%.*]] : @guaranteed
// CHECK: br [[DEFAULT]]
case .Branch(.Leaf(let x), .Leaf(let y)):
c(x, y)
// CHECK: [[DEFAULT]]:
// -- x +0
default:
d()
}
// CHECK: [[OUTER_CONT:%.*]]:
// -- x +0
}
// CHECK: } // end sil function '$s13indirect_enum11switchTreeAyyAA0D1AOyxGlF'
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum11switchTreeB{{[_0-9a-zA-Z]*}}F
func switchTreeB<T>(_ x: TreeB<T>) {
// CHECK: copy_addr %0 to [initialization] [[SCRATCH:%.*]] :
// CHECK: switch_enum_addr [[SCRATCH]]
switch x {
// CHECK: bb{{.*}}:
// CHECK: destroy_addr [[SCRATCH]]
// CHECK: dealloc_stack [[SCRATCH]]
// CHECK: function_ref @$s13indirect_enum1ayyF
// CHECK: br [[OUTER_CONT:bb[0-9]+]]
case .Nil:
a()
// CHECK: bb{{.*}}:
// CHECK: copy_addr [[SCRATCH]] to [initialization] [[LEAF_COPY:%.*]] :
// CHECK: [[LEAF_ADDR:%.*]] = unchecked_take_enum_data_addr [[LEAF_COPY]]
// CHECK: copy_addr [take] [[LEAF_ADDR]] to [initialization] [[LEAF:%.*]] :
// CHECK: function_ref @$s13indirect_enum1b{{[_0-9a-zA-Z]*}}F
// CHECK: destroy_addr [[LEAF]]
// CHECK: dealloc_stack [[LEAF]]
// CHECK-NOT: destroy_addr [[LEAF_COPY]]
// CHECK: dealloc_stack [[LEAF_COPY]]
// CHECK: destroy_addr [[SCRATCH]]
// CHECK: dealloc_stack [[SCRATCH]]
// CHECK: br [[OUTER_CONT]]
case .Leaf(let x):
b(x)
// CHECK: bb{{.*}}:
// CHECK: copy_addr [[SCRATCH]] to [initialization] [[TREE_COPY:%.*]] :
// CHECK: [[TREE_ADDR:%.*]] = unchecked_take_enum_data_addr [[TREE_COPY]]
// -- box +1 immutable
// CHECK: [[BOX:%.*]] = load [take] [[TREE_ADDR]]
// CHECK: [[TUPLE:%.*]] = project_box [[BOX]]
// CHECK: [[LEFT:%.*]] = tuple_element_addr [[TUPLE]]
// CHECK: [[RIGHT:%.*]] = tuple_element_addr [[TUPLE]]
// CHECK: switch_enum_addr [[LEFT]] {{.*}}, default [[LEFT_FAIL:bb[0-9]+]]
// CHECK: bb{{.*}}:
// CHECK: copy_addr [[LEFT]] to [initialization] [[LEFT_COPY:%.*]] :
// CHECK: [[LEFT_LEAF:%.*]] = unchecked_take_enum_data_addr [[LEFT_COPY]] : $*TreeB<T>, #TreeB.Leaf
// CHECK: switch_enum_addr [[RIGHT]] {{.*}}, default [[RIGHT_FAIL:bb[0-9]+]]
// CHECK: bb{{.*}}:
// CHECK: copy_addr [[RIGHT]] to [initialization] [[RIGHT_COPY:%.*]] :
// CHECK: [[RIGHT_LEAF:%.*]] = unchecked_take_enum_data_addr [[RIGHT_COPY]] : $*TreeB<T>, #TreeB.Leaf
// CHECK: copy_addr [take] [[LEFT_LEAF]] to [initialization] [[X:%.*]] :
// CHECK: copy_addr [take] [[RIGHT_LEAF]] to [initialization] [[Y:%.*]] :
// CHECK: function_ref @$s13indirect_enum1c{{[_0-9a-zA-Z]*}}F
// CHECK: destroy_addr [[Y]]
// CHECK: dealloc_stack [[Y]]
// CHECK: destroy_addr [[X]]
// CHECK: dealloc_stack [[X]]
// CHECK-NOT: destroy_addr [[RIGHT_COPY]]
// CHECK: dealloc_stack [[RIGHT_COPY]]
// CHECK-NOT: destroy_addr [[LEFT_COPY]]
// CHECK: dealloc_stack [[LEFT_COPY]]
// -- box +0
// CHECK: destroy_value [[BOX]]
// CHECK-NOT: destroy_addr [[TREE_COPY]]
// CHECK: dealloc_stack [[TREE_COPY]]
// CHECK: destroy_addr [[SCRATCH]]
// CHECK: dealloc_stack [[SCRATCH]]
case .Branch(.Leaf(let x), .Leaf(let y)):
c(x, y)
// CHECK: [[RIGHT_FAIL]]:
// CHECK: destroy_addr [[LEFT_LEAF]]
// CHECK-NOT: destroy_addr [[LEFT_COPY]]
// CHECK: dealloc_stack [[LEFT_COPY]]
// CHECK: destroy_value [[BOX]]
// CHECK-NOT: destroy_addr [[TREE_COPY]]
// CHECK: dealloc_stack [[TREE_COPY]]
// CHECK: br [[INNER_CONT:bb[0-9]+]]
// CHECK: [[LEFT_FAIL]]:
// CHECK: destroy_value [[BOX]]
// CHECK-NOT: destroy_addr [[TREE_COPY]]
// CHECK: dealloc_stack [[TREE_COPY]]
// CHECK: br [[INNER_CONT:bb[0-9]+]]
// CHECK: [[INNER_CONT]]:
// CHECK: destroy_addr [[SCRATCH]]
// CHECK: dealloc_stack [[SCRATCH]]
// CHECK: function_ref @$s13indirect_enum1dyyF
// CHECK: br [[OUTER_CONT]]
default:
d()
}
// CHECK: [[OUTER_CONT]]:
// CHECK: return
}
// Make sure that switchTreeInt obeys ownership invariants.
//
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum13switchTreeInt{{[_0-9a-zA-Z]*}}F
func switchTreeInt(_ x: TreeInt) {
switch x {
case .Nil:
a()
case .Leaf(let x):
b(x)
case .Branch(.Leaf(let x), .Leaf(let y)):
c(x, y)
default:
d()
}
}
// CHECK: } // end sil function '$s13indirect_enum13switchTreeInt{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum10guardTreeA{{[_0-9a-zA-Z]*}}F
func guardTreeA<T>(_ tree: TreeA<T>) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $TreeA<T>):
do {
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO1:bb[0-9]+]]
// CHECK: [[YES]]:
guard case .Nil = tree else { return }
// CHECK: [[X:%.*]] = alloc_stack $T
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO2:bb[0-9]+]]
// CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var τ_0_0 } <T>):
// CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]]
// CHECK: [[TMP:%.*]] = alloc_stack
// CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[TMP]]
// CHECK: copy_addr [take] [[TMP]] to [initialization] [[X]]
// CHECK: destroy_value [[BOX]]
guard case .Leaf(let x) = tree else { return }
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO3:bb[0-9]+]]
// CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>):
// CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]]
// CHECK: [[TUPLE:%.*]] = load_borrow [[VALUE_ADDR]]
// CHECK: [[TUPLE_COPY:%.*]] = copy_value [[TUPLE]]
// CHECK: end_borrow [[TUPLE]]
// CHECK: ([[L:%.*]], [[R:%.*]]) = destructure_tuple [[TUPLE_COPY]]
// CHECK: destroy_value [[BOX]]
guard case .Branch(left: let l, right: let r) = tree else { return }
// CHECK: destroy_value [[R]]
// CHECK: destroy_value [[L]]
// CHECK: destroy_addr [[X]]
}
do {
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO4:bb[0-9]+]]
// CHECK: [[NO4]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: [[YES]]:
// CHECK: br
if case .Nil = tree { }
// CHECK: [[X:%.*]] = alloc_stack $T
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO5:bb[0-9]+]]
// CHECK: [[NO5]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var τ_0_0 } <T>):
// CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]]
// CHECK: [[TMP:%.*]] = alloc_stack
// CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[TMP]]
// CHECK: copy_addr [take] [[TMP]] to [initialization] [[X]]
// CHECK: destroy_value [[BOX]]
// CHECK: destroy_addr [[X]]
if case .Leaf(let x) = tree { }
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>):
// CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]]
// CHECK: [[TUPLE:%.*]] = load_borrow [[VALUE_ADDR]]
// CHECK: [[TUPLE_COPY:%.*]] = copy_value [[TUPLE]]
// CHECK: end_borrow [[TUPLE]]
// CHECK: ([[L:%.*]], [[R:%.*]]) = destructure_tuple [[TUPLE_COPY]]
// CHECK: destroy_value [[BOX]]
// CHECK: destroy_value [[R]]
// CHECK: destroy_value [[L]]
if case .Branch(left: let l, right: let r) = tree { }
}
// CHECK: [[NO3]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: [[NO2]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: [[NO1]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
}
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum10guardTreeB{{[_0-9a-zA-Z]*}}F
func guardTreeB<T>(_ tree: TreeB<T>) {
do {
// CHECK: copy_addr %0 to [initialization] [[TMP1:%.*]] :
// CHECK: switch_enum_addr [[TMP1]] : $*TreeB<T>, case #TreeB.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO2:bb[0-9]+]]
// CHECK: [[YES]]:
// CHECK: destroy_addr [[TMP1]]
guard case .Nil = tree else { return }
// CHECK: [[X:%.*]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[TMP2:%.*]] :
// CHECK: switch_enum_addr [[TMP2]] : $*TreeB<T>, case #TreeB.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO2:bb[0-9]+]]
// CHECK: [[YES]]:
// CHECK: [[VALUE:%.*]] = unchecked_take_enum_data_addr [[TMP2]]
// CHECK: copy_addr [take] [[VALUE]] to [initialization] [[X]]
// CHECK: dealloc_stack [[TMP2]]
guard case .Leaf(let x) = tree else { return }
// CHECK: [[L:%.*]] = alloc_stack $TreeB
// CHECK: [[R:%.*]] = alloc_stack $TreeB
// CHECK: copy_addr %0 to [initialization] [[TMP3:%.*]] :
// CHECK: switch_enum_addr [[TMP3]] : $*TreeB<T>, case #TreeB.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO3:bb[0-9]+]]
// CHECK: [[YES]]:
// CHECK: [[BOX_ADDR:%.*]] = unchecked_take_enum_data_addr [[TMP3]]
// CHECK: [[BOX:%.*]] = load [take] [[BOX_ADDR]]
// CHECK: [[TUPLE_ADDR:%.*]] = project_box [[BOX]]
// CHECK: copy_addr [[TUPLE_ADDR]] to [initialization] [[TUPLE_COPY:%.*]] :
// CHECK: [[L_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]]
// CHECK: copy_addr [take] [[L_COPY]] to [initialization] [[L]]
// CHECK: [[R_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]]
// CHECK: copy_addr [take] [[R_COPY]] to [initialization] [[R]]
// CHECK: destroy_value [[BOX]]
guard case .Branch(left: let l, right: let r) = tree else { return }
// CHECK: destroy_addr [[R]]
// CHECK: destroy_addr [[L]]
// CHECK: destroy_addr [[X]]
}
do {
// CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] :
// CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]:
// CHECK: destroy_addr [[TMP]]
// CHECK: [[YES]]:
// CHECK: destroy_addr [[TMP]]
if case .Nil = tree { }
// CHECK: [[X:%.*]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] :
// CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]:
// CHECK: destroy_addr [[TMP]]
// CHECK: [[YES]]:
// CHECK: [[VALUE:%.*]] = unchecked_take_enum_data_addr [[TMP]]
// CHECK: copy_addr [take] [[VALUE]] to [initialization] [[X]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[X]]
if case .Leaf(let x) = tree { }
// CHECK: [[L:%.*]] = alloc_stack $TreeB
// CHECK: [[R:%.*]] = alloc_stack $TreeB
// CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] :
// CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]:
// CHECK: destroy_addr [[TMP]]
// CHECK: [[YES]]:
// CHECK: [[BOX_ADDR:%.*]] = unchecked_take_enum_data_addr [[TMP]]
// CHECK: [[BOX:%.*]] = load [take] [[BOX_ADDR]]
// CHECK: [[TUPLE_ADDR:%.*]] = project_box [[BOX]]
// CHECK: copy_addr [[TUPLE_ADDR]] to [initialization] [[TUPLE_COPY:%.*]] :
// CHECK: [[L_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]]
// CHECK: copy_addr [take] [[L_COPY]] to [initialization] [[L]]
// CHECK: [[R_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]]
// CHECK: copy_addr [take] [[R_COPY]] to [initialization] [[R]]
// CHECK: destroy_value [[BOX]]
// CHECK: destroy_addr [[R]]
// CHECK: destroy_addr [[L]]
if case .Branch(left: let l, right: let r) = tree { }
}
// CHECK: [[NO3]]:
// CHECK: destroy_addr [[TMP3]]
// CHECK: [[NO2]]:
// CHECK: destroy_addr [[TMP2]]
// CHECK: [[NO1]]:
// CHECK: destroy_addr [[TMP1]]
}
// Just run guardTreeInt through the ownership verifier
//
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum12guardTreeInt{{[_0-9a-zA-Z]*}}F
func guardTreeInt(_ tree: TreeInt) {
do {
guard case .Nil = tree else { return }
guard case .Leaf(let x) = tree else { return }
guard case .Branch(left: let l, right: let r) = tree else { return }
}
do {
if case .Nil = tree { }
if case .Leaf(let x) = tree { }
if case .Branch(left: let l, right: let r) = tree { }
}
}
// SEMANTIC ARC TODO: This test needs to be made far more comprehensive.
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum35dontDisableCleanupOfIndirectPayloadyyAA010TrivialButG0OF : $@convention(thin) (@guaranteed TrivialButIndirect) -> () {
func dontDisableCleanupOfIndirectPayload(_ x: TrivialButIndirect) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $TrivialButIndirect):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TrivialButIndirect, case #TrivialButIndirect.Direct!enumelt.1: [[YES:bb[0-9]+]], case #TrivialButIndirect.Indirect!enumelt.1: [[NO:bb[0-9]+]]
//
guard case .Direct(let foo) = x else { return }
// CHECK: [[YES]]({{%.*}} : $Int):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TrivialButIndirect, case #TrivialButIndirect.Indirect!enumelt.1: [[YES:bb[0-9]+]], case #TrivialButIndirect.Direct!enumelt.1: [[NO2:bb[0-9]+]]
// CHECK: [[YES]]([[BOX:%.*]] : @owned ${ var Int }):
// CHECK: destroy_value [[BOX]]
// CHECK: [[NO2]]({{%.*}} : $Int):
// CHECK-NOT: destroy_value
// CHECK: [[NO]]([[PAYLOAD:%.*]] : @owned ${ var Int }):
// CHECK: destroy_value [[PAYLOAD]]
guard case .Indirect(let bar) = x else { return }
}
// CHECK: } // end sil function '$s13indirect_enum35dontDisableCleanupOfIndirectPayloadyyAA010TrivialButG0OF'
// Make sure that in these cases we do not break any ownership invariants.
class Box<T> {
var value: T
init(_ inputValue: T) { value = inputValue }
}
enum ValueWithInlineStorage<T> {
case inline(T)
indirect case box(Box<T>)
}
func switchValueWithInlineStorage<U>(v: ValueWithInlineStorage<U>) {
switch v {
case .inline:
return
case .box(let box):
return
}
}
func guardValueWithInlineStorage<U>(v: ValueWithInlineStorage<U>) {
do {
guard case .inline = v else { return }
guard case .box(let box) = v else { return }
}
do {
if case .inline = v { return }
if case .box(let box) = v { return }
}
}
|
apache-2.0
|
d25c630c69b7fbd871279b97b57fbb43
| 42.717949 | 185 | 0.546979 | 3.074657 | false | false | false | false |
adamnemecek/AudioKit
|
Sources/AudioKit/Internals/Settings/Settings+iOSVariants.swift
|
1
|
7470
|
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
#if !os(macOS)
import AVFoundation
import Foundation
import os.log
extension Settings {
/// Global audio format AudioKit will default to for new objects and connections
public static var audioFormat = defaultAudioFormat {
didSet {
do {
try AVAudioSession.sharedInstance().setPreferredSampleRate(audioFormat.sampleRate)
} catch {
Log("Could not set preferred sample rate to \(sampleRate) " + error.localizedDescription,
log: OSLog.settings,
type: .error)
}
}
}
/// Whether haptics and system sounds are played while a microphone is setup or recording is active
public static var allowHapticsAndSystemSoundsDuringRecording: Bool = false {
didSet {
if #available(iOS 13.0, tvOS 13.0, *) {
do {
try AVAudioSession.sharedInstance()
.setAllowHapticsAndSystemSoundsDuringRecording(allowHapticsAndSystemSoundsDuringRecording)
} catch {
Log("Could not set allow haptics to \(allowHapticsAndSystemSoundsDuringRecording)" +
error.localizedDescription, log: OSLog.settings, type: .error)
}
}
}
}
/// Enable AudioKit AVAudioSession Category Management
public static var disableAVAudioSessionCategoryManagement: Bool = false
/// The hardware ioBufferDuration. Setting this will request the new value, getting
/// will query the hardware.
public static var ioBufferDuration: Double {
set {
do {
try AVAudioSession.sharedInstance().setPreferredIOBufferDuration(newValue)
} catch {
Log("Could not set the preferred IO buffer duration to \(newValue): \(error)",
log: OSLog.settings,
type: .error)
}
}
get {
return AVAudioSession.sharedInstance().ioBufferDuration
}
}
/// Checks the application's info.plist to see if UIBackgroundModes includes "audio".
/// If background audio is supported then the system will allow the AVAudioEngine to start even if
/// the app is in, or entering, a background state. This can help prevent a potential crash
/// (AVAudioSessionErrorCodeCannotStartPlaying aka error code 561015905) when a route/category change causes
/// AudioEngine to attempt to start while the app is not active and background audio is not supported.
public static let appSupportsBackgroundAudio = (
Bundle.main.infoDictionary?["UIBackgroundModes"] as? [String])?.contains("audio") ?? false
/// Shortcut for AVAudioSession.sharedInstance()
public static let session = AVAudioSession.sharedInstance()
/// Convenience method accessible from Objective-C
public static func setSession(category: SessionCategory, options: UInt) throws {
try setSession(category: category, with: AVAudioSession.CategoryOptions(rawValue: options))
}
/// Set the audio session type
public static func setSession(category: SessionCategory,
with options: AVAudioSession.CategoryOptions = []) throws {
guard Settings.disableAVAudioSessionCategoryManagement == false else { return }
try session.setCategory(category.avCategory, mode: .default, options: options)
// Core Haptics
do {
if #available(iOS 13.0, tvOS 13.0, *) {
try session.setAllowHapticsAndSystemSoundsDuringRecording(
allowHapticsAndSystemSoundsDuringRecording
)
}
} catch {
Log("Could not allow haptics: \(error)", log: OSLog.settings, type: .error)
}
try session.setPreferredIOBufferDuration(bufferLength.duration)
try session.setActive(true)
}
/// Checks if headphones are connected
/// Returns true if headPhones are connected, otherwise return false
public static var headPhonesPlugged: Bool {
let headphonePortTypes: [AVAudioSession.Port] =
[.headphones, .bluetoothHFP, .bluetoothA2DP]
return session.currentRoute.outputs.contains {
headphonePortTypes.contains($0.portType)
}
}
/// Enum of available AVAudioSession Categories
public enum SessionCategory: Int, CustomStringConvertible {
/// Audio silenced by silent switch and screen lock - audio is mixable
case ambient
/// Audio is silenced by silent switch and screen lock - audio is non mixable
case soloAmbient
/// Audio is not silenced by silent switch and screen lock - audio is non mixable
case playback
/// Silences playback audio
case record
/// Audio is not silenced by silent switch and screen lock - audio is non mixable.
/// To allow mixing see AVAudioSessionCategoryOptionMixWithOthers.
case playAndRecord
#if !os(tvOS)
/// Disables playback and recording; deprecated in iOS 10, unavailable on tvOS
case audioProcessing
#endif
/// Use to multi-route audio. May be used on input, output, or both.
case multiRoute
/// Printout string
public var description: String {
switch self {
case .ambient:
return AVAudioSession.Category.ambient.rawValue
case .soloAmbient:
return AVAudioSession.Category.soloAmbient.rawValue
case .playback:
return AVAudioSession.Category.playback.rawValue
case .record:
return AVAudioSession.Category.record.rawValue
case .playAndRecord:
return AVAudioSession.Category.playAndRecord.rawValue
case .multiRoute:
return AVAudioSession.Category.multiRoute.rawValue
#if !os(tvOS)
default:
return AVAudioSession.Category.soloAmbient.rawValue
#endif
}
}
/// AV Audio Session Category
public var avCategory: AVAudioSession.Category {
switch self {
case .ambient:
return .ambient
case .soloAmbient:
return .soloAmbient
case .playback:
return .playback
case .record:
return .record
case .playAndRecord:
return .playAndRecord
case .multiRoute:
return .multiRoute
#if !os(tvOS)
default:
return .soloAmbient
#endif
}
}
}
}
#endif
|
mit
|
b2286b38a144409c7e528cc5bd16f862
| 41.931034 | 118 | 0.568407 | 5.868028 | false | false | false | false |
adamdahan/GraphKit
|
Source/ManagedBond.swift
|
1
|
5276
|
//
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
// #internal
import CoreData
@objc(ManagedBond)
internal class ManagedBond : NSManagedObject {
@NSManaged internal var nodeClass: String
@NSManaged internal var type: String
@NSManaged internal var createdDate: NSDate
@NSManaged internal var propertySet: NSSet
@NSManaged internal var groupSet: NSSet
@NSManaged internal var subject: ManagedEntity?
@NSManaged internal var object: ManagedEntity?
private var context: NSManagedObjectContext?
internal var worker: NSManagedObjectContext? {
if nil == context {
let graph: Graph = Graph()
context = graph.worker
}
return context
}
/**
:name: init
:description: Initializes the Model Object with e a given type.
*/
convenience internal init(type: String!) {
let g: Graph = Graph()
var w: NSManagedObjectContext? = g.worker
self.init(entity: NSEntityDescription.entityForName(GraphUtility.bondDescriptionName, inManagedObjectContext: w!)!, insertIntoManagedObjectContext: w)
nodeClass = "3"
self.type = type
createdDate = NSDate()
propertySet = NSSet()
groupSet = NSSet()
subject = nil
object = nil
context = w
}
/**
:name: properties
:description: Allows for Dictionary style coding, which maps to the internal properties Dictionary.
*/
internal subscript(name: String) -> AnyObject? {
get {
for n in propertySet {
let property: BondProperty = n as! BondProperty
if name == property.name {
return property.object
}
}
return nil
}
set(object) {
if nil == object {
for n in propertySet {
let property: BondProperty = n as! BondProperty
if name == property.name {
property.delete()
let set: NSMutableSet = propertySet as! NSMutableSet
set.removeObject(property)
break
}
}
} else {
var hasProperty: Bool = false
for n in propertySet {
let property: BondProperty = n as! BondProperty
if name == property.name {
hasProperty = true
property.object = object!
break
}
}
if false == hasProperty {
var property: BondProperty = BondProperty(name: name, object: object!)
property.node = self
}
}
}
}
/**
:name: addGroup
:description: Adds a Group name to the list of Groups if it does not exist.
*/
internal func addGroup(name: String!) -> Bool {
if !hasGroup(name) {
var group: BondGroup = BondGroup(name: name)
group.node = self
return true
}
return false
}
/**
:name: hasGroup
:description: Checks whether the Node is a part of the Group name passed or not.
*/
internal func hasGroup(name: String!) -> Bool {
for n in groupSet {
let group: BondGroup = n as! BondGroup
if name == group.name {
return true
}
}
return false
}
/**
:name: removeGroup
:description: Removes a Group name from the list of Groups if it exists.
*/
internal func removeGroup(name: String!) -> Bool {
for n in groupSet {
let group: BondGroup = n as! BondGroup
if name == group.name {
group.delete()
let set: NSMutableSet = groupSet as! NSMutableSet
set.removeObject(group)
return true
}
}
return false
}
/**
:name: delete
:description: Marks the Model Object to be deleted from the Graph.
*/
internal func delete() {
worker?.deleteObject(self)
}
}
extension ManagedBond {
/**
:name: addPropertySetObject
:description: Adds the Property to the propertySet for the Bond.
*/
func addPropertySetObject(value: BondProperty) {
let nodes: NSMutableSet = propertySet as! NSMutableSet
nodes.addObject(value)
}
/**
:name: removePropertySetObject
:description: Removes the Property to the propertySet for the Bond.
*/
func removePropertySetObject(value: BondProperty) {
let nodes: NSMutableSet = propertySet as! NSMutableSet
nodes.removeObject(value)
}
/**
:name: addGroupSetObject
:description: Adds the Group to the groupSet for the Bond.
*/
func addGroupSetObject(value: BondGroup) {
let nodes: NSMutableSet = groupSet as! NSMutableSet
nodes.addObject(value)
}
/**
:name: removeGroupSetObject
:description: Removes the Group to the groupSet for the Bond.
*/
func removeGroupSetObject(value: BondGroup) {
let nodes: NSMutableSet = groupSet as! NSMutableSet
nodes.removeObject(value)
}
}
|
agpl-3.0
|
965b0183e9e50c62a6966b897e7a344e
| 26.336788 | 152 | 0.676649 | 3.876561 | false | false | false | false |
ShunzhiTang/PhotoSelector
|
PhotoSelector/PhotoSelector/TSZPhotoSeletor.swift
|
2
|
7839
|
// TSZPhotoSeletor.swift
// PhotoSelector
// Created by Tsz on 15/10/20.
// Copyright © 2015年 Tsz. All rights reserved.
import UIKit
private let TSZPhotoSelectorIdentify = "TSZPhotoSelectorIdentify"
private let MaxNumberPriture = 9
class TSZPhotoSeletor: UICollectionViewController ,PhotoSelectorViewDelegate{
//照片的数组
lazy var photos: [UIImage] = [UIImage]()
// 当前用户选择照片的索引
private var currentIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
//注册 cell
collectionView?.registerClass(TSZPhotoSelectorCell.self, forCellWithReuseIdentifier: TSZPhotoSelectorIdentify)
collectionView?.backgroundColor = UIColor.whiteColor()
//使用了 一种在内部设置cell的大小 ,定义布局的属性
let layout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout
layout?.itemSize = CGSize(width: 80, height: 80)
//外边距
layout?.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
}
init(){
super.init(collectionViewLayout: UICollectionViewFlowLayout())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: 实现UICollectionViewController 的数据源方法
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (photos.count == MaxNumberPriture) ? photos.count : photos.count + 1
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(TSZPhotoSelectorIdentify, forIndexPath: indexPath) as! TSZPhotoSelectorCell
cell.backgroundColor = UIColor.blueColor()
cell.image = (indexPath.item < photos.count) ? photos[indexPath.item] : nil
cell.photoDelegate = self
return cell
}
//MARK: 照片选择的 协议实现
private func photoSelectorViewCellSelectorPhoto(cell: TSZPhotoSelectorCell) {
print(__FUNCTION__)
//一个参数默认就会删除参数名
if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
print("无法访问图片库")
return
}
//记录当前用户选中的索引
let indexPath = collectionView?.indexPathForCell(cell)
print(indexPath)
currentIndex = indexPath!.item
//实例化图片选择器
let picker = UIImagePickerController()
//自己实现自己的方法
picker.delegate = self
//设置允许编辑
// 设置允许编辑 - 会多一个窗口,让用户缩放照片
// 在实际开发中,如果让用户从照片库选择头像,非常重要!
// 好处:1. 正方形,2. 图像会小
picker.allowsEditing = true
//跳转页面
presentViewController(picker, animated: true, completion: nil)
}
//MARK: 照片删除的 协议实现
private func photoSelectorViewCellRemovePhoto(cell: TSZPhotoSelectorCell) {
//找到对应的cell
let indexPath = collectionView?.indexPathForCell(cell)
photos.removeAtIndex(indexPath!.item)
//刷新数据
collectionView?.reloadData()
}
}
//MARK: - 实现从本机获取图片需要实现
extension TSZPhotoSeletor:UIImagePickerControllerDelegate , UINavigationControllerDelegate{
//根据api显示 一旦实现代理方法 需要 程序员去自己释放
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//图像统一缩放到300宽 , 为了考虑到内存的问题
let imgScale = image.scaleImage(300)
//当前的索引何照片的总数相等
if currentIndex == photos.count{
photos.append(imgScale)
}else {
//如果小于说明是数组中的某一项,
photos[currentIndex] = imgScale
}
//更新collectionView
collectionView?.reloadData()
//记得一定要关闭
dismissViewControllerAnimated(true, completion: nil)
}
}
//MARK: 点击我们的cell ,需要控制器去实现图片选择器
private protocol PhotoSelectorViewDelegate: NSObjectProtocol{
/// MARK: 选择图片
func photoSelectorViewCellSelectorPhoto(cell: TSZPhotoSelectorCell)
//删除图片
func photoSelectorViewCellRemovePhoto(cell: TSZPhotoSelectorCell)
}
//MARK: 自定我们需要的cell
private class TSZPhotoSelectorCell: UICollectionViewCell {
/**
* cell的图像
*/
var image: UIImage? {
didSet{
//判断图片是否为空
if image == nil {
addPhotoButton.setImage("compose_pic_add")
}else{
addPhotoButton.setImage(image, forState: UIControlState.Normal)
}
//MARK - 这一句隐藏删除按钮
removePhotoButton.hidden = (image == nil)
}
}
//MARK: - 构造函数
override init(frame: CGRect) {
super.init(frame: frame)
//设置 显示 UI
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: --- 给出一个接口去实现cell的 协议
weak var photoDelegate: PhotoSelectorViewDelegate?
// MARK: - 实现点击方法
@objc func clickPhoto(){
photoDelegate?.photoSelectorViewCellSelectorPhoto(self)
}
@objc func clickRemove(){
photoDelegate?.photoSelectorViewCellRemovePhoto(self)
}
private func setupUI(){
addSubview(addPhotoButton)
addSubview(removePhotoButton)
//MARK: 显示 添加按钮的 自动布局
addPhotoButton.translatesAutoresizingMaskIntoConstraints = false
removePhotoButton.translatesAutoresizingMaskIntoConstraints = false
//数组
let dict = ["add" : addPhotoButton , "remove" : removePhotoButton]
//布局
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[add]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[add]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[remove]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[remove]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
//MARK: 添加监听方法
addPhotoButton.addTarget(self, action: "clickPhoto", forControlEvents: UIControlEvents.TouchUpInside)
removePhotoButton.addTarget(self, action: "clickRemove", forControlEvents: UIControlEvents.TouchUpInside)
//MARK: - 图片显示的不全,需要修改填充模式
addPhotoButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
}
//MARK: 懒加载两个button
private lazy var addPhotoButton:UIButton = UIButton(imageName: "compose_pic_add")
private lazy var removePhotoButton:UIButton = UIButton(imageName: "compose_photo_close")
}
|
mit
|
ca22be6e135e7ed7445255e826684dc0
| 32.141509 | 162 | 0.650014 | 4.920168 | false | false | false | false |
MitchellPhillips22/TIY-Assignments
|
Day 14/yelqApp/yelqApp/RestaurantsTableViewController.swift
|
1
|
3468
|
//
// RestaurantsTableViewController.swift
// yelqApp
//
// Created by Mitchell Phillips on 2/18/16.
// Copyright © 2016 Mitchell Phillips. All rights reserved.
//
import UIKit
class RestaurantsTableViewController: UITableViewController {
var restaurantArray = [Restaurant]()
var currentRestaurant: Restaurant?
var jsonString = ""
override func viewDidLoad() {
super.viewDidLoad()
let (jsonString, data) = loadJSONFile("restaurantsJSON", fileType: "json")
print(jsonString)
if let data = data {
do {
let object = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
if let dict = object as? JSONDictionary {
if let results = dict["restaurants"] as? JSONArray {
for result in results {
let m = Restaurant(dict: result)
self.restaurantArray.append(m)
}
}
}
for currentRestaurant in restaurantArray {
}
} catch {
print("There is no character")
}
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellForRowRestaurant = self.restaurantArray[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("restaurantCell", forIndexPath: indexPath) as! RestaurantTableViewCell
print(cellForRowRestaurant.location)
cell.restaurantLabel.text = cellForRowRestaurant.name
cell.locationLabel.text = cellForRowRestaurant.location
cell.imageOutlet.image = UIImage(named: "\(cellForRowRestaurant.image)")
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return restaurantArray.count
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.currentRestaurant = restaurantArray[indexPath.row]
self.performSegueWithIdentifier("showDetails", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetails" {
let detailViewController = segue.destinationViewController as! DetailViewController
detailViewController.currentRestaurant = self.currentRestaurant
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100
}
func loadJSONFile(filename: String, fileType: String) -> (String, NSData?) {
var returnString = ""
var data: NSData? = nil
guard let filePath = NSBundle.mainBundle().URLForResource(filename, withExtension: fileType) else { return (returnString, data) }
if let jsondata = NSData(contentsOfURL: filePath) {
if let jsonString = NSString(data: jsondata, encoding: NSUTF8StringEncoding) {
returnString = jsonString as String
data = jsondata
}
}
return (returnString, data)
}
}
|
cc0-1.0
|
52bf3accb5c6b5ce7c89bd7086ebb730
| 34.377551 | 137 | 0.600231 | 5.916382 | false | false | false | false |
carabina/SwiftMock
|
Pod/Classes/MockExpectation.swift
|
1
|
3555
|
//
// MockExpectation.swift
// SwiftMock
//
// Created by Matthew Flint on 13/09/2015.
//
//
import Foundation
public class MockExpectation {
public var functionName: String?
var args: [Any?]
/// the return value for this expectation, if any
public var returnValue: Any?
public init() {
args = [Any?]()
}
public func call<T>(value: T) -> MockActionable<T> {
return MockActionable(value, self)
}
/// record the function name and arguments during the expectation-setting phase
public func acceptExpected(functionName theFunctionName: String, args theArgs: Any?...) -> Bool {
// do we already have a function? if so, we can't accept this call as an expectation
let result = functionName == nil
if result {
functionName = theFunctionName
args = theArgs
}
return result
}
public func isComplete() -> Bool {
return functionName != nil
}
/// offer this function, and its arguments, to the expectation to see if it matches
public func satisfy(functionName theFunctionName: String, args theArgs: Any?...) -> Bool {
return functionName == theFunctionName && match(args, theArgs)
}
func match(firstAnyOptional: Any?, _ secondAnyOptional: Any?) -> Bool {
if firstAnyOptional == nil && secondAnyOptional == nil {
return true
}
if firstAnyOptional == nil || secondAnyOptional == nil {
return false
}
let firstAny = firstAnyOptional!
let secondAny = secondAnyOptional!
// there must be a better way to match two Any? values :-/
var result = false
switch(firstAny) {
case let firstArray as Array<Any?>:
if let secondArray = secondAny as? Array<Any?> {
result = matchArraysOfOptionals(firstArray, secondArray)
}
case let firstArray as Array<Any>:
if let secondArray = secondAny as? Array<Any> {
result = matchArrays(firstArray, secondArray)
}
case let first as String:
if let second = secondAny as? String {
result = first == second
}
case let first as Int:
if let second = secondAny as? Int {
result = first == second
}
case let first as Double:
if let second = secondAny as? Double {
result = first == second
}
case let first as Bool:
if let second = secondAny as? Bool {
result = first == second
}
default: break
}
return result
}
func matchArraysOfOptionals(firstArray: Array<Any?>, _ secondArray: Array<Any?>) -> Bool {
var result = true
if firstArray.count != secondArray.count {
result = false
}
for var index=0; index<firstArray.count && result; index++ {
result = match(firstArray[index], secondArray[index])
}
return result
}
func matchArrays(firstArray: Array<Any>, _ secondArray: Array<Any>) -> Bool {
var result = true
if firstArray.count != secondArray.count {
result = false
}
for var index=0; index<firstArray.count && result; index++ {
result = match(firstArray[index], secondArray[index])
}
return result
}
}
|
mit
|
cb6e981cf6b77b96db7efa4f0bbc4ee5
| 29.655172 | 101 | 0.558931 | 4.74 | false | false | false | false |
JustinM1/S3SignerAWS
|
Sources/S3SignerAWS.swift
|
1
|
14520
|
import Foundation
import OpenCrypto
public class S3SignerAWS {
/// AWS Access Key
private let accessKey: String
/// The region where S3 bucket is located.
public let region: Region
/// AWS Secret Key
private let secretKey: String
/// AWS Security Token. Used to validate temporary credentials, such as those from an EC2 Instance's IAM role
private let securityToken : String? //
/// The service used in calculating the signature. Currently limited to s3, possible expansion to other services after testing.
internal var service: String {
return "s3"
}
/// Initializes a signer which works for either permanent credentials or temporary secrets
///
/// - Parameters:
/// - accessKey: AWS Access Key
/// - secretKey: AWS Secret Key
/// - region: Which AWS region to sign against
/// - securityToken: Optional token used only with temporary credentials
public init(accessKey: String,
secretKey: String,
region: Region,
securityToken: String? = nil)
{
self.accessKey = accessKey
self.secretKey = secretKey
self.region = region
self.securityToken = securityToken
}
/// Generate a V4 auth header for aws Requests.
///
/// - Parameters:
/// - httpMethod: HTTP Method (GET, HEAD, PUT, POST, DELETE)
/// - urlString: Full URL String. Left for ability to customize whether a virtual hosted-style request i.e. "https://exampleBucket.s3.amazonaws.com" vs path-style request i.e. "https://s3.amazonaws.com/exampleBucket". Make sure to include url scheme i.e. https:// or signature will not be calculated properly.
/// - headers: Any additional headers you want incuded in the signature. All the required headers are created automatically.
/// - payload: The payload being sent with request
/// - Returns: The required headers that need to be sent with request. Host, X-Amz-Date, Authorization
/// - If PUT request, Content-Length
/// - if PUT and pathExtension is available, Content-Type
/// - if PUT and not unsigned, Content-md5
/// - Throws: S3SignerError
public func authHeaderV4(
httpMethod: HTTPMethod,
urlString: String,
headers: [String: String] = [:],
payload: Payload)
throws -> [String:String]
{
guard let url = URL(string: urlString) else {
throw S3SignerError.badURL
}
let dates = getDates(date: Date())
let bodyDigest = try payload.hashed()
var updatedHeaders = updateHeaders(
headers: headers,
url: url,
longDate: dates.long,
bodyDigest: bodyDigest)
if httpMethod == .put && payload.isData {
updatedHeaders["content-md5"] = Data(Insecure.MD5.hash(data: [UInt8](payload.data))).base64EncodedString()
}
updatedHeaders["Authorization"] = try generateAuthHeader(
httpMethod: httpMethod,
url: url,
headers: updatedHeaders,
bodyDigest: bodyDigest,
dates: dates)
if httpMethod == .put {
updatedHeaders["Content-Length"] = payload.size()
if url.pathExtension != "" {
updatedHeaders["Content-Type"] = url.pathExtension
}
}
if payload.isUnsigned {
updatedHeaders["x-amz-content-sha256"] = bodyDigest
}
return updatedHeaders
}
/// Generate a V4 pre-signed URL
///
/// - Parameters:
/// - httpMethod: The method of request.
/// - urlString: Full URL String. Left for ability to customize whether a virtual hosted-style request i.e. "https://exampleBucket.s3.amazonaws.com" vs path-style request i.e. "https://s3.amazonaws.com/exampleBucket". Make sure to include url scheme i.e. https:// or signature will not be calculated properly.
/// - expiration: How long the URL is valid.
/// - headers: Any additional headers to be included with signature calculation.
/// - Returns: Pre-signed URL string.
/// - Throws: S3SignerError
public func presignedURLV4(
httpMethod: HTTPMethod,
urlString: String,
expiration: TimeFromNow,
headers: [String:String])
throws -> String
{
guard let url = URL(string: urlString) else {
throw S3SignerError.badURL
}
let dates = getDates(date: Date())
var updatedHeaders = headers
updatedHeaders["Host"] = url.host ?? region.host
let (canonRequest, fullURL) = try presignedURLCanonRequest(httpMethod: httpMethod, dates: dates, expiration: expiration, url: url, headers: updatedHeaders)
let stringToSign = try createStringToSign(canonicalRequest: canonRequest, dates: dates)
let signature = try createSignature(stringToSign: stringToSign, timeStampShort: dates.short)
return fullURL.absoluteString.appending("&X-Amz-Signature=\(signature)")
}
internal func canonicalHeaders(
headers: [String: String])
-> String
{
let headerList = Array(headers.keys)
.map { "\($0.lowercased()):\(headers[$0]!)" }
.filter { $0 != "authorization" }
.sorted(by: { $0.localizedCompare($1) == ComparisonResult.orderedAscending })
.joined(separator: "\n")
.appending("\n")
return headerList
}
internal func createCanonicalRequest(
httpMethod: HTTPMethod,
url: URL,
headers: [String: String],
bodyDigest: String)
throws -> String
{
return try [
httpMethod.rawValue,
path(url: url),
query(url: url),
canonicalHeaders(headers: headers),
signedHeaders(headers: headers),
bodyDigest
].joined(separator: "\n")
}
/// Create signature
///
/// - Parameters:
/// - stringToSign: String to sign.
/// - timeStampShort: Short timestamp.
/// - Returns: Signature.
/// - Throws: HMAC error.
internal func createSignature(
stringToSign: String,
timeStampShort: String)
throws -> String
{
let dateKey = hmacSign(data: timeStampShort, key: Data("AWS4\(secretKey)".utf8))
let dateRegionKey = hmacSign(data: region.value, key: dateKey)
let dateRegionServiceKey = hmacSign(data: service, key: dateRegionKey)
let signingKey = hmacSign(data: "aws4_request", key: dateRegionServiceKey)
let signature = hmacSign(data: stringToSign, key: signingKey)
return signature.hexEncodedString()
}
func hmacSign(data: String, key: Data) -> Data {
let stringToSign = data.data(using: .utf8) ?? Data()
let key = SymmetricKey(data: key)
let hash = HMAC<SHA256>.authenticationCode(for: stringToSign,
using: key)
return Data(hash)
}
/// Create the String To Sign portion of signature.
///
/// - Parameters:
/// - canonicalRequest: The canonical request used.
/// - dates: The dates object containing short and long timestamps of request.
/// - Returns: String to sign.
/// - Throws: If hashing canonical request fails.
internal func createStringToSign(
canonicalRequest: String,
dates: Dates)
throws -> String
{
let canonRequestHash = [UInt8](Data(SHA256.hash(data: [UInt8](canonicalRequest.utf8)))).hexEncodedString()
return ["AWS4-HMAC-SHA256",
dates.long,
credentialScope(timeStampShort: dates.short),
canonRequestHash]
.joined(separator: "\n")
}
/// Credential scope
///
/// - Parameter timeStampShort: Short timestamp.
/// - Returns: Credential Scope.
private func credentialScope(
timeStampShort: String)
-> String
{
return [
timeStampShort,
region.value,
service, "aws4_request"
].joined(separator: "/")
}
/// Generate Auth Header for V4 Authorization Header request.
///
/// - Parameters:
/// - httpMethod: The HTTPMethod of request.
/// - url: The URL of the request.
/// - headers: All headers used in signature calcuation.
/// - bodyDigest: The hashed payload of request.
/// - dates: The short and long timestamps of time of request.
/// - Returns: Authorization header value.
/// - Throws: S3SignerError
internal func generateAuthHeader(
httpMethod: HTTPMethod,
url: URL,
headers: [String:String],
bodyDigest: String,
dates: Dates)
throws -> String
{
let canonicalRequestHex = try createCanonicalRequest(httpMethod: httpMethod, url: url, headers: headers, bodyDigest: bodyDigest)
let stringToSign = try createStringToSign(canonicalRequest: canonicalRequestHex, dates: dates)
let signature = try createSignature(stringToSign: stringToSign, timeStampShort: dates.short)
return "AWS4-HMAC-SHA256 Credential=\(accessKey)/\(credentialScope(timeStampShort: dates.short)), SignedHeaders=\(signedHeaders(headers: headers)), Signature=\(signature)"
}
/// Instantiate Dates object containing the required date formats needed for signature calculation.
///
/// - Parameter date: The date of request.
/// - Returns: Dates object.
internal func getDates(date: Date) -> Dates {
return Dates(date: date)
}
/// The percent encoded path of request URL.
///
/// - Parameter url: The URL of request.
/// - Returns: Percent encoded path if not empty, or "/".
/// - Throws: Encoding error.
private func path(url: URL) throws -> String {
if !url.path.isEmpty, let encodedPath = url.path.percentEncode(.pathAllowed) {
return encodedPath
}
return "/"
}
/// The canonical request for Presigned URL requests.
///
/// - Parameters:
/// - httpMethod: HTTPMethod of request.
/// - dates: Dates formatted for request.
/// - expiration: The period of time before URL expires.
/// - url: The URL of the request.
/// - headers: Headers used to sign and add to presigned URL.
/// - Returns: Canonical request for pre-signed URL.
/// - Throws: S3SignerError
internal func presignedURLCanonRequest(
httpMethod: HTTPMethod,
dates: Dates,
expiration: TimeFromNow,
url: URL,
headers: [String: String])
throws -> (String, URL)
{
let credScope = credentialScope(timeStampShort: dates.short)
let signHeaders = signedHeaders(headers: headers)
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
throw S3SignerError.badURL
}
let defaultParams: [(name: String, value: String)] = [
("X-Amz-Algorithm", "AWS4-HMAC-SHA256"),
("X-Amz-Credential", "\(accessKey)/\(credScope)"),
("X-Amz-Date", "\(dates.long)"),
("X-Amz-Expires", "\(expiration.expiration)"),
("X-Amz-SignedHeaders", "\(signHeaders)")
]
components.queryItems = ((components.queryItems ?? []) + defaultParams.map { URLQueryItem(name: $0.name, value: $0.value) })
.sorted(by: { $0.name < $1.name })
// This should never throw.
guard let url = components.url else {
throw S3SignerError.badURL
}
let encodedQuery = try query(url: url)
components.percentEncodedQuery = encodedQuery
guard let updatedURL = components.url else {
throw S3SignerError.badURL
}
return try (
[
httpMethod.rawValue,
path(url: updatedURL),
encodedQuery,
canonicalHeaders(headers: headers),
signHeaders,
"UNSIGNED-PAYLOAD"
].joined(separator: "\n"),
updatedURL)
}
/// Encode and sort queryItems.
///
/// - Parameter url: The URL for request containing the possible queryItems.
/// - Returns: Encoded and sorted(By Key) queryItem String.
/// - Throws: Encoding Error
internal func query(url: URL) throws -> String {
if let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems {
let encodedItems = queryItems.map { "\($0.name.percentEncode(.queryAllowed) ?? "")=\($0.value?.percentEncode(.queryAllowed) ?? "")" }
return encodedItems.sorted().joined(separator: "&")
}
return ""
}
/// Signed headers
///
/// - Parameter headers: Headers to sign.
/// - Returns: Signed headers.
private func signedHeaders(headers: [String: String]) -> String {
let headerList = Array(headers.keys).map { $0.lowercased() }.filter { $0 != "authorization" }.sorted().joined(separator: ";")
return headerList
}
/// Add the required headers to a V4 authorization header request.
///
/// - Parameters:
/// - headers: Original headers to add the additional required headers to.
/// - url: The URL of the request.
/// - longDate: The formatted ISO date.
/// - bodyDigest: The payload hash of request.
/// - Returns: Updated headers with additional required headers.
internal func updateHeaders(
headers: [String:String],
url: URL,
longDate: String,
bodyDigest: String)
-> [String:String]
{
var updatedHeaders = headers
updatedHeaders["X-Amz-Date"] = longDate
updatedHeaders["Host"] = url.host ?? region.host
if bodyDigest != "UNSIGNED-PAYLOAD" && service == "s3" {
updatedHeaders["x-amz-content-sha256"] = bodyDigest
}
// According to http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html#RequestWithSTS
if let token = securityToken {
updatedHeaders["X-Amz-Security-Token"] = token
}
return updatedHeaders
}
}
|
mit
|
f5bd7c7cdc49d89293415bfe8886ef25
| 36.714286 | 315 | 0.597865 | 4.634536 | false | false | false | false |
eurofurence/ef-app_ios
|
Packages/EurofurenceComponents/Tests/TutorialComponentTests/Test Doubles/CapturingTutorialPageScene.swift
|
1
|
2089
|
import Foundation
import TutorialComponent
import UIKit
class CapturingTutorialPageSceneDelegate: TutorialPageSceneDelegate {
private(set) var primaryActionButtonTapped = false
func tutorialPageSceneDidTapPrimaryActionButton(_ tutorialPageScene: TutorialPageScene) {
primaryActionButtonTapped = true
}
private(set) var secondaryActionButtonTapped = false
func tutorialPageSceneDidTapSecondaryActionButton(_ tutorialPageScene: TutorialPageScene) {
secondaryActionButtonTapped = true
}
}
class CapturingTutorialPageScene: TutorialPageScene {
var tutorialPageSceneDelegate: TutorialPageSceneDelegate?
private(set) var capturedPageTitle: String?
func showPageTitle(_ title: String?) {
capturedPageTitle = title
}
private(set) var capturedPageDescription: String?
func showPageDescription(_ description: String?) {
capturedPageDescription = description
}
private(set) var capturedPageImage: UIImage?
func showPageImage(_ image: UIImage?) {
capturedPageImage = image
}
private(set) var didShowPrimaryActionButton = false
func showPrimaryActionButton() {
didShowPrimaryActionButton = true
}
private(set) var capturedPrimaryActionDescription: String?
func showPrimaryActionDescription(_ primaryActionDescription: String) {
capturedPrimaryActionDescription = primaryActionDescription
}
private(set) var didShowSecondaryActionButton = false
func showSecondaryActionButton() {
didShowSecondaryActionButton = true
}
private(set) var capturedSecondaryActionDescription: String?
func showSecondaryActionDescription(_ secondaryActionDescription: String) {
capturedSecondaryActionDescription = secondaryActionDescription
}
func simulateTappingPrimaryActionButton() {
tutorialPageSceneDelegate?.tutorialPageSceneDidTapPrimaryActionButton(self)
}
func simulateTappingSecondaryActionButton() {
tutorialPageSceneDelegate?.tutorialPageSceneDidTapSecondaryActionButton(self)
}
}
|
mit
|
6a0b108f961d0fe55965cb63b8a69123
| 30.651515 | 95 | 0.762566 | 5.497368 | false | false | false | false |
kdw9/TIY-Assignments
|
Forecaster/Forecaster/APIController.swift
|
1
|
3076
|
//
// APIController.swift
// Forecaster
//
// Created by Keron Williams on 11/2/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import Foundation
class APIController
{
//1.) this is the bridge of communication from the protocol the this current class
var delegator : APIControllerProtocol
init(delegate: APIControllerProtocol)
{
self.delegator = delegate
}
func googleLocationAp(zipcodeSearchTerm: String)
{
let google = zipcodeSearchTerm.stringByReplacingOccurrencesOfString(" " , withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
if let googleL = google.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet())
{
let url: String = "https://maps.googleapis.com/maps/api/geocode/json?components=postal_code:"+googleL+"&sensor=false"
let NSurl = NSURL(string: url)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(NSurl!, completionHandler: { (data, response, error) -> Void in
print("Completed Task Google")
if error != nil
{
print(error!.localizedDescription)
}
else
{
if let dictionary = self.parseJSON(data!)
{
if let results: NSArray = dictionary["results"] as? NSArray
{
if let result = results[0] as? NSDictionary
{
let address = result["formatted_address"] as! String
let cityName = address.componentsSeparatedByString(",")[0]
if let geometry = result["geometry"] as? NSDictionary
{
if let location = geometry ["location"] as?NSDictionary
{
let area = location["lat"] as! Double
let areaTwo = location["lng"] as! Double
let city = City(cityName: cityName, zip: zipcodeSearchTerm, lat: area, lng: areaTwo)
self.delegator.cityWasFound(city)
}
}
}
}
}
}
})
task.resume()
}
}
func parseJSON(data:NSData) -> NSDictionary?
{
do
{
let dictionary: NSDictionary! = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! NSDictionary; return dictionary
}
catch let error as NSError
{
print(error)
return nil
}
}
}
|
cc0-1.0
|
55297ca3e86a36f4fcf1e3c78b7f9f71
| 32.423913 | 164 | 0.47935 | 6.125498 | false | false | false | false |
mozilla-mobile/focus-ios
|
Blockzilla/Tracking Protection/TrackingProtectionViewController.swift
|
1
|
17270
|
/* 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 SnapKit
import UIKit
import Telemetry
import Glean
import Combine
import UIHelpers
import Onboarding
enum SectionType: Int, Hashable {
case tip
case secure
case enableTrackers
case trackers
case stats
}
class TrackingProtectionViewController: UIViewController {
var tooltipHeight: Constraint?
// MARK: - Data source
lazy var dataSource = DataSource(
tableView: self.tableView,
cellProvider: { tableView, indexPath, itemIdentifier in
return itemIdentifier.configureCell(tableView, indexPath)
},
headerForSection: { section in
switch section {
case .trackers:
return UIConstants.strings.trackersHeader.uppercased()
case .tip, .secure, .enableTrackers, .stats:
return nil
}
},
footerForSection: { [trackingProtectionItem] section in
switch section {
case .enableTrackers:
return trackingProtectionItem.settingsValue ? UIConstants.strings.trackingProtectionOn : UIConstants.strings.trackingProtectionOff
case .tip, .secure, .trackers, .stats:
return nil
}
})
// MARK: - Toggles items
private lazy var trackingProtectionItem = ToggleItem(
label: UIConstants.strings.trackingProtectionToggleLabel,
settingsKey: SettingsToggle.trackingProtection
)
private lazy var toggleItems = [
ToggleItem(label: UIConstants.strings.labelBlockAds2, settingsKey: .blockAds),
ToggleItem(label: UIConstants.strings.labelBlockAnalytics, settingsKey: .blockAnalytics),
ToggleItem(label: UIConstants.strings.labelBlockSocial, settingsKey: .blockSocial)
]
private let blockOtherItem = ToggleItem(label: UIConstants.strings.labelBlockOther, settingsKey: .blockOther)
// MARK: - Sections
func secureConnectionSectionItems(title: String, image: UIImage) -> [SectionItem] {
[
SectionItem(configureCell: { _, _ in
ImageCell(image: image, title: title)
})
]
}
lazy var tooltipSectionItems = [
SectionItem(configureCell: { [unowned self] tableView, indexPath in
let cell = TooltipTableViewCell(title: UIConstants.strings.tooltipTitleTextForPrivacy, body: UIConstants.strings.tooltipBodyTextForPrivacy)
cell.delegate = self
return cell
})
]
lazy var enableTrackersSectionItems = [
SectionItem(
configureCell: { [unowned self] tableView, indexPath in
let cell = SwitchTableViewCell(
item: self.trackingProtectionItem,
reuseIdentifier: "SwitchTableViewCell"
)
cell.valueChanged.sink { [unowned self] isOn in
self.trackingProtectionItem.settingsValue = isOn
self.toggleProtection(isOn: isOn)
if isOn {
var snapshot = self.dataSource.snapshot()
snapshot.insertSections([.trackers], afterSection: .enableTrackers)
snapshot.appendItems(self.trackersSectionItems, toSection: .trackers)
self.dataSource.apply(snapshot, animatingDifferences: true)
snapshot.reloadSections([.enableTrackers])
self.dataSource.apply(snapshot, animatingDifferences: false)
} else {
var snapshot = self.dataSource.snapshot()
snapshot.deleteSections([.trackers])
snapshot.reloadSections([.enableTrackers])
self.dataSource.apply(snapshot, animatingDifferences: true)
}
self.calculatePreferredSize()
}
.store(in: &self.subscriptions)
return cell
}
)
]
lazy var trackersSectionItems = toggleItems.map { toggleItem in
SectionItem(
configureCell: { [unowned self] _, _ in
let cell = SwitchTableViewCell(item: toggleItem, reuseIdentifier: "SwitchTableViewCell")
cell.valueChanged.sink { isOn in
toggleItem.settingsValue = isOn
self.updateTelemetry(toggleItem.settingsKey, isOn)
GleanMetrics
.TrackingProtection
.trackerSettingChanged
.record(.init(
isEnabled: isOn,
sourceOfChange: self.sourceOfChange,
trackerChanged: toggleItem.settingsKey.trackerChanged)
)
}
.store(in: &self.subscriptions)
return cell
}
)
}
+
[
SectionItem(
configureCell: { [unowned self] _, _ in
let cell = SwitchTableViewCell(item: blockOtherItem, reuseIdentifier: "SwitchTableViewCell")
cell.valueChanged.sink { [unowned self] isOn in
if isOn {
let alertController = UIAlertController(title: nil, message: UIConstants.strings.settingsBlockOtherMessage, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: UIConstants.strings.settingsBlockOtherNo, style: .default) { [unowned self] _ in
// TODO: Make sure to reset the toggle
cell.isOn = false
self.blockOtherItem.settingsValue = false
self.updateTelemetry(self.blockOtherItem.settingsKey, false)
GleanMetrics
.TrackingProtection
.trackerSettingChanged
.record(.init(
isEnabled: false,
sourceOfChange: self.sourceOfChange,
trackerChanged: self.blockOtherItem.settingsKey.trackerChanged
))
})
alertController.addAction(UIAlertAction(title: UIConstants.strings.settingsBlockOtherYes, style: .destructive) { [unowned self] _ in
self.blockOtherItem.settingsValue = true
self.updateTelemetry(self.blockOtherItem.settingsKey, true)
GleanMetrics
.TrackingProtection
.trackerSettingChanged
.record(.init(
isEnabled: true,
sourceOfChange: self.sourceOfChange,
trackerChanged: self.blockOtherItem.settingsKey.trackerChanged
))
})
self.present(alertController, animated: true, completion: nil)
} else {
self.blockOtherItem.settingsValue = isOn
self.updateTelemetry(blockOtherItem.settingsKey, isOn)
GleanMetrics
.TrackingProtection
.trackerSettingChanged
.record(.init(
isEnabled: isOn,
sourceOfChange: self.sourceOfChange,
trackerChanged: blockOtherItem.settingsKey.trackerChanged
))
}
}
.store(in: &self.subscriptions)
return cell
}
)
]
lazy var statsSectionItems = [
SectionItem(
configureCell: { [unowned self] _, _ in
SubtitleCell(
title: String(format: UIConstants.strings.trackersBlockedSince, self.getAppInstallDate()),
subtitle: self.getNumberOfTrackersBlocked()
)
}
)
]
// MARK: - Views
private var headerHeight: Constraint?
private lazy var header = TrackingHeaderView()
private lazy var tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: .insetGrouped)
tableView.separatorStyle = .singleLine
tableView.tableFooterView = UIView()
tableView.register(SwitchTableViewCell.self)
return tableView
}()
weak var delegate: TrackingProtectionDelegate?
private var modalDelegate: ModalDelegate?
private var sourceOfChange: String {
if case .settings = state { return "Settings" } else { return "Panel" }
}
private var subscriptions = Set<AnyCancellable>()
private var trackersSectionIndex: Int {
if case .browsing = state { return 2 } else { return 1 }
}
private var tableViewTopInset: CGFloat {
if case .settings = state { return 0 } else { return UIConstants.layout.trackingProtectionTableViewTopInset }
}
var state: TrackingProtectionState
let favIconPublisher: AnyPublisher<URL?, Never>?
private let onboardingEventsHandler: OnboardingEventsHandling
private var cancellable: AnyCancellable?
// MARK: - VC Lifecycle
init(state: TrackingProtectionState, onboardingEventsHandler: OnboardingEventsHandling, favIconPublisher: AnyPublisher<URL?, Never>? = nil) {
self.state = state
self.onboardingEventsHandler = onboardingEventsHandler
self.favIconPublisher = favIconPublisher
super.init(nibName: nil, bundle: nil)
dataSource.defaultRowAnimation = .middle
var snapshot = NSDiffableDataSourceSnapshot<SectionType, SectionItem>()
if case let .browsing(browsingStatus) = state {
let title = browsingStatus.isSecureConnection ? UIConstants.strings.connectionSecure : UIConstants.strings.connectionNotSecure
let image = browsingStatus.isSecureConnection ? UIImage.connectionSecure : .connectionNotSecure
let secureSectionItems = self.secureConnectionSectionItems(title: title, image: image)
snapshot.appendSections([.secure])
snapshot.appendItems(secureSectionItems, toSection: .secure)
}
snapshot.appendSections([.enableTrackers])
snapshot.appendItems(enableTrackersSectionItems, toSection: .enableTrackers)
if self.trackingProtectionItem.settingsValue {
snapshot.appendSections([.trackers])
snapshot.appendItems(trackersSectionItems, toSection: .trackers)
}
snapshot.appendSections([.stats])
snapshot.appendItems(statsSectionItems, toSection: .stats)
dataSource.apply(snapshot, animatingDifferences: false)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = UIConstants.strings.trackingProtectionLabel
navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.primaryText]
navigationController?.navigationBar.tintColor = .accent
if case .settings = state {
let doneButton = UIBarButtonItem(title: UIConstants.strings.done, style: .plain, target: self, action: #selector(doneTapped))
doneButton.tintColor = .accent
navigationItem.rightBarButtonItem = doneButton
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for:.default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.layoutIfNeeded()
self.navigationController?.navigationBar.isTranslucent = false
onboardingEventsHandler.send(.showTrackingProtection)
cancellable = onboardingEventsHandler
.routePublisher
.sink { [unowned self] route in
switch route {
case .none:
var snapshot = dataSource.snapshot()
snapshot.deleteSections([.tip])
dataSource.apply(snapshot, animatingDifferences: true)
case .trackingProtection:
var snapshot = dataSource.snapshot()
snapshot.insertSections([.tip], beforeSection: .enableTrackers)
snapshot.appendItems(tooltipSectionItems, toSection: .tip)
dataSource.apply(snapshot)
default:
break
}
}
}
if case let .browsing(browsingStatus) = state,
let baseDomain = browsingStatus.url.baseDomain {
view.addSubview(header)
header.snp.makeConstraints { make in
self.headerHeight = make.height.equalTo(UIConstants.layout.trackingProtectionHeaderHeight).constraint
make.leading.trailing.equalToSuperview()
make.top.equalTo(view.safeAreaLayoutGuide).offset(UIConstants.layout.trackingProtectionHeaderTopOffset)
}
if let publisher = favIconPublisher {
header.configure(domain: baseDomain, publisher: publisher)
}
}
view.addSubview(tableView)
tableView.snp.makeConstraints { make in
if case .browsing = state {
make.top.equalTo(header.snp.bottom)
} else {
make.top.equalTo(view).inset(self.tableViewTopInset)
}
make.leading.trailing.equalTo(self.view)
make.bottom.equalTo(self.view)
}
}
private func calculatePreferredSize() {
guard state != .settings else { return }
preferredContentSize = CGSize(
width: tableView.contentSize.width,
height: tableView.contentSize.height + (headerHeight?.layoutConstraints[0].constant ?? .zero)
)
if UIDevice.current.userInterfaceIdiom == .pad {
self.presentingViewController?.presentedViewController?.preferredContentSize = CGSize(
width: tableView.contentSize.width,
height: tableView.contentSize.height + (headerHeight?.layoutConstraints[0].constant ?? .zero)
)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
calculatePreferredSize()
}
@objc private func doneTapped() {
onboardingEventsHandler.route = nil
self.dismiss(animated: true, completion: nil)
}
fileprivate func updateTelemetry(_ settingsKey: SettingsToggle, _ isOn: Bool) {
let telemetryEvent = TelemetryEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.change, object: "setting", value: settingsKey.rawValue)
telemetryEvent.addExtra(key: "to", value: isOn)
Telemetry.default.recordEvent(telemetryEvent)
Settings.set(isOn, forToggle: settingsKey)
ContentBlockerHelper.shared.reload()
}
private func getAppInstallDate() -> String {
let urlToDocumentsFolder = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
if let installDate = (try! FileManager.default.attributesOfItem(atPath: urlToDocumentsFolder.path)[FileAttributeKey.creationDate]) as? Date {
let stringDate = dateFormatter.string(from: installDate)
return stringDate
}
return dateFormatter.string(from: Date())
}
private func getNumberOfTrackersBlocked() -> String {
let numberOfTrackersBlocked = NSNumber(integerLiteral: UserDefaults.standard.integer(forKey: BrowserViewController.userDefaultsTrackersBlockedKey))
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter.string(from: numberOfTrackersBlocked) ?? "0"
}
private func toggleProtection(isOn: Bool) {
let telemetryEvent = TelemetryEvent(
category: TelemetryEventCategory.action,
method: TelemetryEventMethod.change,
object: "setting",
value: SettingsToggle.trackingProtection.rawValue
)
telemetryEvent.addExtra(key: "to", value: isOn)
Telemetry.default.recordEvent(telemetryEvent)
GleanMetrics.TrackingProtection.trackingProtectionChanged.record(.init(isEnabled: isOn))
GleanMetrics.TrackingProtection.hasEverChangedEtp.set(true)
delegate?.trackingProtectionDidToggleProtection(enabled: isOn)
}
}
extension TrackingProtectionViewController: TooltipViewDelegate {
func didTapTooltipDismissButton() {
onboardingEventsHandler.route = nil
}
}
|
mpl-2.0
|
f08383d6e7eba4ccda0200cea8fc0ef7
| 42.175 | 169 | 0.604806 | 5.820694 | false | false | false | false |
kences/swift_weibo
|
Swift-SinaWeibo/Classes/Module/Compose/Controller/LGComposeViewController.swift
|
1
|
12827
|
//
// LGComposeViewController.swift
// Swift-SinaWeibo
//
// Created by lu on 15/11/4.
// Copyright © 2015年 lg. All rights reserved.
//
import UIKit
import SVProgressHUD
class LGComposeViewController: UIViewController
{
/// toolBar的约束
var toolBarCon: NSLayoutConstraint?
/// 图片选择器的底部约束
var photoSelectorCon: NSLayoutConstraint?
/// 发送微博可以输入的最大字数
let maxNumber = 20
override func viewDidLoad()
{
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor()
// 准备UI
prepareUI()
// 监听键盘的通知
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
}
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
// 当图片选择器不在屏幕上的时候才弹出键盘
if photoSelectorCon?.constant != 0 {
textView.becomeFirstResponder()
}
}
// MARK: - 通知
func keyboardWillChangeFrame(notification: NSNotification)
{
// print("\(notification)")
// 获取键盘弹出后的frame
let endFrame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
// 获取动画时间
let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
// 修改toolBar的约束
toolBarCon?.constant = -(UIScreen.height() - endFrame.origin.y)
// 执行动画
UIView.animateWithDuration(duration) { () -> Void in
self.view.layoutIfNeeded()
}
}
deinit
{
// 移除通知
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - 准备UI
/// 准备UI
private func prepareUI()
{
// 注意添加顺序
view.addSubview(textView)
view.addSubview(photoSelectorVC.view)
view.addSubview(toolBar)
view.addSubview(statusContentLeft)
// 1.设置导航
setupNavigationBar()
// 3.输入文本内容的textView
setupTextView()
// 5.照片选择器
setupPhotoSelector()
// 2.设置底部的toolBar
setupToolBar()
// 4.微博内容剩余字数
setupStatusContentLeft()
}
/// 输入文本内容的textView
private func setupTextView()
{
// 约束
textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil)
}
/// 设置底部的toolBar
private func setupToolBar()
{
// 添加约束
let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.width(), height: 44))
// 获取底部约束
toolBarCon = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
// 添加toolBar的item
// MARK: important
// 数组中存放图片名称 和 响应事件的方法名.这种做法的好处就是可以遍历(快速)该数组,从中取出相应的值的创建按钮,而且按钮的方法也是固定的,日后如果想调整这些按钮的位置,直接调整这个数组就可以了,而方法和图片名都不用修改
let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
["imageName": "compose_trendbutton_background", "action": "trend"],
["imageName": "compose_mentionbutton_background", "action": "mention"],
["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
["imageName": "compose_addbutton_background", "action": "add"]]
var items = [UIBarButtonItem]()
for setting in itemSettings {
// 创建item
let item = UIBarButtonItem(imageName: setting["imageName"]!)
// 取出UIBarButtonItem中的按钮,添加点击事件
let button = item.customView as! UIButton
button.addTarget(self, action: Selector(setting["action"]!), forControlEvents: UIControlEvents.TouchUpInside)
// 添加弹簧
let bounce = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
items.append(item)
items.append(bounce)
}
// 去掉最后一个弹簧
items.removeLast()
// 添加到toolBar上
toolBar.items = items
}
/// 设置导航按钮
private func setupNavigationBar()
{
// 导航栏左按钮
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
// 导航栏右按钮
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
navigationItem.rightBarButtonItem?.enabled = false
// titleView
navigationItem.titleView = setupTitleView()
}
/// 设置titleView
private func setupTitleView() -> UIView
{
let label = UILabel()
label.numberOfLines = 0
label.textAlignment = NSTextAlignment.Center
label.font = UIFont.systemFontOfSize(14)
let name = LGUserAccount.loadUserAccount()?.name ?? "没有昵称"
let str = "发送微博\n\(name)"
// 可变属性字符串
let attrStr = NSMutableAttributedString(string: str)
let range = (str as NSString).rangeOfString(name)
attrStr.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(12), NSForegroundColorAttributeName: UIColor.grayColor()], range: range)
label.attributedText = attrStr
label.sizeToFit()
return label
}
/// 微博内容剩余字数
private func setupStatusContentLeft()
{
statusContentLeft.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil, offset: CGPoint(x: -8, y: -8))
}
/// 设置图片选择器
private func setupPhotoSelector()
{
let psView = photoSelectorVC.view
// 约束
psView.translatesAutoresizingMaskIntoConstraints = false
let views = ["psView": psView]
// 左右
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[psView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
// 高 = view.height * 0.6
view.addConstraint(NSLayoutConstraint(item: psView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Height, multiplier: 0.6, constant: 0))
// 底部:默认不显示在屏幕上
photoSelectorCon = NSLayoutConstraint(item: psView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: view.bounds.height * 0.6)
view.addConstraint(photoSelectorCon!)
}
// MARK: - toolBar按钮的响应事件
/// 图片选择器
@objc private func picture()
{
// 让图片选择器显示出来
photoSelectorCon?.constant = 0
if textView.isFirstResponder() {
textView.resignFirstResponder()
} else {
textView.becomeFirstResponder()
}
UIView.animateWithDuration(0.25) { () -> Void in
self.view.layoutIfNeeded()
}
}
/// #
@objc private func trend()
{
print("#")
}
/// @
@objc private func mention()
{
print("@")
}
/// 点击表情按钮
/*
// MARK: important
在 切换键盘 方法里面打印 textView.inputView, 在键盘弹出时 textView.inputView == nil 弹出的是系统键盘
设置 textView 的键盘为自定义键盘 textView.inputView = emoticonVC.view,发现键盘在显示的时候不能切换,需要将它先退下,再呼出来
*/
@objc private func emoticon()
{
textView.resignFirstResponder()
// USEC_PER_SEC: 毫秒
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
// 切换系统键盘和表情键盘s
self.textView.inputView = self.textView.inputView == nil ? self.emoticonVC.view : nil
self.textView.becomeFirstResponder()
})
}
/// +
@objc private func add()
{
print("+")
}
// MARK: - 导航栏按钮响应
/// 发送
@objc private func send()
{
sendStatus()
}
/** 发送微博 */
private func sendStatus()
{
// 获取文本
let status = textView.emoticonText()
if status.characters.count > maxNumber {
SVProgressHUD.showErrorWithStatus("发送的微博字数超出", maskType: SVProgressHUDMaskType.Black)
return
}
// 获取配图
let image = photoSelectorVC.photoes.first
SVProgressHUD.showWithStatus("正在发布...", maskType: SVProgressHUDMaskType.Black)
// 发送微博
LGNetworkTool.sharedInstance.sendStatus(status, image: image) { (result, error) -> () in
if error != nil {
print("sendStatusError: \(error)")
SVProgressHUD.showErrorWithStatus("网路繁忙..")
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
self.dismiss()
})
return
}
// 成功
SVProgressHUD.showSuccessWithStatus("你的微博已发布")
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
self.dismiss()
})
}
}
/// 退出当前控制器
@objc private func dismiss()
{
SVProgressHUD.dismiss()
textView.resignFirstResponder()
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - 懒加载
/// 底部的toolBar
private lazy var toolBar: UIToolbar = {
let toolBar = UIToolbar()
toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
return toolBar
}()
/// 输入文本内容的textView
private lazy var textView: LGPlaceholderTextView = {
let textView = LGPlaceholderTextView()
// 指定代理
textView.delegate = self
// 字体
textView.font = UIFont.systemFontOfSize(18)
textView.placeholder = "发现新鲜事"
// 设置偏移使输入文字就显示在导航栏下面
// textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
// 垂直方向有滚动回弹效果
textView.bounces = true
textView.alwaysBounceVertical = true
// 当拖拽的时候辞去键盘
textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
return textView
}()
/// 表情键盘
private lazy var emoticonVC: LGEmoticonViewController = {
let vc = LGEmoticonViewController()
// 定义表情键盘所工作的textView
vc.textView = self.textView
return vc
}()
/// 显示发微博剩余的字数
private lazy var statusContentLeft: UILabel = {
let label = UILabel(fontsize: 12, textColor: UIColor.lightGrayColor())
label.text = "\(self.maxNumber)"
label.sizeToFit()
return label
}()
/// 图片选择器
private lazy var photoSelectorVC: LGPhotoSelectorViewController = {
let vc = LGPhotoSelectorViewController()
self.addChildViewController(vc)
return vc
}()
}
// MARK: - UITextViewDelegate 代理方法
extension LGComposeViewController: UITextViewDelegate
{
func textViewDidChange(textView: UITextView)
{
navigationItem.rightBarButtonItem?.enabled = textView.hasText()
// 发送微博剩余字数
let text = textView.emoticonText()
let leftCount = maxNumber-text.characters.count
statusContentLeft.text = "\(maxNumber-text.characters.count)"
// 设置显示的颜色
statusContentLeft.textColor = leftCount >= 0 ? UIColor.lightGrayColor() : UIColor.redColor()
}
}
|
apache-2.0
|
f8ae7633a48059f19757e0957b507651
| 30.917355 | 233 | 0.605127 | 4.686893 | false | false | false | false |
jkereako/NavigationControllerAsMenu
|
Source/ContextMenuPresentationAnimator.swift
|
1
|
1577
|
//
// MenuPresentationAnimator.swift
// NavigationControllerAsMenu
//
// Created by Jeffrey Kereakoglow on 2/29/16.
// Copyright © 2016 Alexis Digital. All rights reserved.
//
import UIKit
class ContextMenuPresentationAnimator: NSObject {}
// MARK: - UIViewControllerAnimatedTransitioning
extension ContextMenuPresentationAnimator: UIViewControllerAnimatedTransitioning {
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?)
-> NSTimeInterval {
return 0.5
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let to = transitionContext.viewForKey(UITransitionContextToViewKey)
let from = transitionContext.viewForKey(UITransitionContextFromViewKey)
UIScreen.mainScreen().bounds.height
let endFrame = CGRect(
x: UIScreen.mainScreen().bounds.width * 0.25,
y: 0,
width: UIScreen.mainScreen().bounds.width * 0.75,
height: UIScreen.mainScreen().bounds.height
)
from?.userInteractionEnabled = false
transitionContext.containerView()?.addSubview(from ?? UIView())
transitionContext.containerView()?.addSubview(to ?? UIView())
var startFrame = endFrame
startFrame.origin.x += UIScreen.mainScreen().bounds.width * 0.75
to?.frame = startFrame
UIView.animateWithDuration(
transitionDuration(transitionContext),
animations: {
from?.tintAdjustmentMode = .Dimmed
to?.frame = endFrame
},
completion: {(done: Bool) in
transitionContext.completeTransition(done)
}
)
}
}
|
mit
|
0282a2d971c0c3be7874be6655144f5e
| 28.185185 | 83 | 0.725254 | 5.37884 | false | false | false | false |
mcomella/prox
|
Prox/Prox/Utilities/AppConstants.swift
|
1
|
1718
|
/* 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
public enum AppBuildChannel {
case Developer
case Enterprise
case Release
}
public struct AppConstants {
public static let IsRunningTest = NSClassFromString("XCTestCase") != nil
/// Build Channel.
public static let BuildChannel: AppBuildChannel = {
#if MOZ_CHANNEL_ENTERPRISE
return AppBuildChannel.Enterprise
#elseif MOZ_CHANNEL_RELEASE
return AppBuildChannel.Release
#else
return AppBuildChannel.Developer
#endif
}()
/// Flag indiciating if we are running in Debug mode or not.
public static let isDebug: Bool = {
#if MOZ_CHANNEL_DEBUG
return true
#else
return false
#endif
}()
/// Flag indiciating if we are running in Enterprise mode or not.
public static let isEnterprise: Bool = {
#if MOZ_CHANNEL_ENTERPRISE
return true
#else
return false
#endif
}()
public static let isSimulator: Bool = {
#if (arch(i386) || arch(x86_64))
return true
#else
return false
#endif
}()
// Enables/disables location faking for Hawaii
public static let MOZ_LOCATION_FAKING: Bool = {
#if MOZ_CHANNEL_DEBUG
return false
#elseif MOZ_CHANNEL_ENTERPRISE
return true
#elseif MOZ_CHANNEL_RELEASE
return false
#else
return false
#endif
}()
}
|
mpl-2.0
|
13b6f046f29152078098eb11e20b890d
| 24.264706 | 76 | 0.593714 | 4.643243 | false | false | false | false |
jairoeli/Habit
|
Zero/Sources/Utils/UITableView+ScrollToBottom.swift
|
1
|
886
|
//
// UITableView+ScrollToBottom.swift
// Zero
//
// Created by Jairo Eli de Leon on 9/29/17.
// Copyright © 2017 Jairo Eli de León. All rights reserved.
//
import UIKit
import UIKit
extension UITableView {
func isReachedBottom(withOffset offset: CGFloat = 0) -> Bool {
guard self.contentSize.height > self.height, self.height > 0 else { return true }
let contentOffsetBottom = self.contentOffset.y + self.height
return contentOffsetBottom - offset >= self.contentSize.height
}
func scrollToBottom(animated: Bool) {
let scrollHeight = self.contentSize.height + self.contentInset.top + self.contentInset.bottom
guard scrollHeight > self.height, self.height > 0 else { return }
let targetOffset = CGPoint(x: 0, y: self.contentSize.height + self.contentInset.bottom - self.height)
self.setContentOffset(targetOffset, animated: animated)
}
}
|
mit
|
53d7b6dbbe800d71ad4782ab67333340
| 30.571429 | 105 | 0.725113 | 3.946429 | false | false | false | false |
Pikaurd/ImageCache4ASDK
|
ImageCache4ASDK/ImageCache.swift
|
1
|
7248
|
//
// ImageCache.swift
// ASDKLesson
//
// Created by Pikaurd on 4/16/15.
// Copyright (c) 2015 Shanghai Zuijiao Infomation Technology Inc. All rights reserved.
//
import Foundation
import AsyncDisplayKit
public class ImageCache: NSCache {
static let kDefaultTimeoutLengthInNanoSeconds = 10 * 1_000_000_000 as Int64
private let downloadConcurrentQueue: dispatch_queue_t
private let workingConcurrentQueue: dispatch_queue_t
private let directoryPath: String
private let fileManager: NSFileManager
private var downloadingMap: [NSURL : dispatch_semaphore_t]
required public init(appGroupIdentifier: String? = .None) {
downloadConcurrentQueue = dispatch_queue_create("net.zuijiao.async.DownloadQueue", DISPATCH_QUEUE_CONCURRENT)
workingConcurrentQueue = dispatch_queue_create("net.zuijiao.async.WorkingQueue", DISPATCH_QUEUE_CONCURRENT)
downloadingMap = [ : ]
fileManager = NSFileManager.defaultManager()
directoryPath = ImageCache.generateCacheDirectoryPathByAppGroupIdentifier(fileManager, appGroupIdentifier: appGroupIdentifier)
super.init()
dispatch_barrier_async(workingConcurrentQueue, { () -> Void in
if !self.fileManager.fileExistsAtPath(self.directoryPath) {
var error: NSError?
self.fileManager.createDirectoryAtPath(self.directoryPath
, withIntermediateDirectories: false
, attributes: [:]
, error: &error)
if let error = error {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
debugLog("error: \(error)")
exit(1)
})
}
}
})
}
public func newASNetworkImageNode() -> ASNetworkImageNode {
return ASNetworkImageNode(cache: self, downloader: self)
}
public func clearCache() -> () {
dispatch_barrier_async(workingConcurrentQueue, { () -> Void in
self.removeAllObjects()
self.removePath(self.directoryPath)
})
}
public func clearCache(key: NSURL) -> () {
dispatch_barrier_async(workingConcurrentQueue, { () -> Void in
self.removeObjectForKey(key)
let filePath = self.getFilePath(key)
self.removePath(filePath)
})
}
private func removePath(path: String) -> () {
if self.fileManager.fileExistsAtPath(path) {
var error: NSError?
self.fileManager.removeItemAtPath(path, error: &error)
if let error = error {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
debugLog("error: \(error)")
})
}
}
}
private func persistImage(image: UIImage, withKey key: NSURL) {
dispatch_sync(workingConcurrentQueue, { () -> Void in
self.setObject(image, forKey: key)
let png = UIImagePNGRepresentation(image)
png.writeToFile(self.getFilePath(key), atomically: true)
})
}
public func fetchImage(key: NSURL) -> UIImage? {
let resultImage: UIImage?
if let hittedImage: AnyObject = self.objectForKey(key) { // memory
resultImage = hittedImage as? UIImage
debugLog("Hit")
}
else if imageInDiskCache(key) { // fetch from disk
resultImage = UIImage(contentsOfFile: getFilePath(key))
setObject(resultImage!, forKey: key)
debugLog("Miss")
}
else { // Not hit
resultImage = .None
}
return resultImage
}
private func imageInDiskCache(url: NSURL) -> Bool {
return fileManager.fileExistsAtPath(getFilePath(url))
}
private func getFilePath(url: NSURL) -> String {
return "\(directoryPath)/Cache_\(url.hash).png"
}
private func downloadImage(url: NSURL) -> UIImage? {
if let _ = downloadingMap[url] {
return .None // cancle thread 'cause the url was downloading
}
let sema = dispatch_semaphore_create(0)
downloadingMap.updateValue(sema, forKey: url)
dispatch_async(downloadConcurrentQueue, { () -> Void in
if let data = NSData(contentsOfURL: url) {
if let image = UIImage(data: data) {
self.persistImage(image, withKey: url)
}
}
dispatch_semaphore_signal(sema)
});
let timeout = dispatch_time(DISPATCH_TIME_NOW, ImageCache.kDefaultTimeoutLengthInNanoSeconds)
dispatch_semaphore_wait(sema, timeout);
downloadingMap.removeValueForKey(url)
let resultImage = fetchImage(url)
return resultImage
}
private static func generateCacheDirectoryPathByAppGroupIdentifier(fileManager: NSFileManager, appGroupIdentifier: String?) -> String {
let foldername = "Library/Caches/net.zuijiao.ios.asyncdisplay.ImageCache"
let path: String
if let appGroupIdentifier = appGroupIdentifier {
let url = fileManager.containerURLForSecurityApplicationGroupIdentifier(appGroupIdentifier)
let folderUrl = url!.URLByAppendingPathComponent(foldername).absoluteString!
path = folderUrl.substringFromIndex(advance(folderUrl.startIndex, 7))
}
else {
path = "\(NSHomeDirectory())\(foldername)"
}
return path
}
}
extension ImageCache: ASImageCacheProtocol {
public func fetchCachedImageWithURL(
URL: NSURL!
, callbackQueue: dispatch_queue_t!
, completion: ((CGImage!) -> Void)!
) -> ()
{
dispatch_async(callbackQueue, { () -> Void in
completion(self.fetchImage(URL)?.CGImage)
})
}
}
extension ImageCache: ASImageDownloaderProtocol {
public func downloadImageWithURL(
URL: NSURL!
, callbackQueue: dispatch_queue_t!
, downloadProgressBlock: ((CGFloat) -> Void)!
, completion: ((CGImage!, NSError!) -> Void)!)
-> AnyObject!
{
dispatch_async(workingConcurrentQueue, { () -> Void in
var error: NSError?
let resultImage: UIImage! = self.downloadImage(URL)
if resultImage == .None {
error = NSError(domain: "net.zuijiao.ios.async", code: 0x1, userInfo: ["Reason": "download failed"])
}
dispatch_async(callbackQueue, { () -> Void in
completion(resultImage?.CGImage, error)
})
})
return .None // not implement cancle method
}
public func cancelImageDownloadForIdentifier(downloadIdentifier: AnyObject!) {
debugLog("[Not implement] Do nothing")
}
}
private class DownloadState {
let semaphore: dispatch_semaphore_t
let task: NSURLSessionTask
required init(semaphore: dispatch_semaphore_t, task: NSURLSessionTask) {
self.semaphore = semaphore
self.task = task
}
}
|
mit
|
c3fa9224a562e9b542924ea633042f2d
| 31.502242 | 139 | 0.595613 | 5.019391 | false | false | false | false |
alickbass/ViewComponents
|
ViewComponents/ComponentProtocols.swift
|
1
|
1647
|
//
// ComponentProtocols.swift
// ViewComponents
//
// Created by Oleksii on 17/05/2017.
// Copyright © 2017 WeAreReasonablePeople. All rights reserved.
//
import UIKit
// MARK: - Component Convertible
public protocol ComponentConvertible {
associatedtype ComponentViewType
var toComponent: Component<ComponentViewType> { get }
func configure(item: ComponentViewType)
func diffChanges<T: ComponentConvertible>(from other: T) -> Component<ComponentViewType> where T.ComponentViewType == ComponentViewType
}
public extension ComponentConvertible {
public func configure(item: ComponentViewType) {
toComponent.configure(item: item)
}
public func diffChanges<T: ComponentConvertible>(from other: T) -> Component<ComponentViewType> where T.ComponentViewType == ComponentViewType {
return toComponent.diffChanges(from: other.toComponent)
}
}
// MARK: - Component Protocol
public protocol ComponentType: Equatable {
associatedtype View
var children: [ChildComponent<View>] { get }
var isEmpty: Bool { get }
func configure(item: View)
func diffChanges(from other: Self) -> Self
}
// MARK: - Component View Protocol
public protocol ComponentContainingView: class {
associatedtype ViewModel: ComponentConvertible
var item: ViewModel? { get set }
func configure(with newItem: ViewModel)
}
public extension ComponentContainingView where ViewModel.ComponentViewType == Self {
public func configure(with newItem: ViewModel) {
(item?.diffChanges(from: newItem) ?? newItem.toComponent).configure(item: self)
item = newItem
}
}
|
mit
|
df124b875247d59bb3155f291de50ec3
| 29.481481 | 148 | 0.727825 | 4.509589 | false | true | false | false |
ben-ng/swift
|
stdlib/public/core/Builtin.swift
|
1
|
19723
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Definitions that make elements of Builtin usable in real code
// without gobs of boilerplate.
@available(*, unavailable, message: "use MemoryLayout<T>.size instead.")
public func sizeof<T>(_:T.Type) -> Int {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "MemoryLayout.size(ofValue:)")
public func sizeofValue<T>(_:T) -> Int {
Builtin.unreachable()
}
@available(*, unavailable, message: "use MemoryLayout<T>.alignment instead.")
public func alignof<T>(_:T.Type) -> Int {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "MemoryLayout.alignment(ofValue:)")
public func alignofValue<T>(_:T) -> Int {
Builtin.unreachable()
}
@available(*, unavailable, message: "use MemoryLayout<T>.stride instead.")
public func strideof<T>(_:T.Type) -> Int {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "MemoryLayout.stride(ofValue:)")
public func strideofValue<T>(_:T) -> Int {
Builtin.unreachable()
}
// This function is the implementation of the `_roundUp` overload set. It is
// marked `@inline(__always)` to make primary `_roundUp` entry points seem
// cheap enough for the inliner.
@_versioned
@inline(__always)
internal func _roundUpImpl(_ offset: UInt, toAlignment alignment: Int) -> UInt {
_sanityCheck(alignment > 0)
_sanityCheck(_isPowerOf2(alignment))
// Note, given that offset is >= 0, and alignment > 0, we don't
// need to underflow check the -1, as it can never underflow.
let x = offset + UInt(bitPattern: alignment) &- 1
// Note, as alignment is a power of 2, we'll use masking to efficiently
// get the aligned value
return x & ~(UInt(bitPattern: alignment) &- 1)
}
@_versioned
internal func _roundUp(_ offset: UInt, toAlignment alignment: Int) -> UInt {
return _roundUpImpl(offset, toAlignment: alignment)
}
@_versioned
internal func _roundUp(_ offset: Int, toAlignment alignment: Int) -> Int {
_sanityCheck(offset >= 0)
return Int(_roundUpImpl(UInt(bitPattern: offset), toAlignment: alignment))
}
// This function takes a raw pointer and returns a typed pointer. It implicitly
// assumes that memory at the returned pointer is bound to `Destination` type.
@_versioned
internal func _roundUp<DestinationType>(
_ pointer: UnsafeMutableRawPointer,
toAlignmentOf destinationType: DestinationType.Type
) -> UnsafeMutablePointer<DestinationType> {
// Note: unsafe unwrap is safe because this operation can only increase the
// value, and can not produce a null pointer.
return UnsafeMutablePointer<DestinationType>(
bitPattern: _roundUpImpl(
UInt(bitPattern: pointer),
toAlignment: MemoryLayout<DestinationType>.alignment)
).unsafelyUnwrapped
}
/// Returns a tri-state of 0 = no, 1 = yes, 2 = maybe.
@_transparent
public // @testable
func _canBeClass<T>(_: T.Type) -> Int8 {
return Int8(Builtin.canBeClass(T.self))
}
/// Returns the bits of `x`, interpreted as having type `U`.
///
/// - Warning: Breaks the guarantees of Swift's type system; use
/// with extreme care. There's almost always a better way to do
/// anything.
///
@_transparent
public func unsafeBitCast<T, U>(_ x: T, to: U.Type) -> U {
_precondition(MemoryLayout<T>.size == MemoryLayout<U>.size,
"can't unsafeBitCast between types of different sizes")
return Builtin.reinterpretCast(x)
}
/// `unsafeBitCast` something to `AnyObject`.
@_transparent
internal func _reinterpretCastToAnyObject<T>(_ x: T) -> AnyObject {
return unsafeBitCast(x, to: AnyObject.self)
}
@_transparent
func == (lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@_transparent
func != (lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool {
return !(lhs == rhs)
}
@_transparent
func == (lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@_transparent
func != (lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {
return !(lhs == rhs)
}
/// Returns `true` iff `t0` is identical to `t1`; i.e. if they are both
/// `nil` or they both represent the same type.
public func == (t0: Any.Type?, t1: Any.Type?) -> Bool {
return unsafeBitCast(t0, to: Int.self) == unsafeBitCast(t1, to: Int.self)
}
/// Returns `false` iff `t0` is identical to `t1`; i.e. if they are both
/// `nil` or they both represent the same type.
public func != (t0: Any.Type?, t1: Any.Type?) -> Bool {
return !(t0 == t1)
}
/// Tell the optimizer that this code is unreachable if condition is
/// known at compile-time to be true. If condition is false, or true
/// but not a compile-time constant, this call has no effect.
@_transparent
internal func _unreachable(_ condition: Bool = true) {
if condition {
// FIXME: use a parameterized version of Builtin.unreachable when
// <rdar://problem/16806232> is closed.
Builtin.unreachable()
}
}
/// Tell the optimizer that this code is unreachable if this builtin is
/// reachable after constant folding build configuration builtins.
@_versioned @_transparent internal
func _conditionallyUnreachable() -> Never {
Builtin.conditionallyUnreachable()
}
@_versioned
@_silgen_name("_swift_isClassOrObjCExistentialType")
func _swift_isClassOrObjCExistentialType<T>(_ x: T.Type) -> Bool
/// Returns `true` iff `T` is a class type or an `@objc` existential such as
/// `AnyObject`.
@_versioned
@inline(__always)
internal func _isClassOrObjCExistential<T>(_ x: T.Type) -> Bool {
switch _canBeClass(x) {
// Is not a class.
case 0:
return false
// Is a class.
case 1:
return true
// Maybe a class.
default:
return _swift_isClassOrObjCExistentialType(x)
}
}
/// Returns an `UnsafePointer` to the storage used for `object`. There's
/// not much you can do with this other than use it to identify the
/// object.
@available(*, unavailable, message: "Removed in Swift 3. Use Unmanaged.passUnretained(x).toOpaque() instead.")
public func unsafeAddress(of object: AnyObject) -> UnsafeRawPointer {
Builtin.unreachable()
}
@available(*, unavailable, message: "Removed in Swift 3. Use Unmanaged.passUnretained(x).toOpaque() instead.")
public func unsafeAddressOf(_ object: AnyObject) -> UnsafeRawPointer {
Builtin.unreachable()
}
/// Converts a reference of type `T` to a reference of type `U` after
/// unwrapping one level of Optional.
///
/// Unwrapped `T` and `U` must be convertible to AnyObject. They may
/// be either a class or a class protocol. Either T, U, or both may be
/// optional references.
@_transparent
public func _unsafeReferenceCast<T, U>(_ x: T, to: U.Type) -> U {
return Builtin.castReference(x)
}
/// - returns: `x as T`.
///
/// - Precondition: `x is T`. In particular, in -O builds, no test is
/// performed to ensure that `x` actually has dynamic type `T`.
///
/// - Warning: Trades safety for performance. Use `unsafeDowncast`
/// only when `x as T` has proven to be a performance problem and you
/// are confident that, always, `x is T`. It is better than an
/// `unsafeBitCast` because it's more restrictive, and because
/// checking is still performed in debug builds.
@_transparent
public func unsafeDowncast<T : AnyObject>(_ x: AnyObject, to: T.Type) -> T {
_debugPrecondition(x is T, "invalid unsafeDowncast")
return Builtin.castReference(x)
}
@inline(__always)
public func _getUnsafePointerToStoredProperties(_ x: AnyObject)
-> UnsafeMutableRawPointer {
let storedPropertyOffset = _roundUp(
MemoryLayout<_HeapObject>.size,
toAlignment: MemoryLayout<Optional<AnyObject>>.alignment)
return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(x)) +
storedPropertyOffset
}
//===----------------------------------------------------------------------===//
// Branch hints
//===----------------------------------------------------------------------===//
// Use @_semantics to indicate that the optimizer recognizes the
// semantics of these function calls. This won't be necessary with
// mandatory generic inlining.
@_versioned
@_transparent
@_semantics("branchhint")
internal func _branchHint(_ actual: Bool, expected: Bool) -> Bool {
return Bool(Builtin.int_expect_Int1(actual._value, expected._value))
}
/// Optimizer hint that `x` is expected to be `true`.
@_transparent
@_semantics("fastpath")
public func _fastPath(_ x: Bool) -> Bool {
return _branchHint(x, expected: true)
}
/// Optimizer hint that `x` is expected to be `false`.
@_transparent
@_semantics("slowpath")
public func _slowPath(_ x: Bool) -> Bool {
return _branchHint(x, expected: false)
}
/// Optimizer hint that the code where this function is called is on the fast
/// path.
@_transparent
public func _onFastPath() {
Builtin.onFastPath()
}
//===--- Runtime shim wrappers --------------------------------------------===//
/// Returns `true` iff the class indicated by `theClass` uses native
/// Swift reference-counting.
#if _runtime(_ObjC)
// Declare it here instead of RuntimeShims.h, because we need to specify
// the type of argument to be AnyClass. This is currently not possible
// when using RuntimeShims.h
@_versioned
@_silgen_name("swift_objc_class_usesNativeSwiftReferenceCounting")
func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool
#else
@_versioned
@inline(__always)
func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool {
return true
}
#endif
@_silgen_name("swift_class_getInstanceExtents")
func swift_class_getInstanceExtents(_ theClass: AnyClass)
-> (negative: UInt, positive: UInt)
@_silgen_name("swift_objc_class_unknownGetInstanceExtents")
func swift_objc_class_unknownGetInstanceExtents(_ theClass: AnyClass)
-> (negative: UInt, positive: UInt)
/// - Returns:
@inline(__always)
internal func _class_getInstancePositiveExtentSize(_ theClass: AnyClass) -> Int {
#if _runtime(_ObjC)
return Int(swift_objc_class_unknownGetInstanceExtents(theClass).positive)
#else
return Int(swift_class_getInstanceExtents(theClass).positive)
#endif
}
//===--- Builtin.BridgeObject ---------------------------------------------===//
#if arch(i386) || arch(arm)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x0000_0003 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0002 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0 }
}
#elseif arch(x86_64)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x7F00_0000_0000_0006 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x4000_0000_0000_0000 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 1 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0x8000_0000_0000_0001 }
}
#elseif arch(arm64)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x7F00_0000_0000_0007 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x4000_0000_0000_0000 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0x8000_0000_0000_0000 }
}
#elseif arch(powerpc64) || arch(powerpc64le)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x0000_0000_0000_0007 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0000_0000_0002 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0 }
}
#elseif arch(s390x)
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x0000_0000_0000_0007 }
}
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0000_0000_0002 }
}
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0 }
}
#endif
/// Extract the raw bits of `x`.
@_versioned
@inline(__always)
internal func _bitPattern(_ x: Builtin.BridgeObject) -> UInt {
return UInt(Builtin.castBitPatternFromBridgeObject(x))
}
/// Extract the raw spare bits of `x`.
@_versioned
@inline(__always)
internal func _nonPointerBits(_ x: Builtin.BridgeObject) -> UInt {
return _bitPattern(x) & _objectPointerSpareBits
}
@_versioned
@inline(__always)
internal func _isObjCTaggedPointer(_ x: AnyObject) -> Bool {
return (Builtin.reinterpretCast(x) & _objCTaggedPointerBits) != 0
}
/// Create a `BridgeObject` around the given `nativeObject` with the
/// given spare bits.
///
/// Reference-counting and other operations on this
/// object will have access to the knowledge that it is native.
///
/// - Precondition: `bits & _objectPointerIsObjCBit == 0`,
/// `bits & _objectPointerSpareBits == bits`.
@_versioned
@inline(__always)
internal func _makeNativeBridgeObject(
_ nativeObject: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_sanityCheck(
(bits & _objectPointerIsObjCBit) == 0,
"BridgeObject is treated as non-native when ObjC bit is set"
)
return _makeBridgeObject(nativeObject, bits)
}
/// Create a `BridgeObject` around the given `objCObject`.
@inline(__always)
public // @testable
func _makeObjCBridgeObject(
_ objCObject: AnyObject
) -> Builtin.BridgeObject {
return _makeBridgeObject(
objCObject,
_isObjCTaggedPointer(objCObject) ? 0 : _objectPointerIsObjCBit)
}
/// Create a `BridgeObject` around the given `object` with the
/// given spare bits.
///
/// - Precondition:
///
/// 1. `bits & _objectPointerSpareBits == bits`
/// 2. if `object` is a tagged pointer, `bits == 0`. Otherwise,
/// `object` is either a native object, or `bits ==
/// _objectPointerIsObjCBit`.
@_versioned
@inline(__always)
internal func _makeBridgeObject(
_ object: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_sanityCheck(!_isObjCTaggedPointer(object) || bits == 0,
"Tagged pointers cannot be combined with bits")
_sanityCheck(
_isObjCTaggedPointer(object)
|| _usesNativeSwiftReferenceCounting(type(of: object))
|| bits == _objectPointerIsObjCBit,
"All spare bits must be set in non-native, non-tagged bridge objects"
)
_sanityCheck(
bits & _objectPointerSpareBits == bits,
"Can't store non-spare bits into Builtin.BridgeObject")
return Builtin.castToBridgeObject(
object, bits._builtinWordValue
)
}
@_versioned
@_silgen_name("_swift_class_getSuperclass")
internal func _swift_class_getSuperclass(_ t: AnyClass) -> AnyClass?
/// Returns the superclass of `t`, if any. The result is `nil` if `t` is
/// a root class or class protocol.
@inline(__always)
public // @testable
func _getSuperclass(_ t: AnyClass) -> AnyClass? {
return _swift_class_getSuperclass(t)
}
/// Returns the superclass of `t`, if any. The result is `nil` if `t` is
/// not a class, is a root class, or is a class protocol.
@inline(__always)
public // @testable
func _getSuperclass(_ t: Any.Type) -> AnyClass? {
return (t as? AnyClass).flatMap { _getSuperclass($0) }
}
//===--- Builtin.IsUnique -------------------------------------------------===//
// _isUnique functions must take an inout object because they rely on
// Builtin.isUnique which requires an inout reference to preserve
// source-level copies in the presence of ARC optimization.
//
// Taking an inout object makes sense for two additional reasons:
//
// 1. You should only call it when about to mutate the object.
// Doing so otherwise implies a race condition if the buffer is
// shared across threads.
//
// 2. When it is not an inout function, self is passed by
// value... thus bumping the reference count and disturbing the
// result we are trying to observe, Dr. Heisenberg!
//
// _isUnique and _isUniquePinned cannot be made public or the compiler
// will attempt to generate generic code for the transparent function
// and type checking will fail.
/// Returns `true` if `object` is uniquely referenced.
@_versioned
@_transparent
internal func _isUnique<T>(_ object: inout T) -> Bool {
return Bool(Builtin.isUnique(&object))
}
/// Returns `true` if `object` is uniquely referenced or pinned.
@_versioned
@_transparent
internal func _isUniqueOrPinned<T>(_ object: inout T) -> Bool {
return Bool(Builtin.isUniqueOrPinned(&object))
}
/// Returns `true` if `object` is uniquely referenced.
/// This provides sanity checks on top of the Builtin.
@_transparent
public // @testable
func _isUnique_native<T>(_ object: inout T) -> Bool {
// This could be a bridge object, single payload enum, or plain old
// reference. Any case it's non pointer bits must be zero, so
// force cast it to BridgeObject and check the spare bits.
_sanityCheck(
(_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits)
== 0)
_sanityCheck(_usesNativeSwiftReferenceCounting(
type(of: Builtin.reinterpretCast(object) as AnyObject)))
return Bool(Builtin.isUnique_native(&object))
}
/// Returns `true` if `object` is uniquely referenced or pinned.
/// This provides sanity checks on top of the Builtin.
@_transparent
public // @testable
func _isUniqueOrPinned_native<T>(_ object: inout T) -> Bool {
// This could be a bridge object, single payload enum, or plain old
// reference. Any case it's non pointer bits must be zero.
_sanityCheck(
(_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits)
== 0)
_sanityCheck(_usesNativeSwiftReferenceCounting(
type(of: Builtin.reinterpretCast(object) as AnyObject)))
return Bool(Builtin.isUniqueOrPinned_native(&object))
}
/// Returns `true` if type is a POD type. A POD type is a type that does not
/// require any special handling on copying or destruction.
@_transparent
public // @testable
func _isPOD<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.ispod(type))
}
/// Returns `true` if type is nominally an Optional type.
@_transparent
public // @testable
func _isOptional<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.isOptional(type))
}
@available(*, unavailable, message: "Removed in Swift 3. Please use Optional.unsafelyUnwrapped instead.")
public func unsafeUnwrap<T>(_ nonEmpty: T?) -> T {
Builtin.unreachable()
}
/// Extract an object reference from an Any known to contain an object.
internal func _unsafeDowncastToAnyObject(fromAny any: Any) -> AnyObject {
_sanityCheck(type(of: any) is AnyObject.Type
|| type(of: any) is AnyObject.Protocol,
"Any expected to contain object reference")
// With a SIL instruction, we could more efficiently grab the object reference
// out of the Any's inline storage.
// On Linux, bridging isn't supported, so this is a force cast.
#if _runtime(_ObjC)
return any as AnyObject
#else
return any as! AnyObject
#endif
}
|
apache-2.0
|
dfad1d77f6f92d0f1344ad88ade3afa3
| 31.762458 | 110 | 0.697105 | 4.049066 | false | false | false | false |
Esri/arcgis-runtime-samples-ios
|
arcgis-ios-sdk-samples/Features/Generate geodatabase replica from feature service/GenerateGeodatabaseViewController.swift
|
1
|
7353
|
//
// Copyright 2016 Esri.
//
// 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 ArcGIS
class GenerateGeodatabaseViewController: UIViewController {
@IBOutlet var mapView: AGSMapView!
@IBOutlet var downloadBBI: UIBarButtonItem!
@IBOutlet var extentView: UIView!
private var syncTask: AGSGeodatabaseSyncTask = {
let featureServiceURL = URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/WildfireSync/FeatureServer")!
return AGSGeodatabaseSyncTask(url: featureServiceURL)
}()
private var generatedGeodatabase: AGSGeodatabase?
// must retain a strong reference to a job while it runs
private var activeJob: AGSJob?
override func viewDidLoad() {
super.viewDidLoad()
// add the source code button item to the right of navigation bar
(navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["GenerateGeodatabaseViewController"]
let tileCache = AGSTileCache(name: "SanFrancisco")
let localTiledLayer = AGSArcGISTiledLayer(tileCache: tileCache)
let map = AGSMap(basemap: AGSBasemap(baseLayer: localTiledLayer))
mapView.map = map
addFeatureLayers()
// setup extent view
extentView.layer.borderColor = UIColor.red.cgColor
extentView.layer.borderWidth = 3
}
func addFeatureLayers() {
syncTask.load { [weak self] (error) in
if let error = error {
print("Could not load feature service \(error)")
} else {
guard let self = self,
let featureServiceInfo = self.syncTask.featureServiceInfo else {
return
}
// For each layer in the service, add a layer to the map.
let featureLayers = featureServiceInfo.layerInfos.enumerated().map { (offset, layerInfo) -> AGSFeatureLayer in
let layerURL = self.syncTask.url!.appendingPathComponent(String(offset))
let featureTable = AGSServiceFeatureTable(url: layerURL)
let featureLayer = AGSFeatureLayer(featureTable: featureTable)
featureLayer.name = layerInfo.name
featureLayer.opacity = 0.65
return featureLayer
}
self.mapView.map?.operationalLayers.addObjects(from: featureLayers.reversed())
// enable download
self.downloadBBI.isEnabled = true
}
}
}
func frameToExtent() -> AGSEnvelope {
let frame = mapView.convert(extentView.frame, from: view)
let minPoint = mapView.screen(toLocation: frame.origin)
let maxPoint = mapView.screen(toLocation: CGPoint(x: frame.maxX, y: frame.maxY))
let extent = AGSEnvelope(min: minPoint, max: maxPoint)
return extent
}
// MARK: - Actions
@IBAction func downloadAction() {
// generate default param to contain all layers in the service
syncTask.defaultGenerateGeodatabaseParameters(withExtent: self.frameToExtent()) { [weak self] (params: AGSGenerateGeodatabaseParameters?, error: Error?) in
if let params = params,
let self = self {
// don't include attachments to minimze the geodatabae size
params.returnAttachments = false
// create a unique name for the geodatabase based on current timestamp
let dateFormatter = ISO8601DateFormatter()
let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let downloadFileURL = documentDirectoryURL
.appendingPathComponent(dateFormatter.string(from: Date()))
.appendingPathExtension("geodatabase")
// request a job to generate the geodatabase
let generateJob = self.syncTask.generateJob(with: params, downloadFileURL: downloadFileURL)
self.activeJob = generateJob
// kick off the job
generateJob.start(
statusHandler: { (status: AGSJobStatus) in
UIApplication.shared.showProgressHUD(message: status.statusString())
},
completion: { [weak self] (geodatabase: AGSGeodatabase?, error: Error?) in
UIApplication.shared.hideProgressHUD()
if let error = error {
self?.presentAlert(error: error)
} else {
self?.generatedGeodatabase = geodatabase
self?.displayLayersFromGeodatabase()
}
self?.activeJob = nil
}
)
} else {
print("Could not generate default parameters: \(error!)")
}
}
}
func displayLayersFromGeodatabase() {
guard let generatedGeodatabase = generatedGeodatabase else {
return
}
generatedGeodatabase.load { [weak self] (error: Error?) in
guard let self = self else {
return
}
if let error = error {
self.presentAlert(error: error)
} else {
self.mapView.map?.operationalLayers.removeAllObjects()
AGSLoadObjects(generatedGeodatabase.geodatabaseFeatureTables) { (success: Bool) in
if success {
for featureTable in generatedGeodatabase.geodatabaseFeatureTables.reversed() {
// check if featureTable has geometry
if featureTable.hasGeometry {
let featureLayer = AGSFeatureLayer(featureTable: featureTable)
self.mapView.map?.operationalLayers.add(featureLayer)
}
}
self.presentAlert(message: "Now showing data from geodatabase")
// hide the extent view
self.extentView.isHidden = true
// disable the download button
self.downloadBBI.isEnabled = false
}
// unregister geodatabase as the sample wont be editing or syncing features
self.syncTask.unregisterGeodatabase(generatedGeodatabase)
}
}
}
}
}
|
apache-2.0
|
98203bfa77e668e2ffc801f8ed3a75e1
| 43.02994 | 163 | 0.571467 | 5.38287 | false | false | false | false |
ReiVerdugo/uikit-fundamentals
|
step5.8-makeYourOwnAdventure-complete/MYOA/StoryNode.swift
|
1
|
1652
|
//
// StoryNode.swift
// MYOA
//
// Copyright (c) 2015 Udacity. All rights reserved.
//
import Foundation
// MARK: - StoryNode
struct StoryNode {
// MARK: Properites
var message: String
private var adventure: Adventure
private var connections: [Connection]
var imageName: String? {
return adventure.credits.imageName
}
// MARK: Initializer
init(dictionary: [String : AnyObject], adventure: Adventure) {
self.adventure = adventure
message = dictionary["message"] as! String
connections = [Connection]()
message = message.stringByReplacingOccurrencesOfString("\\n", withString: "\n\n")
if let connectionsArray = dictionary["connections"] as? [[String : String]] {
for connectionDictionary: [String : String] in connectionsArray {
connections.append(Connection(dictionary: connectionDictionary))
}
}
}
// MARK: Prompts
// The number of prompts for story choices
func promptCount() -> Int {
return connections.count
}
// The prompt string, these will be something like: "Open the door, and look inside"
func promptForIndex(index: Int) -> String {
return connections[index].prompt
}
// The Story node that corresponds to the prompt with the same index.
func storyNodeForIndex(index: Int) -> StoryNode {
let storyNodeName = connections[index].connectedStoryNodeName
let storyNode = adventure.storyNodes[storyNodeName]
return storyNode!
}
}
|
mit
|
efdfc1a3e5a89e79173ae01cdec1eaff
| 25.222222 | 89 | 0.615012 | 4.902077 | false | false | false | false |
irace/tickets
|
Tickets/ViewController.swift
|
1
|
3164
|
//
// ViewController.swift
// Tickets
//
// Created by Bryan Irace on 10/14/14.
// Copyright (c) 2014 Bryan Irace. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private let padding: CGFloat = 30
private var textView: UITextView?
private var bottomConstraint: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
view.setTranslatesAutoresizingMaskIntoConstraints(false);
let textView = UITextView()
textView.layer.borderColor = UIColor.redColor().CGColor
textView.layer.borderWidth = 1
textView.layer.cornerRadius = 3
textView.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(textView)
self.textView = textView;
let bottomConstraint = NSLayoutConstraint(item: textView,
attribute: .Bottom,
relatedBy: .Equal,
toItem: self.view,
attribute: .Bottom,
multiplier: 1,
constant: -padding);
self.view.addConstraints([
NSLayoutConstraint(item: textView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top,
multiplier: 1, constant: padding),
bottomConstraint,
NSLayoutConstraint(item: textView, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right,
multiplier: 1, constant: -padding),
NSLayoutConstraint(item: textView, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left,
multiplier: 1, constant: padding)
])
self.bottomConstraint = bottomConstraint
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:",
name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:",
name: UIKeyboardWillHideNotification, object: nil)
}
// NOTE: Notifications
func keyboardWillShow(notification: NSNotification) {
if let info = notification.userInfo as? Dictionary<NSString, AnyObject> {
let keyboardHeight = (info[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue().size.height
let duration = (info[UIKeyboardAnimationDurationUserInfoKey] as NSNumber).doubleValue
self.bottomConstraint?.constant = -padding - keyboardHeight
UIView.animateWithDuration(duration, animations: { () -> Void in
self.view.layoutIfNeeded()
});
}
}
func keyboardWillHide(notification: NSNotification) {
if let info = notification.userInfo as? Dictionary<NSString, AnyObject> {
let duration = (info[UIKeyboardAnimationDurationUserInfoKey] as NSNumber).doubleValue
self.bottomConstraint?.constant = -padding
UIView.animateWithDuration(duration, animations: { () -> Void in
self.view.layoutIfNeeded()
});
}
}
}
|
mit
|
871bc711341655be007d31353b755b7b
| 36.666667 | 117 | 0.626106 | 5.773723 | false | false | false | false |
airbnb/lottie-ios
|
Sources/Private/Model/Text/Font.swift
|
2
|
1193
|
//
// Font.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/9/19.
//
import Foundation
// MARK: - Font
final class Font: Codable, DictionaryInitializable {
// MARK: Lifecycle
init(dictionary: [String: Any]) throws {
name = try dictionary.value(for: CodingKeys.name)
familyName = try dictionary.value(for: CodingKeys.familyName)
style = try dictionary.value(for: CodingKeys.style)
ascent = try dictionary.value(for: CodingKeys.ascent)
}
// MARK: Internal
let name: String
let familyName: String
let style: String
let ascent: Double
// MARK: Private
private enum CodingKeys: String, CodingKey {
case name = "fName"
case familyName = "fFamily"
case style = "fStyle"
case ascent
}
}
// MARK: - FontList
/// A list of fonts
final class FontList: Codable, DictionaryInitializable {
// MARK: Lifecycle
init(dictionary: [String: Any]) throws {
let fontDictionaries: [[String: Any]] = try dictionary.value(for: CodingKeys.fonts)
fonts = try fontDictionaries.map { try Font(dictionary: $0) }
}
// MARK: Internal
enum CodingKeys: String, CodingKey {
case fonts = "list"
}
let fonts: [Font]
}
|
apache-2.0
|
8b4730931d4cd1c49ab04ec8196a4418
| 18.557377 | 87 | 0.671417 | 3.751572 | false | false | false | false |
ProfileCreator/ProfileCreator
|
ProfileCreator/ProfileCreator/Profile Editor Payload Library CellView Items/LibraryCellViewItemTextField.swift
|
1
|
5967
|
//
// LibraryCellViewItemTextField.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Cocoa
class LibraryTextField {
class func description(string: String?,
constraints: inout [NSLayoutConstraint],
topConstant: CGFloat = 1.0,
cellView: PayloadLibraryCellView) -> NSTextField? {
guard let textFieldTitle = cellView.textFieldTitle else {
// TODO: Proper Loggin
return nil
}
// ---------------------------------------------------------------------
// Create and setup TextField
// ---------------------------------------------------------------------
let textField = NSTextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.lineBreakMode = .byTruncatingTail
textField.isBordered = false
textField.isBezeled = false
textField.drawsBackground = false
textField.isEditable = false
textField.isSelectable = false
textField.controlSize = .regular
textField.textColor = .labelColor
textField.alignment = .left
textField.font = NSFont.systemFont(ofSize: 10)
textField.stringValue = string ?? ""
// ---------------------------------------------------------------------
// Add TextField to cell view
// ---------------------------------------------------------------------
cellView.addSubview(textField)
// -------------------------------------------------------------------------
// Setup Layout Constraings for TextField
// -------------------------------------------------------------------------
// Top
constraints.append(NSLayoutConstraint(item: textField,
attribute: .top,
relatedBy: .equal,
toItem: textFieldTitle,
attribute: .bottom,
multiplier: 1.0,
constant: topConstant))
// Leading
constraints.append(NSLayoutConstraint(item: textField,
attribute: .leading,
relatedBy: .equal,
toItem: textFieldTitle,
attribute: .leading,
multiplier: 1.0,
constant: 0.0))
// Trailing
constraints.append(NSLayoutConstraint(item: textField,
attribute: .trailing,
relatedBy: .equal,
toItem: textFieldTitle,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0))
return textField
}
class func title(string: String?,
fontSize: CGFloat,
fontWeight: CGFloat,
indent: CGFloat,
constraints: inout [NSLayoutConstraint],
cellView: PayloadLibraryCellView) -> NSTextField? {
guard let imageView = cellView.imageViewIcon else {
// TODO: Proper Loggin
return nil
}
// ---------------------------------------------------------------------
// Create and setup TextField
// ---------------------------------------------------------------------
let textField = NSTextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.lineBreakMode = .byTruncatingTail
textField.isBordered = false
textField.isBezeled = false
textField.drawsBackground = false
textField.isEditable = false
textField.isSelectable = false
textField.controlSize = .regular
textField.textColor = .labelColor
textField.alignment = .left
textField.font = NSFont.systemFont(ofSize: fontSize, weight: NSFont.Weight(rawValue: fontWeight))
textField.stringValue = string ?? ""
// ---------------------------------------------------------------------
// Add TextField to cell view
// ---------------------------------------------------------------------
cellView.addSubview(textField)
// -------------------------------------------------------------------------
// Setup Layout Constraings for TextField
// -------------------------------------------------------------------------
// Leading
constraints.append(NSLayoutConstraint(item: textField,
attribute: .leading,
relatedBy: .equal,
toItem: imageView,
attribute: .trailing,
multiplier: 1.0,
constant: indent))
// Trailing
constraints.append(NSLayoutConstraint(item: textField,
attribute: .trailing,
relatedBy: .equal,
toItem: cellView,
attribute: .trailing,
multiplier: 1.0,
constant: indent))
return textField
}
}
|
mit
|
17cf315afed529fa5fd9a7f34072cd67
| 43.192593 | 105 | 0.389205 | 8.228966 | false | false | false | false |
xuech/OMS-WH
|
OMS-WH/Classes/DeliveryGoods/Model/DGOutBoundListModel.swift
|
1
|
838
|
//
// DGOutBoundListModel.swift
// OMS-WH
//
// Created by ___Gwy on 2017/9/18.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
class DGOutBoundListModel: CommonPaseModel {
var dTCode:String?
var dTCodeName = ""
var hPCode:String?
var hPCodeName = ""
var medMIWarehouse:String?
var outboundDate:String?
var outboundNote:String?
var outboundPersonName:String?
var qualityCheckDate:String?
var qualityCheckNote:String?
var qualityCheckPersonName:String?
var sOCreateByOrgCode:String?
var sOCreateByOrgCodeName = ""
var sONo = ""
var sOOIOrgCode:String?
var sOOIOrgCodeName = ""
var sOType:String?
var status:String?
var statusName = ""
var wHName = ""
var wHSpecialNotes:String?
var wONo = ""
var soCreateByName = ""
}
|
mit
|
bd93320f8c81574301d024c416ed80a9
| 21.567568 | 50 | 0.670659 | 3.394309 | false | false | false | false |
mtnkdev/wikipedia-ios
|
PromiseKit/PromiseKit.swift
|
4
|
37749
|
import Dispatch
import Foundation.NSDate
/**
@return A new promise that resolves after the specified duration.
@parameter duration The duration in seconds to wait before this promise is resolve.
For example:
after(1).then {
//…
}
*/
public func after(delay: NSTimeInterval) -> Promise<Void> {
return Promise { fulfill, _ in
let delta = delay * NSTimeInterval(NSEC_PER_SEC)
let when = dispatch_time(DISPATCH_TIME_NOW, Int64(delta))
dispatch_after(when, dispatch_get_global_queue(0, 0)) {
fulfill()
}
}
}
import Foundation.NSError
/**
AnyPromise is a Promise that can be used in Objective-C code
Swift code can only convert Promises to AnyPromises or vice versa.
Libraries that only provide promises will require you to write a
small Swift function that can convert those promises into AnyPromises
as you require them.
To effectively use AnyPromise in Objective-C code you must use `#import`
rather than `@import PromiseKit;`
#import <PromiseKit/PromiseKit.h>
*/
/**
Resolution.Fulfilled takes an Any. When retrieving the Any you cannot
convert it into an AnyObject?. By giving Fulfilled an object that has
an AnyObject? property we never have to cast and everything is fine.
*/
private class Box {
let obj: AnyObject?
init(_ obj: AnyObject?) {
self.obj = obj
}
}
private func box(obj: AnyObject?) -> Resolution {
if let error = obj as? NSError {
unconsume(error)
return .Rejected(error)
} else {
return .Fulfilled(Box(obj))
}
}
private func unbox(resolution: Resolution) -> AnyObject? {
switch resolution {
case .Fulfilled(let box):
return (box as! Box).obj
case .Rejected(let error):
return error
}
}
@objc(PMKAnyPromise) public class AnyPromise: NSObject {
var state: State
/**
@return A new AnyPromise bound to a Promise<T>.
The two promises represent the same task, any changes to either
will instantly reflect on both.
*/
public init<T: AnyObject>(bound: Promise<T>) {
//WARNING copy pasta from below. FIXME how?
var resolve: ((Resolution) -> Void)!
state = UnsealedState(resolver: &resolve)
bound.pipe { resolution in
switch resolution {
case .Fulfilled:
resolve(box(bound.value))
case .Rejected(let error):
resolve(box(error))
}
}
}
public init<T: AnyObject>(bound: Promise<T?>) {
//WARNING copy pasta from above. FIXME how?
var resolve: ((Resolution) -> Void)!
state = UnsealedState(resolver: &resolve)
bound.pipe { resolution in
switch resolution {
case .Fulfilled:
resolve(box(bound.value!))
case .Rejected(let error):
resolve(box(error))
}
}
}
/**
@return A new AnyPromise bound to a Promise<[T]>.
The two promises represent the same task, any changes to either
will instantly reflect on both.
The value is converted to an NSArray so Objective-C can use it.
*/
public init<T: AnyObject>(bound: Promise<[T]>) {
//WARNING copy pasta from above. FIXME how?
var resolve: ((Resolution) -> Void)!
state = UnsealedState(resolver: &resolve)
bound.pipe { resolution in
switch resolution {
case .Fulfilled:
resolve(box(NSArray(array: bound.value!)))
case .Rejected(let error):
resolve(box(error))
}
}
}
/**
@return A new AnyPromise bound to a Promise<[T]>.
The two promises represent the same task, any changes to either
will instantly reflect on both.
The value is converted to an NSArray so Objective-C can use it.
*/
public init<T: AnyObject, U: AnyObject>(bound: Promise<[T:U]>) {
//WARNING copy pasta from above. FIXME how?
var resolve: ((Resolution) -> Void)!
state = UnsealedState(resolver: &resolve)
bound.pipe { resolution in
switch resolution {
case .Fulfilled:
resolve(box(bound.value! as NSDictionary))
case .Rejected(let error):
resolve(box(error))
}
}
}
convenience public init(bound: Promise<Int>) {
self.init(bound: bound.then(on: zalgo) { NSNumber(integer: $0) })
}
convenience public init(bound: Promise<Void>) {
self.init(bound: bound.then(on: zalgo) { _ -> AnyObject? in return nil })
}
@objc init(@noescape bridge: ((AnyObject?) -> Void) -> Void) {
var resolve: ((Resolution) -> Void)!
state = UnsealedState(resolver: &resolve)
bridge { result in
func preresolve(obj: AnyObject?) {
resolve(box(obj))
}
if let next = result as? AnyPromise {
next.pipe(preresolve)
} else {
preresolve(result)
}
}
}
@objc func pipe(body: (AnyObject?) -> Void) {
state.get { seal in
func prebody(resolution: Resolution) {
body(unbox(resolution))
}
switch seal {
case .Pending(let handlers):
handlers.append(prebody)
case .Resolved(let resolution):
prebody(resolution)
}
}
}
@objc var __value: AnyObject? {
if let resolution = state.get() {
return unbox(resolution)
} else {
return nil
}
}
/**
A promise starts pending and eventually resolves.
@return True if the promise has not yet resolved.
*/
@objc public var pending: Bool {
return state.get() == nil
}
/**
A promise starts pending and eventually resolves.
@return True if the promise has resolved.
*/
@objc public var resolved: Bool {
return !pending
}
/**
A promise starts pending and eventually resolves.
A fulfilled promise is resolved and succeeded.
@return True if the promise was fulfilled.
*/
@objc public var fulfilled: Bool {
switch state.get() {
case .Some(.Fulfilled):
return true
default:
return false
}
}
/**
A promise starts pending and eventually resolves.
A rejected promise is resolved and failed.
@return True if the promise was rejected.
*/
@objc public var rejected: Bool {
switch state.get() {
case .Some(.Rejected):
return true
default:
return false
}
}
// because you can’t access top-level Swift functions in objc
@objc class func setUnhandledErrorHandler(body: (NSError) -> Void) -> (NSError) -> Void {
let oldHandler = PMKUnhandledErrorHandler
PMKUnhandledErrorHandler = body
return oldHandler
}
}
extension AnyPromise: DebugPrintable {
override public var debugDescription: String {
return "AnyPromise: \(state)"
}
}
import Dispatch
import Foundation.NSError
public func dispatch_promise<T>(on queue: dispatch_queue_t = dispatch_get_global_queue(0, 0), body: () -> T) -> Promise<T> {
return Promise { sealant in
contain_zalgo(queue) {
sealant.resolve(body())
}
}
}
// TODO Swift 1.2 thinks that usage of the following two is ambiguous
//public func dispatch_promise<T>(on queue: dispatch_queue_t = dispatch_get_global_queue(0, 0), body: () -> Promise<T>) -> Promise<T> {
// return Promise { sealant in
// contain_zalgo(queue) {
// body().pipe(sealant.handler)
// }
// }
//}
public func dispatch_promise<T>(on: dispatch_queue_t = dispatch_get_global_queue(0, 0), body: () -> (T!, NSError!)) -> Promise<T> {
return Promise{ (sealant: Sealant) -> Void in
contain_zalgo(on) {
let (a, b) = body()
sealant.resolve(a, b)
}
}
}
import Foundation.NSError
/**
The unhandled error handler.
If a promise is rejected and no catch handler is called in its chain, the
provided handler is called. The default handler logs the error.
PMKUnhandledErrorHandler = { error in
println("Unhandled error: \(error)")
}
@warning *Important* The handler is executed on an undefined queue.
@warning *Important* Don’t use promises in your handler, or you risk an
infinite error loop.
@return The previous unhandled error handler.
*/
public var PMKUnhandledErrorHandler = { (error: NSError) -> Void in
if !error.cancelled {
NSLog("PromiseKit: Unhandled error: %@", error)
}
}
private class Consumable: NSObject {
let parentError: NSError
var consumed: Bool = false
deinit {
if !consumed {
PMKUnhandledErrorHandler(parentError)
}
}
init(parent: NSError) {
// we take a copy to avoid a retain cycle. A weak ref
// is no good because then the error is deallocated
// before we can call PMKUnhandledErrorHandler()
parentError = parent.copy() as! NSError
}
}
private var handle: UInt8 = 0
func consume(error: NSError) {
let pmke = objc_getAssociatedObject(error, &handle) as! Consumable
pmke.consumed = true
}
extension AnyPromise {
// objc can't see Swift top-level function :(
//TODO move this and the one in AnyPromise to a compat something
@objc class func __consume(error: NSError) {
consume(error)
}
}
func unconsume(error: NSError) {
if let pmke = objc_getAssociatedObject(error, &handle) as! Consumable? {
pmke.consumed = false
} else {
// this is how we know when the error is deallocated
// because we will be deallocated at the same time
objc_setAssociatedObject(error, &handle, Consumable(parent: error), objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
}
private struct ErrorPair: Hashable {
let domain: String
let code: Int
init(_ d: String, _ c: Int) {
domain = d; code = c
}
var hashValue: Int {
return "\(domain):\(code)".hashValue
}
}
private func ==(lhs: ErrorPair, rhs: ErrorPair) -> Bool {
return lhs.domain == rhs.domain && lhs.code == rhs.code
}
private var cancelledErrorIdentifiers = Set([
ErrorPair(PMKErrorDomain, PMKOperationCancelled),
ErrorPair(NSURLErrorDomain, NSURLErrorCancelled)
])
extension NSError {
public class func cancelledError() -> NSError {
let info: [NSObject: AnyObject] = [NSLocalizedDescriptionKey: "The operation was cancelled"]
return NSError(domain: PMKErrorDomain, code: PMKOperationCancelled, userInfo: info)
}
/**
You may only call this on the main thread.
*/
public class func registerCancelledErrorDomain(domain: String, code: Int) {
cancelledErrorIdentifiers.insert(ErrorPair(domain, code))
}
public var cancelled: Bool {
return cancelledErrorIdentifiers.contains(ErrorPair(domain, code))
}
}
import Foundation
private func b0rkedEmptyRailsResponse() -> NSData {
return NSData(bytes: " ", length: 1)
}
public func NSJSONFromData(data: NSData) -> Promise<NSArray> {
if data == b0rkedEmptyRailsResponse() {
return Promise(NSArray())
} else {
return NSJSONFromDataT(data)
}
}
public func NSJSONFromData(data: NSData) -> Promise<NSDictionary> {
if data == b0rkedEmptyRailsResponse() {
return Promise(NSDictionary())
} else {
return NSJSONFromDataT(data)
}
}
private func NSJSONFromDataT<T>(data: NSData) -> Promise<T> {
var error: NSError?
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options:nil, error:&error)
if let cast = json as? T {
return Promise(cast)
} else if let error = error {
// NSJSONSerialization gives awful errors, so we wrap it
let debug = error.userInfo!["NSDebugDescription"] as? String
let description = "The server’s JSON response could not be decoded. (\(debug))"
return Promise(NSError(domain: PMKErrorDomain, code: PMKJSONError, userInfo: [
NSLocalizedDescriptionKey: "There was an error decoding the server’s JSON response.",
NSUnderlyingErrorKey: error
]))
} else {
var info = [NSObject: AnyObject]()
info[NSLocalizedDescriptionKey] = "The server returned JSON in an unexpected arrangement"
info[PMKJSONErrorJSONObjectKey] = json
return Promise(NSError(domain: PMKErrorDomain, code: PMKJSONError, userInfo: info))
}
}
import Foundation.NSError
extension Promise {
/**
@return The error with which this promise was rejected; nil if this promise is not rejected.
*/
public var error: NSError? {
switch state.get() {
case .None:
return nil
case .Some(.Fulfilled):
return nil
case .Some(.Rejected(let error)):
return error
}
}
/**
@return `YES` if the promise has not yet resolved.
*/
public var pending: Bool {
return state.get() == nil
}
/**
@return `YES` if the promise has resolved.
*/
public var resolved: Bool {
return !pending
}
/**
@return `YES` if the promise was fulfilled.
*/
public var fulfilled: Bool {
return value != nil
}
/**
@return `YES` if the promise was rejected.
*/
public var rejected: Bool {
return error != nil
}
}
import Foundation.NSError
public let PMKOperationQueue = NSOperationQueue()
public enum CatchPolicy {
case AllErrors
case AllErrorsExceptCancellation
}
/**
A promise represents the future value of a task.
To obtain the value of a promise we call `then`.
Promises are chainable: `then` returns a promise, you can call `then` on
that promise, which returns a promise, you can call `then` on that
promise, et cetera.
0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2
Promises start in a pending state and *resolve* with a value to become
*fulfilled* or with an `NSError` to become rejected.
@see [PromiseKit `then` Guide](http://promisekit.org/then/)
@see [PromiseKit Chaining Guide](http://promisekit.org/chaining/)
*/
public class Promise<T> {
let state: State
/**
Create a new pending promise.
Use this method when wrapping asynchronous systems that do *not* use
promises so that they can be involved in promise chains.
Don’t use this method if you already have promises! Instead, just return
your promise!
The closure you pass is executed immediately on the calling thread.
func fetchKitten() -> Promise<UIImage> {
return Promise { fulfill, reject in
KittenFetcher.fetchWithCompletionBlock({ img, err in
if err == nil {
fulfill(img)
} else {
reject(err)
}
})
}
}
@param resolvers The provided closure is called immediately. Inside,
execute your asynchronous system, calling fulfill if it suceeds and
reject for any errors.
@return A new promise.
@warning *Note* If you are wrapping a delegate-based system, we recommend
to use instead: defer
@see http://promisekit.org/sealing-your-own-promises/
@see http://promisekit.org/wrapping-delegation/
*/
public convenience init(@noescape resolvers: (fulfill: (T) -> Void, reject: (NSError) -> Void) -> Void) {
self.init(sealant: { sealant in
resolvers(fulfill: sealant.resolve, reject: sealant.resolve)
})
}
/**
Create a new pending promise.
This initializer is convenient when wrapping asynchronous systems that
use common patterns. For example:
func fetchKitten() -> Promise<UIImage> {
return Promise { sealant in
KittenFetcher.fetchWithCompletionBlock(sealant.resolve)
}
}
@see Sealant
@see init(resolvers:)
*/
public init(@noescape sealant: (Sealant<T>) -> Void) {
var resolve: ((Resolution) -> Void)!
state = UnsealedState(resolver: &resolve)
sealant(Sealant(body: resolve))
}
/**
Create a new fulfilled promise.
*/
public init(_ value: T) {
state = SealedState(resolution: .Fulfilled(value))
}
/**
Create a new rejected promise.
*/
public init(_ error: NSError) {
unconsume(error)
state = SealedState(resolution: .Rejected(error))
}
/**
I’d prefer this to be the designated initializer, but then there would be no
public designated unsealed initializer! Making this convenience would be
inefficient. Not very inefficient, but still it seems distasteful to me.
*/
init(passthru: ((Resolution) -> Void) -> Void) {
var resolve: ((Resolution) -> Void)!
state = UnsealedState(resolver: &resolve)
passthru(resolve)
}
/**
defer is convenient for wrapping delegates or larger asynchronous systems.
class Foo: BarDelegate {
let (promise, fulfill, reject) = Promise<Int>.defer()
func barDidFinishWithResult(result: Int) {
fulfill(result)
}
func barDidError(error: NSError) {
reject(error)
}
}
@return A tuple consisting of:
1) A promise
2) A function that fulfills that promise
3) A function that rejects that promise
*/
public class func defer() -> (promise: Promise, fulfill: (T) -> Void, reject: (NSError) -> Void) {
var sealant: Sealant<T>!
let promise = Promise { sealant = $0 }
return (promise, sealant.resolve, sealant.resolve)
}
func pipe(body: (Resolution) -> Void) {
state.get { seal in
switch seal {
case .Pending(let handlers):
handlers.append(body)
case .Resolved(let resolution):
body(resolution)
}
}
}
private convenience init<U>(when: Promise<U>, body: (Resolution, (Resolution) -> Void) -> Void) {
self.init(passthru: { resolve in
when.pipe{ body($0, resolve) }
})
}
/**
The provided block is executed when this Promise is resolved.
If you provide a block that takes a parameter, the value of the receiver will be passed as that parameter.
@param on The queue on which body should be executed.
@param body The closure that is executed when this Promise is fulfilled.
[NSURLConnection GET:url].then(^(NSData *data){
// do something with data
});
@return A new promise that is resolved with the value returned from the provided closure. For example:
[NSURLConnection GET:url].then(^(NSData *data){
return data.length;
}).then(^(NSNumber *number){
//…
});
@see thenInBackground
*/
public func then<U>(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: (T) -> U) -> Promise<U> {
return Promise<U>(when: self) { resolution, resolve in
switch resolution {
case .Rejected:
resolve(resolution)
case .Fulfilled(let value):
contain_zalgo(q) {
resolve(.Fulfilled(body(value as! T)))
}
}
}
}
public func then<U>(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: (T) -> Promise<U>) -> Promise<U> {
return Promise<U>(when: self) { resolution, resolve in
switch resolution {
case .Rejected:
resolve(resolution)
case .Fulfilled(let value):
contain_zalgo(q) {
body(value as! T).pipe(resolve)
}
}
}
}
public func then(on q: dispatch_queue_t = dispatch_get_main_queue(), body: (T) -> AnyPromise) -> Promise<AnyObject?> {
return Promise<AnyObject?>(when: self) { resolution, resolve in
switch resolution {
case .Rejected:
resolve(resolution)
case .Fulfilled(let value):
contain_zalgo(q) {
let anypromise = body(value as! T)
anypromise.pipe { obj in
if let error = obj as? NSError {
resolve(.Rejected(error))
} else {
// possibly the value of this promise is a PMKManifold, if so
// calling the objc `value` method will return the first item.
let obj: AnyObject? = anypromise.valueForKey("value")
resolve(.Fulfilled(obj))
}
}
}
}
}
}
/**
The provided closure is executed on the default background queue when this Promise is fulfilled.
This method is provided as a convenience for `then`.
@see then
*/
public func thenInBackground<U>(body: (T) -> U) -> Promise<U> {
return then(on: dispatch_get_global_queue(0, 0), body)
}
public func thenInBackground<U>(body: (T) -> Promise<U>) -> Promise<U> {
return then(on: dispatch_get_global_queue(0, 0), body)
}
/**
The provided closure is executed when this Promise is rejected.
Rejecting a promise cascades: rejecting all subsequent promises (unless
recover is invoked) thus you will typically place your catch at the end
of a chain. Often utility promises will not have a catch, instead
delegating the error handling to the caller.
The provided closure always runs on the main queue.
@param policy The default policy does not execute your handler for
cancellation errors. See registerCancellationError for more
documentation.
@param body The handler to execute when this Promise is rejected.
@see registerCancellationError
*/
public func catch(policy: CatchPolicy = .AllErrorsExceptCancellation, _ body: (NSError) -> Void) {
pipe { resolution in
switch resolution {
case .Fulfilled:
break
case .Rejected(let error):
if policy == .AllErrors || !error.cancelled {
dispatch_async(dispatch_get_main_queue()) {
consume(error)
body(error)
}
}
}
}
}
/**
The provided closure is executed when this Promise is rejected giving you
an opportunity to recover from the error and continue the promise chain.
*/
public func recover(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: (NSError) -> Promise<T>) -> Promise<T> {
return Promise(when: self) { resolution, resolve in
switch resolution {
case .Rejected(let error):
contain_zalgo(q) {
consume(error)
body(error).pipe(resolve)
}
case .Fulfilled:
resolve(resolution)
}
}
}
/**
The provided closure is executed when this Promise is resolved.
@param on The queue on which body should be executed.
@param body The closure that is executed when this Promise is resolved.
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
somePromise().then {
//…
}.finally {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
*/
public func finally(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: () -> Void) -> Promise<T> {
return Promise(when: self) { resolution, resolve in
contain_zalgo(q) {
body()
resolve(resolution)
}
}
}
/**
@return The value with which this promise was fulfilled or nil if this
promise is not fulfilled.
*/
public var value: T? {
switch state.get() {
case .None:
return nil
case .Some(.Fulfilled(let value)):
return (value as! T)
case .Some(.Rejected):
return nil
}
}
}
/**
Zalgo is dangerous.
Pass as the `on` parameter for a `then`. Causes the handler to be executed
as soon as it is resolved. That means it will be executed on the queue it
is resolved. This means you cannot predict the queue.
In the case that the promise is already resolved the handler will be
executed immediately.
zalgo is provided for libraries providing promises that have good tests
that prove unleashing zalgo is safe. You can also use it in your
application code in situations where performance is critical, but be
careful: read the essay at the provided link to understand the risks.
@see http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony
*/
public let zalgo: dispatch_queue_t = dispatch_queue_create("Zalgo", nil)
/**
Waldo is dangerous.
Waldo is zalgo, unless the current queue is the main thread, in which case
we dispatch to the default background queue.
If your block is likely to take more than a few milliseconds to execute,
then you should use waldo: 60fps means the main thread cannot hang longer
than 17 milliseconds. Don’t contribute to UI lag.
Conversely if your then block is trivial, use zalgo: GCD is not free and
for whatever reason you may already be on the main thread so just do what
you are doing quickly and pass on execution.
It is considered good practice for asynchronous APIs to complete onto the
main thread. Apple do not always honor this, nor do other developers.
However, they *should*. In that respect waldo is a good choice if your
then is going to take a while and doesn’t interact with the UI.
Please note (again) that generally you should not use zalgo or waldo. The
performance gains are neglible and we provide these functions only out of
a misguided sense that library code should be as optimized as possible.
If you use zalgo or waldo without tests proving their correctness you may
unwillingly introduce horrendous, near-impossible-to-trace bugs.
@see zalgo
*/
public let waldo: dispatch_queue_t = dispatch_queue_create("Waldo", nil)
func contain_zalgo(q: dispatch_queue_t, block: () -> Void) {
if q === zalgo {
block()
} else if q === waldo {
if NSThread.isMainThread() {
dispatch_async(dispatch_get_global_queue(0, 0), block)
} else {
block()
}
} else {
dispatch_async(q, block)
}
}
extension Promise {
/**
Creates a rejected Promise with `PMKErrorDomain` and a specified localizedDescription and error code.
*/
public convenience init(error: String, code: Int = PMKUnexpectedError) {
let error = NSError(domain: "PMKErrorDomain", code: code, userInfo: [NSLocalizedDescriptionKey: error])
self.init(error)
}
/**
Promise<Any> is more flexible, and often needed. However Swift won't cast
<T> to <Any> directly. Once that is possible we will deprecate this
function.
*/
public func asAny() -> Promise<Any> {
return Promise<Any>(passthru: pipe)
}
/**
Promise<AnyObject> is more flexible, and often needed. However Swift won't
cast <T> to <AnyObject> directly. Once that is possible we will deprecate
this function.
*/
public func asAnyObject() -> Promise<AnyObject> {
return Promise<AnyObject>(passthru: pipe)
}
/**
Swift (1.2) seems to be much less fussy about Void promises.
*/
public func asVoid() -> Promise<Void> {
return then(on: zalgo) { _ in return }
}
}
extension Promise: DebugPrintable {
public var debugDescription: String {
return "Promise: \(state)"
}
}
/**
Firstly can make chains more readable.
Compare:
NSURLConnection.GET(url1).then {
NSURLConnection.GET(url2)
}.then {
NSURLConnection.GET(url3)
}
With:
firstly {
NSURLConnection.GET(url1)
}.then {
NSURLConnection.GET(url2)
}.then {
NSURLConnection.GET(url3)
}
*/
public func firstly<T>(promise: () -> Promise<T>) -> Promise<T> {
return promise()
}
public func race<T>(promises: Promise<T>...) -> Promise<T> {
return Promise(passthru: { resolve in
for promise in promises {
promise.pipe(resolve)
}
})
}
import Foundation.NSError
public class Sealant<T> {
let handler: (Resolution) -> ()
init(body: (Resolution) -> Void) {
handler = body
}
/** internal because it is dangerous */
func __resolve(obj: AnyObject) {
switch obj {
case is NSError:
resolve(obj as! NSError)
default:
handler(.Fulfilled(obj))
}
}
public func resolve(value: T) {
handler(.Fulfilled(value))
}
public func resolve(error: NSError!) {
unconsume(error)
handler(.Rejected(error))
}
/**
Makes wrapping (typical) asynchronous patterns easy.
For example, here we wrap an `MKLocalSearch`:
func search() -> Promise<MKLocalSearchResponse> {
return Promise { sealant in
MKLocalSearch(request: …).startWithCompletionHandler(sealant.resolve)
}
}
To get this to work you often have to help the compiler by specifiying
the type. In future versions of Swift, this should become unecessary.
*/
public func resolve(obj: T!, var _ error: NSError!) {
if obj != nil {
handler(.Fulfilled(obj))
} else if error != nil {
resolve(error)
} else {
//FIXME couldn't get the constants from the umbrella header :(
error = NSError(domain: PMKErrorDomain, code: /*PMKUnexpectedError*/ 1, userInfo: nil)
resolve(error)
}
}
public func resolve(obj: T, _ error: NSError!) {
if error == nil {
handler(.Fulfilled(obj))
} else {
resolve(error)
}
}
/**
Provided for APIs that *still* return [AnyObject] because they suck.
FIXME fails
*/
// public func convert(objects: [AnyObject]!, _ error: NSError!) {
// if error != nil {
// resolve(error)
// } else {
// handler(.Fulfilled(objects))
// }
// }
/**
For the case where T is Void. If it isn’t stuff will crash at some point.
FIXME crashes when T is Void and .Fulfilled contains Void. Fucking sigh.
*/
// public func ignore<U>(obj: U, _ error: NSError!) {
// if error == nil {
// handler(.Fulfilled(T))
// } else {
// resolve(error)
// }
// }
}
import Foundation.NSError
enum Resolution {
case Fulfilled(Any) //TODO make type T when Swift can handle it
case Rejected(NSError)
}
enum Seal {
case Pending(Handlers)
case Resolved(Resolution)
}
protocol State {
func get() -> Resolution?
func get(body: (Seal) -> Void)
}
class UnsealedState: State {
private let barrier = dispatch_queue_create("org.promisekit.barrier", DISPATCH_QUEUE_CONCURRENT)
private var seal: Seal
/**
Quick return, but will not provide the handlers array
because it could be modified while you are using it by
another thread. If you need the handlers, use the second
`get` variant.
*/
func get() -> Resolution? {
var result: Resolution?
dispatch_sync(barrier) {
switch self.seal {
case .Resolved(let resolution):
result = resolution
case .Pending:
break
}
}
return result
}
func get(body: (Seal) -> Void) {
var sealed = false
dispatch_sync(barrier) {
switch self.seal {
case .Resolved:
sealed = true
case .Pending:
sealed = false
}
}
if !sealed {
dispatch_barrier_sync(barrier) {
switch (self.seal) {
case .Pending:
body(self.seal)
case .Resolved:
sealed = true // welcome to race conditions
}
}
}
if sealed {
body(seal)
}
}
init(inout resolver: ((Resolution) -> Void)!) {
seal = .Pending(Handlers())
resolver = { resolution in
var handlers: Handlers?
dispatch_barrier_sync(self.barrier) {
switch self.seal {
case .Pending(let hh):
self.seal = .Resolved(resolution)
handlers = hh
case .Resolved:
break
}
}
if let handlers = handlers {
for handler in handlers {
handler(resolution)
}
}
}
}
}
class SealedState: State {
private let resolution: Resolution
init(resolution: Resolution) {
self.resolution = resolution
}
func get() -> Resolution? {
return resolution
}
func get(body: (Seal) -> Void) {
body(.Resolved(resolution))
}
}
class Handlers: SequenceType {
var bodies: [(Resolution)->()] = []
func append(body: (Resolution)->()) {
bodies.append(body)
}
func generate() -> IndexingGenerator<[(Resolution)->()]> {
return bodies.generate()
}
var count: Int {
return bodies.count
}
}
extension Resolution: DebugPrintable {
var debugDescription: String {
switch self {
case Fulfilled(let value):
return "Fulfilled with value: \(value)"
case Rejected(let error):
return "Rejected with error: \(error)"
}
}
}
extension UnsealedState: DebugPrintable {
var debugDescription: String {
var rv: String?
get { seal in
switch seal {
case .Pending(let handlers):
rv = "Pending with \(handlers.count) handlers"
case .Resolved(let resolution):
rv = "\(resolution)"
}
}
return "UnsealedState: \(rv!)"
}
}
extension SealedState: DebugPrintable {
var debugDescription: String {
return "SealedState: \(resolution)"
}
}
import Foundation.NSProgress
private func when<T>(promises: [Promise<T>]) -> Promise<Void> {
let (rootPromise, fulfill, reject) = Promise<Void>.defer()
#if !PMKDisableProgress
let progress = NSProgress(totalUnitCount: Int64(promises.count))
progress.cancellable = false
progress.pausable = false
#else
var progress: (completedUnitCount: Int, totalUnitCount: Int) = (0, 0)
#endif
var countdown = promises.count
for (index, promise) in enumerate(promises) {
promise.pipe { resolution in
if rootPromise.pending {
switch resolution {
case .Rejected(let error):
progress.completedUnitCount = progress.totalUnitCount
//TODO PMKFailingPromiseIndexKey
reject(error)
case .Fulfilled:
progress.completedUnitCount++
if --countdown == 0 {
fulfill()
}
}
}
}
}
return rootPromise
}
public func when<T>(promises: [Promise<T>]) -> Promise<[T]> {
return when(promises).then(on: zalgo) { promises.map{ $0.value! } }
}
public func when<T>(promises: Promise<T>...) -> Promise<[T]> {
return when(promises)
}
public func when(promises: Promise<Void>...) -> Promise<Void> {
return when(promises)
}
public func when<U, V>(pu: Promise<U>, pv: Promise<V>) -> Promise<(U, V)> {
return when(pu.asVoid(), pv.asVoid()).then(on: zalgo) { (pu.value!, pv.value!) }
}
public func when<U, V, X>(pu: Promise<U>, pv: Promise<V>, px: Promise<X>) -> Promise<(U, V, X)> {
return when(pu.asVoid(), pv.asVoid(), px.asVoid()).then(on: zalgo) { (pu.value!, pv.value!, px.value!) }
}
@availability(*, unavailable, message="Use `when`")
public func join<T>(promises: Promise<T>...) {}
let PMKErrorDomain = "PMKErrorDomain"
let PMKFailingPromiseIndexKey = "PMKFailingPromiseIndexKey"
let PMKURLErrorFailingURLResponseKey = "PMKURLErrorFailingURLResponseKey"
let PMKURLErrorFailingDataKey = "PMKURLErrorFailingDataKey"
let PMKURLErrorFailingStringKey = "PMKURLErrorFailingStringKey"
let PMKJSONErrorJSONObjectKey = "PMKJSONErrorJSONObjectKey"
let PMKUnexpectedError = 1
let PMKUnknownError = 2
let PMKInvalidUsageError = 3
let PMKAccessDeniedError = 4
let PMKOperationCancelled = 5
let PMKNotFoundError = 6
let PMKJSONError = 7
let PMKOperationFailed = 8
let PMKTaskError = 9
let PMKTaskErrorLaunchPathKey = "PMKTaskErrorLaunchPathKey"
let PMKTaskErrorArgumentsKey = "PMKTaskErrorArgumentsKey"
let PMKTaskErrorStandardOutputKey = "PMKTaskErrorStandardOutputKey"
let PMKTaskErrorStandardErrorKey = "PMKTaskErrorStandardErrorKey"
let PMKTaskErrorExitStatusKey = "PMKTaskErrorExitStatusKey"
|
mit
|
e78d58e490f40c89bf260c4bc5cc8535
| 28.56348 | 135 | 0.599793 | 4.399184 | false | false | false | false |
gbuela/kanjiryokucha
|
KanjiRyokucha/CredentialsViewController.swift
|
1
|
3595
|
//
// CredentialsViewController.swift
// KanjiRyokucha
//
// Created by German Buela on 12/17/16.
// Copyright © 2016 German Buela. All rights reserved.
//
import UIKit
import PKHUD
import ReactiveSwift
import SafariServices
let usernameKey = "username"
let passwordKey = "passwordKey"
let httpStatusMovedTemp = 302
class CredentialsViewController: UIViewController, UITextFieldDelegate, BackendAccess {
private class func notEmpty(string: String?) -> Bool {
return string != nil && string != ""
}
@IBOutlet weak var versionLabel: UILabel!
@IBOutlet weak var loginContainer: UIView!
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var storeSwitch: UISwitch!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var signupButton: UIButton!
var enteredCredentialsCallback: ((String, String) -> ())?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .ryokuchaFaint
let versionNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
versionLabel.text = versionNumber
let tap = UITapGestureRecognizer(target: self, action: #selector(userTappedBackground))
view.addGestureRecognizer(tap)
loginButton.isEnabled = false
loginButton.titleLabel?.adjustsFontForContentSizeCategory = true
signupButton.titleLabel?.adjustsFontForContentSizeCategory = true
wireUp()
}
func wireUp() {
loginButton.reactive.isEnabled <~
usernameField.reactive.continuousTextValues.map(CredentialsViewController.notEmpty).combineLatest(with: passwordField.reactive.continuousTextValues.map(CredentialsViewController.notEmpty)).map { $0 && $1 }
}
@IBAction func userTappedBackground() {
view.endEditing(true)
}
@IBAction func loginPressed(_ sender: AnyObject) {
attemptLogin()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let nextTag = textField.tag + 1;
if let nextView = textField.superview?.viewWithTag(nextTag) {
nextView.becomeFirstResponder()
} else {
textField.resignFirstResponder()
attemptLogin()
}
return false
}
private func attemptLogin() {
guard let username = usernameField.text,
let password = passwordField.text,
username != "" &&
password != ""
else {
showAlert("Please enter all fields")
return
}
view.endEditing(true)
let defaults = UserDefaults()
if storeSwitch.isOn {
defaults.set(username, forKey: usernameKey)
defaults.set(password, forKey: passwordKey)
} else {
defaults.set(nil, forKey: usernameKey)
defaults.set(nil, forKey: passwordKey)
}
dismiss(animated: true) { [weak self] in
self?.enteredCredentialsCallback?(username, password)
}
}
@IBAction func signupPressed(_ sender: AnyObject) {
guard let url = URL(string: backendHost + "/account/create") else { return }
let safariVC = SFSafariViewController(url: url)
safariVC.preferredBarTintColor = .ryokuchaDark
safariVC.preferredControlTintColor = .white
present(safariVC, animated: true, completion: nil)
}
}
|
mit
|
dee30240bfc6f516bd6a86ca2013c050
| 30.526316 | 217 | 0.637173 | 5.277533 | false | false | false | false |
thedistance/TheDistanceCore
|
TDCore/Extensions/UIImage.swift
|
1
|
5165
|
//
// UIImage.swift
// Pods
//
// Created by Josh Campion on 16/02/2016.
//
//
import UIKit
public extension UIImage {
/**
Creates a new image scaled to maintain the curent aspect ratio where the scaled image will have a maximum dimension of the given size.
- seealso: `scaledImage(_:sy:)`
- seealso: `scaledToMaxDimension(_:)`
- parameter dim: The maximum size of either the width or height of the scaled image.
- returns: The scaled image.
*/
func scaledToMaxDimension(_ dim: CGFloat) -> UIImage {
let ratio = dim / max(size.width, size.height)
return scaledImage(ratio, sy: ratio)
}
/**
Creates a new image scaled to the exact size given.
- seealso: `scaledImage(_:sy:)`
- seealso: `scaledToMaxDimension(_:)`
- parameter size: The size in px to create this image.
- returns: The scaled image.
*/
func scaledImageToSize(_ size: CGSize) -> UIImage {
let sx = size.width / self.size.width
let sy = size.height / self.size.height
return scaledImage(sx, sy: sy)
}
/**
Creates a new image in a `CGBitMapContext` scaled to the given proportions.
- seealso: `scaledImageToSize(_:)`
- seealso: `scaledToMaxDimension(_:)`
- returns: The scaled image.
*/
func scaledImage(_ sx:CGFloat, sy: CGFloat) -> UIImage {
let scaledSize = CGSize(width: size.width * sx, height: size.height * sy)
let cgImg = self.cgImage
let ctx = CGContext(data: nil, width: Int(scaledSize.width), height: Int(scaledSize.height),
bitsPerComponent: cgImg!.bitsPerComponent, bytesPerRow: 0,
space: cgImg!.colorSpace!,
bitmapInfo: cgImg!.bitmapInfo.rawValue)
ctx!.draw(cgImg!, in: CGRect(x: 0,y: 0,width: scaledSize.width, height: scaledSize.height))
let newImage = UIImage(cgImage:ctx!.makeImage()!)
return newImage
}
/**
A new `UIImage` created from applying a transform to the image in a CGContext. The rotation of the image is no longer stored in image meta data which is useful for uploading images to servers which don't interpret the meta data.
- returns: The rotated image.
*/
public func orientationNeutralImage() -> UIImage! {
// No-op if the orientation is already correct
if (self.imageOrientation == .up) {
return self
}
// We need to calculate the proper transformation to make the image upright.
// We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
var transform = CGAffineTransform.identity
switch (self.imageOrientation) {
case .down, .downMirrored:
transform = transform.translatedBy(x: self.size.width, y: self.size.height)
transform = transform.rotated(by: .pi)
case .left,.leftMirrored:
transform = transform.translatedBy(x: self.size.width, y: 0)
transform = transform.rotated(by: CGFloat(Double.pi))
case .right, .rightMirrored:
transform = transform.translatedBy(x: 0, y: self.size.height)
transform = transform.rotated(by: CGFloat(-Double.pi))
default:
transform = transform.concatenating(CGAffineTransform.identity)
}
switch (self.imageOrientation) {
case .upMirrored, .downMirrored:
transform = transform.translatedBy(x: self.size.width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
case .leftMirrored, .rightMirrored:
transform = transform.translatedBy(x: self.size.height, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
default:
transform = transform.concatenating(CGAffineTransform.identity)
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
let ctx = CGContext(data: nil, width: Int(self.size.width), height: Int(self.size.height),
bitsPerComponent: self.cgImage!.bitsPerComponent, bytesPerRow: 0,
space: self.cgImage!.colorSpace!,
bitmapInfo: self.cgImage!.bitmapInfo.rawValue)
ctx!.concatenate(transform)
switch (self.imageOrientation) {
case .left, .leftMirrored, .right, .rightMirrored:
// Grr...
ctx!.draw(self.cgImage!, in: CGRect(x: 0,y: 0,width: self.size.height,height: self.size.width))
default:
ctx!.draw(self.cgImage!, in: CGRect(x: 0,y: 0,width: self.size.width,height: self.size.height))
}
// And now we just create a new UIImage from the drawing context
let cgimg = ctx!.makeImage()
let img = UIImage(cgImage:cgimg!)
return img
}
}
|
mit
|
1eeadce66f5f96f0bd692bd13d755563
| 34.376712 | 233 | 0.582962 | 4.678442 | false | false | false | false |
lorentey/swift
|
test/IDE/print_swift_module.swift
|
10
|
2138
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module-path %t/print_swift_module.swiftmodule -emit-module-doc -emit-module-doc-path %t/print_swift_module.swiftdoc %s
// RUN: %target-swift-ide-test -print-module -print-interface -no-empty-line-between-members -module-to-print=print_swift_module -I %t -source-filename=%s > %t.syn.txt
// RUN: %target-swift-ide-test -print-module -access-filter-internal -no-empty-line-between-members -module-to-print=print_swift_module -I %t -source-filename=%s > %t.syn.internal.txt
// RUN: %FileCheck %s -check-prefix=CHECK1 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK2 < %t.syn.internal.txt
public protocol P1 {
/// foo1 comment from P1
func foo1()
/// foo2 comment from P1
func foo2()
}
public class C1 : P1 {
public func foo1() {
}
/// foo2 comment from C1
public func foo2() {
}
}
/// Alias comment
public typealias Alias<T> = (T, T)
/// returnsAlias() comment
public func returnsAlias() -> Alias<Int> {
return (0, 0)
}
@_functionBuilder
struct BridgeBuilder {}
public struct City {
public init(@BridgeBuilder builder: () -> ()) {}
}
// CHECK1: /// Alias comment
// CHECK1-NEXT: typealias Alias<T> = (T, T)
// CHECK1: public class C1 : print_swift_module.P1 {
// CHECK1-NEXT: /// foo1 comment from P1
// CHECK1-NEXT: public func foo1()
// CHECK1-NEXT: /// foo2 comment from C1
// CHECK1-NEXT: public func foo2()
// CHECK1-NEXT: }
// CHECK1: public init(@print_swift_module.BridgeBuilder builder: () -> ())
// CHECK1: public protocol P1 {
// CHECK1-NEXT: /// foo1 comment from P1
// CHECK1-NEXT: func foo1()
// CHECK1-NEXT: /// foo2 comment from P1
// CHECK1-NEXT: func foo2()
// CHECK1-NEXT: }
// CHECK1: /// returnsAlias() comment
// CHECK1-NEXT: func returnsAlias() -> print_swift_module.Alias<Int>
// CHECK2: struct Event {
public struct Event {
public var start: Int
public var end: Int?
public var repeating: ((), Int?)
public var name = "untitled event"
// CHECK2: init(start: Int, end: Int? = nil, repeating: ((), Int?) = ((), nil), name: String = "untitled event")
}
// CHECK2: }
|
apache-2.0
|
ecfaa4817c2ad292ce4cac188ea9490a
| 30.441176 | 183 | 0.658092 | 3.019774 | false | false | false | false |
IvanKalaica/GitHubSearch
|
GitHubSearch/GitHubSearch/Model/Entities/Repository.swift
|
1
|
1107
|
//
// Repository.swift
// GitHubSearch
//
// Created by Ivan Kalaica on 21/09/2017.
// Copyright © 2017 Kalaica. All rights reserved.
//
import Foundation
import SwiftyJSON
struct Repository {
let id: String
let name: String
let watchersCount: Int
let forksCount: Int
let openIssuesCount: Int
let language: String
let createdAt: Date
let updatedAt: Date
let owner: User
}
extension Repository: Decodable {
init(data: Any) throws {
try self.init(jsonData: JSON(data))
}
init(jsonData: JSON) throws {
self.id = jsonData["id"].stringValue
self.name = jsonData["name"].stringValue
self.watchersCount = jsonData["watchers_count"].intValue
self.forksCount = jsonData["forks_count"].intValue
self.openIssuesCount = jsonData["open_issues_count"].intValue
self.language = jsonData["language"].stringValue
self.createdAt = try jsonData["created_at"].dateOrThrow()
self.updatedAt = try jsonData["updated_at"].dateOrThrow()
self.owner = try User(jsonData: jsonData["owner"])
}
}
|
mit
|
503e2643ea93cbc635fee28fb271f84c
| 27.358974 | 69 | 0.664557 | 4.126866 | false | false | false | false |
loisie123/Cuisine-Project
|
Cuisine/extension.swift
|
1
|
6788
|
//
// extension.swift
// Cuisine
//
// Created by Lois van Vliet on 31-01-17.
// Copyright © 2017 Lois van Vliet. All rights reserved.
//
import Foundation
import Firebase
extension UIViewController{
//MARK:- function to remove and show keyboard.
//reference: http://stackoverflow.com/questions/24126678/close-ios-keyboard-by-touching-anywhere-using-swift
func hideKeyboardWhenTappedAround(){
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
}
func dismissKeyboard(){
view.endEditing(true)
}
//MARK:- Alertcontroller
func showAlert(titleAlert: String , messageAlert: String){
let alertcontroller = UIAlertController(title: titleAlert, message: messageAlert, preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .default)
alertcontroller.addAction(cancelAction)
self.present(alertcontroller, animated: true, completion: nil)
}
//MARK:- Function to make Sections
func makeSectionHeader(returnedView: UIView, section : Int , listAllNames: [[String]]) -> (UIView){
let color = UIColor(red: 121.0/255.0, green: 172.0/255.0, blue: 43.0/255.0, alpha: 0.5)
returnedView.backgroundColor = color
let label = UILabel(frame: CGRect(x: 5, y: 5, width: view.frame.size.width, height: 20))
label.textAlignment = NSTextAlignment.center
label.font = UIFont.systemFont(ofSize: 18)
//label.font = UIFont.boldSystemFont(ofSize: 20)
label.text = listAllNames[section][0]
label.textColor = .black
returnedView.addSubview(label)
return returnedView
}
//MARK:- Functions that get information from Firebase
func getWeekDays(snapshot: FIRDataSnapshot) -> ([String]){
let dictionary = snapshot.value as? NSDictionary
let array = dictionary?.allKeys as! [String]
let days = array.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }
return days
}
func getMealInformation(snapshot: FIRDataSnapshot, categories: [String], kindOfCategorie: String) -> ([[String]], [meals]) {
let meal = snapshot.value as! [String:AnyObject]
var listAllNames = [[String]]()
var listOfmeals = [meals]()
let categorie = categories
for category in categorie {
var listCategoryName = [String]()
listCategoryName.append(category)
for (_,value) in meal{
let showmeals = meals()
if let cat = value[kindOfCategorie] as? String{
if cat == category{
if let likes = value["likes"] as? Int,
let name = value["name"] as? String,
let price = value["price"] as? String{
listCategoryName.append(name)
showmeals.name = name
showmeals.price = price
showmeals.likes = likes
showmeals.typeOFMEal = category
if let days = value["day"] as? String{
showmeals.day = days
}
if let people = value["peoplewholike"] as? [String : AnyObject] {
for (_,person) in people{
showmeals.peopleWhoLike.append(person as! String)
}
}
listOfmeals.append(showmeals)
}
}
}
}
listAllNames.append(listCategoryName)
}
return (listAllNames, listOfmeals)
}
//MARK: delete functions with both different references.
// reference: http://stackoverflow.com/questions/39631998/how-to-delete-from-firebase-database
func myDeleteFunction(firstTree: String, secondTree: String, childIWantToRemove: String) {
var ref:FIRDatabaseReference?
ref = FIRDatabase.database().reference()
ref?.child(firstTree).child(secondTree).child(childIWantToRemove).removeValue { (error, ref) in
if error != nil {
print("error \(error)")
}
else{
print ("removed")
}
}
}
func myDeleteFunctionExtra(firstTree: String, secondTree: String, childIWantToRemove: String) {
var ref:FIRDatabaseReference?
ref?.child("cormet").child(firstTree).child(secondTree).child(childIWantToRemove).removeValue { (error, ref) in
if error != nil {
print("error \(error)")
}
else{
print ("removed")
}
}
}
}
//MARK:- SaveMeal when meal is liked
extension UITableViewCell{
func saveMeal(user: String, name: String, price: String, count: Int, type : String, day: String, child: String){
let ref = FIRDatabase.database().reference()
ref.child("users").child(user).child("likes").child(name).child("name").setValue(name)
ref.child("users").child(user).child("likes").child(name).child("price").setValue(price)
ref.child("users").child(user).child("likes").child(name).child("likes").setValue(count)
ref.child("users").child(user).child("likes").child(name).child("day").setValue(day)
ref.child("users").child(user).child("likes").child(name).child("type").setValue(type)
ref.child("users").child(user).child("likes").child(name).child("child").setValue(child)
}
//MARK:- delete function. reference: http://stackoverflow.com/questions/39631998/how-to-delete-from-firebase-database
func myDeleteFunction(firstTree: String, secondTree: String, childIWantToRemove: String) {
let ref = FIRDatabase.database().reference()
ref.child("users").child(firstTree).child(secondTree).child(childIWantToRemove).removeValue { (error, ref) in
if error != nil {
print("error \(error)")
}
else{
print ("removed")
}
}
}
}
|
mit
|
22034750561c306143ca18728f688981
| 36.291209 | 135 | 0.550611 | 4.896825 | false | false | false | false |
mparrish91/gifRecipes
|
application/UserViewController.swift
|
1
|
1107
|
//
// UserViewController.swift
// reddift
//
// Created by sonson on 2016/09/13.
// Copyright © 2016年 sonson. All rights reserved.
//
import Foundation
class UserViewController: UIViewController {
let name: String
class func controller(_ name: String) -> UINavigationController {
let con = UserViewController(name)
let nav = UINavigationController(rootViewController: con)
return nav
}
required init?(coder aDecoder: NSCoder) {
name = ""
super.init(coder: aDecoder)
}
init(_ aName: String) {
name = aName
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
let barbutton = UIBarButtonItem(title: "Close", style: .plain, target: self, action: #selector(UserViewController.close(sender:)))
self.navigationItem.rightBarButtonItem = barbutton
view.backgroundColor = UIColor.white
self.navigationItem.title = name
}
func close(sender: Any) {
dismiss(animated: true, completion: nil)
}
}
|
mit
|
cc0c576b751103dba32910e6d756752c
| 25.285714 | 138 | 0.633152 | 4.6 | false | false | false | false |
csnu17/My-Swift-learning
|
DrawingPathsAndShapes/Landmarks/Landmarks/Supporting Views/BadgeSymbol.swift
|
2
|
1729
|
/*
See LICENSE folder for this sample’s licensing information.
Abstract:
A view that display a symbol in a badge.
*/
import SwiftUI
struct BadgeSymbol: View {
static let symbolColor = Color(red: 79.0 / 255, green: 79.0 / 255, blue: 191.0 / 255)
var body: some View {
GeometryReader { geometry in
Path { path in
let width = min(geometry.size.width, geometry.size.height)
let height = width * 0.75
let spacing = width * 0.030
let middle = width / 2
let topWidth = 0.226 * width
let topHeight = 0.488 * height
path.addLines([
CGPoint(x: middle, y: spacing),
CGPoint(x: middle - topWidth, y: topHeight - spacing),
CGPoint(x: middle, y: topHeight / 2 + spacing),
CGPoint(x: middle + topWidth, y: topHeight - spacing),
CGPoint(x: middle, y: spacing)
])
path.move(to: CGPoint(x: middle, y: topHeight / 2 + spacing * 3))
path.addLines([
CGPoint(x: middle - topWidth, y: topHeight + spacing),
CGPoint(x: spacing, y: height - spacing),
CGPoint(x: width - spacing, y: height - spacing),
CGPoint(x: middle + topWidth, y: topHeight + spacing),
CGPoint(x: middle, y: topHeight / 2 + spacing * 3)
])
}
.fill(Self.symbolColor)
}
}
}
#if DEBUG
struct BadgeSymbol_Previews: PreviewProvider {
static var previews: some View {
BadgeSymbol()
}
}
#endif
|
mit
|
a7ac0fbe1f89280bcfd1d5a0feaa8d2d
| 32.862745 | 89 | 0.503185 | 4.383249 | false | false | false | false |
joerocca/GitHawk
|
Local Pods/Highlightr/Example/Highlightr/SampleCode.swift
|
1
|
6135
|
//
// SampleCode.swift
// Highlightr
//
// Created by Illanes, J.P. on 5/5/16.
//
import UIKit
import Highlightr
import ActionSheetPicker_3_0
enum pickerSource : Int {
case theme = 0
case language
}
class SampleCode: UIViewController
{
@IBOutlet weak var navBar: UINavigationBar!
@IBOutlet weak var toolBar: UIToolbar!
@IBOutlet weak var viewPlaceholder: UIView!
var textView : UITextView!
@IBOutlet var textToolbar: UIToolbar!
@IBOutlet weak var languageName: UILabel!
@IBOutlet weak var themeName: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
var highlightr : Highlightr!
let textStorage = CodeAttributedString()
override func viewDidLoad()
{
super.viewDidLoad()
activityIndicator.isHidden = true
languageName.text = "Swift"
themeName.text = "Pojoaque"
textStorage.language = languageName.text?.lowercased()
let layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)
let textContainer = NSTextContainer(size: view.bounds.size)
layoutManager.addTextContainer(textContainer)
textView = UITextView(frame: viewPlaceholder.bounds, textContainer: textContainer)
textView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
textView.autocorrectionType = UITextAutocorrectionType.no
textView.autocapitalizationType = UITextAutocapitalizationType.none
textView.textColor = UIColor(white: 0.8, alpha: 1.0)
textView.inputAccessoryView = textToolbar
viewPlaceholder.addSubview(textView)
let code = try! String.init(contentsOfFile: Bundle.main.path(forResource: "sampleCode", ofType: "txt")!)
textView.text = code
highlightr = textStorage.highlightr
updateColors()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
@IBAction func pickLanguage(_ sender: AnyObject)
{
let languages = highlightr.supportedLanguages()
let indexOrNil = languages.index(of: languageName.text!.lowercased())
let index = (indexOrNil == nil) ? 0 : indexOrNil!
ActionSheetStringPicker.show(withTitle: "Pick a Language",
rows: languages,
initialSelection: index,
doneBlock:
{ picker, index, value in
let language = value! as! String
self.textStorage.language = language
self.languageName.text = language.capitalized
let snippetPath = Bundle.main.path(forResource: "default", ofType: "txt", inDirectory: "Samples/\(language)", forLocalization: nil)
let snippet = try! String(contentsOfFile: snippetPath!)
self.textView.text = snippet
},
cancel: nil,
origin: toolBar)
}
@IBAction func performanceTest(_ sender: AnyObject)
{
let code = textStorage.string
activityIndicator.isHidden = false
activityIndicator.startAnimating()
DispatchQueue.global(qos: .userInteractive).async {
let start = Date()
for _ in 0...100
{
_ = self.highlightr.highlight(code, as: self.languageName.text!)
}
let end = Date()
let time = Float(end.timeIntervalSince(start));
let avg = String(format:"%0.4f", time/100)
let total = String(format:"%0.3f", time)
let alert = UIAlertController(title: "Performance test", message: "This code was highlighted 100 times. \n It took an average of \(avg) seconds to process each time,\n with a total of \(total) seconds", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
alert.addAction(okAction)
DispatchQueue.main.async(execute: {
self.activityIndicator.isHidden = true
self.activityIndicator.stopAnimating()
self.present(alert, animated: true, completion: nil)
})
}
}
@IBAction func pickTheme(_ sender: AnyObject)
{
hideKeyboard(nil)
let themes = highlightr.availableThemes()
let indexOrNil = themes.index(of: themeName.text!.lowercased())
let index = (indexOrNil == nil) ? 0 : indexOrNil!
ActionSheetStringPicker.show(withTitle: "Pick a Theme",
rows: themes,
initialSelection: index,
doneBlock:
{ picker, index, value in
let theme = value! as! String
self.textStorage.highlightr.setTheme(to: theme)
self.themeName.text = theme.capitalized
self.updateColors()
},
cancel: nil,
origin: toolBar)
}
@IBAction func hideKeyboard(_ sender: AnyObject?)
{
textView.resignFirstResponder()
}
func updateColors()
{
textView.backgroundColor = highlightr.theme.themeBackgroundColor
navBar.barTintColor = highlightr.theme.themeBackgroundColor
navBar.tintColor = invertColor(navBar.barTintColor!)
languageName.textColor = navBar.tintColor
themeName.textColor = navBar.tintColor.withAlphaComponent(0.5)
toolBar.barTintColor = navBar.barTintColor
toolBar.tintColor = navBar.tintColor
}
func invertColor(_ color: UIColor) -> UIColor
{
var r:CGFloat = 0, g:CGFloat = 0, b:CGFloat = 0
color.getRed(&r, green: &g, blue: &b, alpha: nil)
return UIColor(red:1.0-r, green: 1.0-g, blue: 1.0-b, alpha: 1)
}
}
|
mit
|
9d5766a4fa1cdf29f249d7cb86ea5379
| 35.301775 | 238 | 0.583211 | 5.320902 | false | false | false | false |
diwip/inspector-ios
|
Inspector/Services/NetworkHandler.swift
|
1
|
2458
|
//
// NetworkHandler.swift
// Inspector
//
// Created by Kevin Hury on 5/10/15.
// Copyright (c) 2015 diwip. All rights reserved.
//
import Cocoa
import SwiftyJSON
final class NetworkHandler {
var currentConnection: DeviceConnection?
private func makeRequestURL(forMethod: String) -> NSURL {
let components = NSURLComponents()
components.port = 9998
components.host = currentConnection?.address
components.path = "/" + forMethod
components.scheme = "http"
return components.URL!
}
func getNodeTree() -> TNode! {
guard let data = NSData(contentsOfURL: makeRequestURL("getNodeTree")) else { return nil }
return ThriftUtils.thriftObject(data) as TNode
}
func nodeSelected(node: TNode!) {
let request = NSMutableURLRequest(URL: makeRequestURL("nodeSelected"))
request.HTTPMethod = "POST"
request.HTTPBody = ThriftUtils.dataFromThriftObject(node)
_ = try? NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
}
func nodeModified(nodeHash: String, prop: TNodeProperty!) {
let request = NSMutableURLRequest(URL: makeRequestURL("nodeModified"))
request.HTTPMethod = "POST"
request.addValue(nodeHash, forHTTPHeaderField: "nodeHash")
request.HTTPBody = ThriftUtils.dataFromThriftObject(prop)
_ = try? NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
}
func getResourcesCache() -> JSON? {
guard let data = NSData(contentsOfURL: makeRequestURL("caches")) else { return nil }
return JSON(data: data)
}
func getImageRepresentation(nodeHash: String) -> NSImage? {
let request = NSMutableURLRequest(URL: makeRequestURL("imageRepresentation"))
request.HTTPMethod = "POST"
request.addValue(nodeHash, forHTTPHeaderField: "nodeHash")
guard let data = try? NSURLConnection.sendSynchronousRequest(request, returningResponse: nil) else { return nil }
return NSImage(data: data)
}
func markSelectedNode(mark: Int) {
let request = NSMutableURLRequest(URL: makeRequestURL("markSelectedNode"))
request.HTTPMethod = "POST"
request.addValue(String(mark), forHTTPHeaderField: "marking")
_ = try? NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
}
}
|
mit
|
826627a5c817e107ef17a8e47eec9cbf
| 34.637681 | 121 | 0.666395 | 4.800781 | false | false | false | false |
myandy/shi_ios
|
shishi/UI/Edit/EditPagerView.swift
|
1
|
9856
|
//
// EditPagerView.swift
// shishi
//
// Created by andymao on 2017/4/23.
// Copyright © 2017年 andymao. All rights reserved.
//
import UIKit
private let editCellIdentifier = "editCellIdentifier"
private let TOP_HEIGHT = 60
public class EditPagerView : UIView {
//是否需要保存,如果有编辑才需要保存
public var hasEdit = false
public var writing: Writting!
//列表
fileprivate var tableView: UITableView!
fileprivate var clist: Array<String>!
//已经输入的内容
fileprivate var contentArray: [String?]!
fileprivate var title: UILabel!
//背景图片
fileprivate var defaultImage = PoetryImage.dust
//顶部背景
fileprivate var headView: UIImageView!
//中间的TABLEVIEW的背景
fileprivate var backgroundImageView: UIImageView!
//是否是自由格律
internal var isFreeFormer = false
//自由格律的输入框
internal var freeEditView: UITextView!
// public override init(frame: CGRect) {
// super.init(frame: frame)
// self.setupSubviews()
//
// let image = UIImage(named: EditPagerView.bgimgList[Int(writing.bgImg)]) ?? self.defaultImage.image()
// self.updateImage(image: image)
// }
init(writting: Writting) {
super.init(frame: CGRect.zero)
self.writing = writting
let former = writing.former
//自由
if former.pingze == nil {
clist = [""]
self.isFreeFormer = true
}
else {
let slist = former.pingze.characters.split(separator: "。").map(String.init)
clist = EditUtils.getCodeFromPingze(list: slist)
}
if self.isFreeFormer {
self.contentArray = [writting.text]
}
else {
self.contentArray = Array.init(repeating: nil, count: clist.count)
let textArray = writting.text.components(separatedBy: Writting.textSeparator)
for (index, item) in textArray.enumerated() {
self.contentArray[index] = item
}
}
self.setupSubviews()
if let poetryImage = PoetryImage(rawValue: Int(writting.bgImg)) {
let image = poetryImage.image()
self.updateImage(image: image)
}
if self.isFreeFormer {
self.freeEditView.text = writting.text
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal func setupSubviews() {
// //测试代码
// if writing == nil{
// writing = Writting()
// }
setupHeadView()
self.backgroundImageView = UIImageView()
self.addSubview(self.backgroundImageView)
self.backgroundImageView.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(TOP_HEIGHT)
make.bottom.left.right.equalToSuperview()
}
if self.isFreeFormer {
self.freeEditView = UITextView()
self.freeEditView.backgroundColor = UIColor.clear
self.freeEditView.font = UIFont.systemFont(ofSize: 17)
self.addSubview(self.freeEditView)
self.freeEditView.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(TOP_HEIGHT)
make.bottom.left.right.equalToSuperview()
}
self.freeEditView.becomeFirstResponder()
self.freeEditView.rx.didChange.subscribe(onNext: { [unowned self] text in
self.hasEdit = true
})
.addDisposableTo(self.rx_disposeBag)
}
else {
tableView = UITableView()
tableView.backgroundColor = UIColor.clear
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = 70
tableView.register(EditPagerCell.self, forCellReuseIdentifier: editCellIdentifier)
tableView.hideEmptyCells()
self.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(TOP_HEIGHT)
make.bottom.left.right.equalToSuperview()
}
}
// tableView.bounces = false
}
func setupHeadView(){
let ivTop = UIImageView()
ivTop.contentMode = .scaleAspectFill
self.headView = ivTop
self.addSubview(ivTop)
ivTop.snp.makeConstraints{ (make) in
make.top.left.right.equalToSuperview()
make.height.equalTo(TOP_HEIGHT)
}
ivTop.backgroundColor = UIColor.clear
ivTop.isUserInteractionEnabled = true
let keyboard = UIImageView()
ivTop.addSubview(keyboard)
keyboard.image = UIImage(named:"keyboard")
keyboard.contentMode = UIViewContentMode.center
keyboard.snp.makeConstraints{ (make) in
make.top.left.bottom.equalToSuperview()
make.width.equalTo(60)
}
let dict = UIImageView()
ivTop.addSubview(dict)
dict.image = UIImage(named:"dict")
dict.contentMode = UIViewContentMode.center
dict.snp.makeConstraints{ (make) in
make.top.bottom.equalToSuperview()
make.right.equalToSuperview().offset(-10)
make.width.equalTo(45)
}
let info = UIImageView()
ivTop.addSubview(info)
info.image = UIImage(named:"info")
info.contentMode = UIViewContentMode.center
info.snp.makeConstraints{ (make) in
make.top.bottom.equalToSuperview()
make.width.equalTo(45)
make.right.equalTo(dict.snp.left)
}
title = UILabel()
if writing.title == nil {
writing.title = writing.former.name
}
title.textColor = UIColor.black
title.text = writing.title
ivTop.addSubview(title)
title.snp.makeConstraints{ (make) in
make.width.greaterThanOrEqualTo(100)
make.right.equalTo(info.snp.left)
make.top.height.equalToSuperview()
make.left.equalTo(keyboard.snp.right)
}
keyboard.isUserInteractionEnabled = true
keyboard.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.keyboardClick)))
info.isUserInteractionEnabled = true
info.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.infoClick)))
dict.isUserInteractionEnabled = true
dict.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dictClick)))
title.isUserInteractionEnabled = true
title.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.titleClick)))
FontsUtils.setFont(title)
}
func updateImage(image: UIImage) {
self.headView.image = image
self.backgroundImageView.image = image
}
func titleClick(){
let alert = UIAlertController(title: SSStr.Edit.INPUT_TITLE, message: nil, preferredStyle: UIAlertControllerStyle.alert)
alert.addTextField {
(textField: UITextField!) -> Void in
textField.text = self.writing.title
textField.placeholder = SSStr.Edit.INPUT_TITLE
}
let alertView1 = UIAlertAction(title: SSStr.Common.CANCEL, style: UIAlertActionStyle.cancel)
let alertView2 = UIAlertAction(title: SSStr.Common.CONFIRM, style: UIAlertActionStyle.default) { (UIAlertAction) -> Void in
self.writing.title = (alert.textFields?.first?.text)!
self.refreshTitle()
self.hasEdit = true
}
alert.addAction(alertView1)
alert.addAction(alertView2)
firstViewController()?.navigationController?.present(alert, animated: true, completion: nil)
}
func refreshTitle(){
title.text = writing.title
}
func keyboardClick(){
self.endEditing(true)
}
func infoClick(){
firstViewController()?.navigationController?.pushViewController(FormerIntroVC(former:writing.former), animated: true)
}
func dictClick(){
firstViewController()?.navigationController?.pushViewController(SearchYunVC(), animated: true)
}
//生成输入的内容
func mergeContent() -> String {
if self.isFreeFormer {
return self.freeEditView.text
}
var content = ""
for item in self.contentArray {
if let item = item {
if !content.isEmpty {
content += Writting.textSeparator
}
content += item
}
}
return content
}
}
extension EditPagerView: UITableViewDataSource,UITableViewDelegate {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.clist.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: editCellIdentifier, for: indexPath) as! EditPagerCell
let textArray = self.contentArray!
let content: String? = textArray.count > indexPath.row ? textArray[indexPath.row] : nil
cell.refresh(code: clist[indexPath.row], content: content)
cell.editHandler = { [unowned self] content in
self.contentArray[indexPath.row] = content
self.hasEdit = true
}
return cell
}
}
|
apache-2.0
|
dd238b4679a0a5fc243ed252232433e9
| 32.044218 | 131 | 0.60422 | 4.811788 | false | false | false | false |
chieryw/ReactiveCocoa
|
ReactiveCocoaTests/Swift/PropertySpec.swift
|
21
|
10655
|
//
// PropertySpec.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2015-01-23.
// Copyright (c) 2015 GitHub. All rights reserved.
//
import Result
import Nimble
import Quick
import ReactiveCocoa
private let initialPropertyValue = "InitialValue"
private let subsequentPropertyValue = "SubsequentValue"
class PropertySpec: QuickSpec {
override func spec() {
describe("ConstantProperty") {
it("should have the value given at initialization") {
let constantProperty = ConstantProperty(initialPropertyValue)
expect(constantProperty.value).to(equal(initialPropertyValue))
}
it("should yield a producer that sends the current value then completes") {
let constantProperty = ConstantProperty(initialPropertyValue)
var sentValue: String?
var signalCompleted = false
constantProperty.producer.start(next: { value in
sentValue = value
}, completed: {
signalCompleted = true
})
expect(sentValue).to(equal(initialPropertyValue))
expect(signalCompleted).to(beTruthy())
}
}
describe("MutableProperty") {
it("should have the value given at initialization") {
let mutableProperty = MutableProperty(initialPropertyValue)
expect(mutableProperty.value).to(equal(initialPropertyValue))
}
it("should yield a producer that sends the current value then all changes") {
let mutableProperty = MutableProperty(initialPropertyValue)
var sentValue: String?
mutableProperty.producer.start(next: { value in
sentValue = value
})
expect(sentValue).to(equal(initialPropertyValue))
mutableProperty.value = subsequentPropertyValue
expect(sentValue).to(equal(subsequentPropertyValue))
}
it("should complete its producer when deallocated") {
var mutableProperty: MutableProperty? = MutableProperty(initialPropertyValue)
var signalCompleted = false
mutableProperty?.producer.start(completed: {
signalCompleted = true
})
mutableProperty = nil
expect(signalCompleted).to(beTruthy())
}
it("should not deadlock on recursive value access") {
let (producer, sink) = SignalProducer<Int, NoError>.buffer()
let property = MutableProperty(0)
var value: Int?
property <~ producer
property.producer.start(next: { _ in
value = property.value
})
sendNext(sink, 10)
expect(value).to(equal(10))
}
it("should not deadlock on recursive observation") {
let property = MutableProperty(0)
var value: Int?
property.producer.start(next: { _ in
property.producer.start(next: { x in value = x })
})
expect(value).to(equal(0))
property.value = 1
expect(value).to(equal(1))
}
}
describe("PropertyOf") {
it("should pass through behaviors of the input property") {
let constantProperty = ConstantProperty(initialPropertyValue)
let propertyOf = PropertyOf(constantProperty)
var sentValue: String?
var producerCompleted = false
propertyOf.producer.start(next: { value in
sentValue = value
}, completed: {
producerCompleted = true
})
expect(sentValue).to(equal(initialPropertyValue))
expect(producerCompleted).to(beTruthy())
}
}
describe("DynamicProperty") {
var object: ObservableObject!
var property: DynamicProperty!
let propertyValue: () -> Int? = {
if let value: AnyObject = property?.value {
return value as? Int
} else {
return nil
}
}
beforeEach {
object = ObservableObject()
expect(object.rac_value).to(equal(0))
property = DynamicProperty(object: object, keyPath: "rac_value")
}
afterEach {
object = nil
}
it("should read the underlying object") {
expect(propertyValue()).to(equal(0))
object.rac_value = 1
expect(propertyValue()).to(equal(1))
}
it("should write the underlying object") {
property.value = 1
expect(object.rac_value).to(equal(1))
expect(propertyValue()).to(equal(1))
}
it("should observe changes to the property and underlying object") {
var values: [Int] = []
property.producer.start(next: { value in
expect(value).notTo(beNil())
values.append((value as? Int) ?? -1)
})
expect(values).to(equal([ 0 ]))
property.value = 1
expect(values).to(equal([ 0, 1 ]))
object.rac_value = 2
expect(values).to(equal([ 0, 1, 2 ]))
}
it("should complete when the underlying object deallocates") {
var completed = false
property = {
// Use a closure so this object has a shorter lifetime.
let object = ObservableObject()
let property = DynamicProperty(object: object, keyPath: "rac_value")
property.producer.start(completed: {
completed = true
})
expect(completed).to(beFalsy())
expect(property.value).notTo(beNil())
return property
}()
expect(completed).toEventually(beTruthy())
expect(property.value).to(beNil())
}
it("should retain property while DynamicProperty's object is retained"){
weak var dynamicProperty: DynamicProperty? = property
property = nil
expect(dynamicProperty).toNot(beNil())
object = nil
expect(dynamicProperty).to(beNil())
}
}
describe("binding") {
describe("from a Signal") {
it("should update the property with values sent from the signal") {
let (signal, observer) = Signal<String, NoError>.pipe()
let mutableProperty = MutableProperty(initialPropertyValue)
mutableProperty <~ signal
// Verify that the binding hasn't changed the property value:
expect(mutableProperty.value).to(equal(initialPropertyValue))
sendNext(observer, subsequentPropertyValue)
expect(mutableProperty.value).to(equal(subsequentPropertyValue))
}
it("should tear down the binding when disposed") {
let (signal, observer) = Signal<String, NoError>.pipe()
let mutableProperty = MutableProperty(initialPropertyValue)
let bindingDisposable = mutableProperty <~ signal
bindingDisposable.dispose()
sendNext(observer, subsequentPropertyValue)
expect(mutableProperty.value).to(equal(initialPropertyValue))
}
it("should tear down the binding when bound signal is completed") {
let (signal, observer) = Signal<String, NoError>.pipe()
let mutableProperty = MutableProperty(initialPropertyValue)
let bindingDisposable = mutableProperty <~ signal
expect(bindingDisposable.disposed).to(beFalsy())
sendCompleted(observer)
expect(bindingDisposable.disposed).to(beTruthy())
}
it("should tear down the binding when the property deallocates") {
let (signal, observer) = Signal<String, NoError>.pipe()
var mutableProperty: MutableProperty<String>? = MutableProperty(initialPropertyValue)
let bindingDisposable = mutableProperty! <~ signal
mutableProperty = nil
expect(bindingDisposable.disposed).to(beTruthy())
}
}
describe("from a SignalProducer") {
it("should start a signal and update the property with its values") {
let signalValues = [initialPropertyValue, subsequentPropertyValue]
let signalProducer = SignalProducer<String, NoError>(values: signalValues)
let mutableProperty = MutableProperty(initialPropertyValue)
mutableProperty <~ signalProducer
expect(mutableProperty.value).to(equal(signalValues.last!))
}
it("should tear down the binding when disposed") {
let signalValues = [initialPropertyValue, subsequentPropertyValue]
let signalProducer = SignalProducer<String, NoError>(values: signalValues)
let mutableProperty = MutableProperty(initialPropertyValue)
let disposable = mutableProperty <~ signalProducer
disposable.dispose()
// TODO: Assert binding was torn down?
}
it("should tear down the binding when bound signal is completed") {
let signalValues = [initialPropertyValue, subsequentPropertyValue]
let (signalProducer, observer) = SignalProducer<String, NoError>.buffer(1)
let mutableProperty = MutableProperty(initialPropertyValue)
mutableProperty <~ signalProducer
sendCompleted(observer)
// TODO: Assert binding was torn down?
}
it("should tear down the binding when the property deallocates") {
let signalValues = [initialPropertyValue, subsequentPropertyValue]
let signalProducer = SignalProducer<String, NoError>(values: signalValues)
var mutableProperty: MutableProperty<String>? = MutableProperty(initialPropertyValue)
let disposable = mutableProperty! <~ signalProducer
mutableProperty = nil
expect(disposable.disposed).to(beTruthy())
}
}
describe("from another property") {
it("should take the source property's current value") {
let sourceProperty = ConstantProperty(initialPropertyValue)
let destinationProperty = MutableProperty("")
destinationProperty <~ sourceProperty.producer
expect(destinationProperty.value).to(equal(initialPropertyValue))
}
it("should update with changes to the source property's value") {
let sourceProperty = MutableProperty(initialPropertyValue)
let destinationProperty = MutableProperty("")
destinationProperty <~ sourceProperty.producer
sourceProperty.value = subsequentPropertyValue
expect(destinationProperty.value).to(equal(subsequentPropertyValue))
}
it("should tear down the binding when disposed") {
let sourceProperty = MutableProperty(initialPropertyValue)
let destinationProperty = MutableProperty("")
let bindingDisposable = destinationProperty <~ sourceProperty.producer
bindingDisposable.dispose()
sourceProperty.value = subsequentPropertyValue
expect(destinationProperty.value).to(equal(initialPropertyValue))
}
it("should tear down the binding when the source property deallocates") {
var sourceProperty: MutableProperty<String>? = MutableProperty(initialPropertyValue)
let destinationProperty = MutableProperty("")
destinationProperty <~ sourceProperty!.producer
sourceProperty = nil
// TODO: Assert binding was torn down?
}
it("should tear down the binding when the destination property deallocates") {
let sourceProperty = MutableProperty(initialPropertyValue)
var destinationProperty: MutableProperty<String>? = MutableProperty("")
let bindingDisposable = destinationProperty! <~ sourceProperty.producer
destinationProperty = nil
expect(bindingDisposable.disposed).to(beTruthy())
}
}
}
}
}
private class ObservableObject: NSObject {
dynamic var rac_value: Int = 0
}
|
mit
|
ed32d37879c74bf49abb7a54314759df
| 27.953804 | 90 | 0.703238 | 4.345432 | false | false | false | false |
dusanIntellex/backend-operation-layer
|
Example/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift
|
1
|
2214
|
//
// SingleAssignmentDisposable.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/**
Represents a disposable resource which only allows a single assignment of its underlying disposable resource.
If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an exception.
*/
public final class SingleAssignmentDisposable : DisposeBase, Cancelable {
fileprivate enum DisposeState: Int32 {
case disposed = 1
case disposableSet = 2
}
// state
private var _state = AtomicInt(0)
private var _disposable = nil as Disposable?
/// - returns: A value that indicates whether the object is disposed.
public var isDisposed: Bool {
return _state.isFlagSet(DisposeState.disposed.rawValue)
}
/// Initializes a new instance of the `SingleAssignmentDisposable`.
public override init() {
super.init()
}
/// Gets or sets the underlying disposable. After disposal, the result of getting this property is undefined.
///
/// **Throws exception if the `SingleAssignmentDisposable` has already been assigned to.**
public func setDisposable(_ disposable: Disposable) {
_disposable = disposable
let previousState = _state.fetchOr(DisposeState.disposableSet.rawValue)
if (previousState & DisposeState.disposableSet.rawValue) != 0 {
rxFatalError("oldState.disposable != nil")
}
if (previousState & DisposeState.disposed.rawValue) != 0 {
disposable.dispose()
_disposable = nil
}
}
/// Disposes the underlying disposable.
public func dispose() {
let previousState = _state.fetchOr(DisposeState.disposed.rawValue)
if (previousState & DisposeState.disposed.rawValue) != 0 {
return
}
if (previousState & DisposeState.disposableSet.rawValue) != 0 {
guard let disposable = _disposable else {
rxFatalError("Disposable not set")
}
disposable.dispose()
_disposable = nil
}
}
}
|
mit
|
fc71e426bf4218a88be64291300dca6b
| 30.614286 | 141 | 0.655219 | 5.110855 | false | false | false | false |
iOSDevCafe/YouTube-Example-Codes
|
CollectionViews/CollectionViews/CollectionViewController.swift
|
1
|
3779
|
//
// CollectionViewController.swift
// CollectionViews
//
// Created by iOS Café on 27/08/2017.
// Copyright © 2017 iOS Café. All rights reserved.
//
import UIKit
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
private let reuseIdentifier = "Cell"
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
// MARK: UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = view.bounds.width
let height = width * (9.0 / 16.0)
return CGSize(width: width, height: height)
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return 10
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.row == 1{
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as? ImageCell else {return .init()}
cell.imageView.image = UIImage(named: "swift")
return cell
}
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as? Cell else {return .init()}
cell.label.text = "Hello, World!"
return cell
}
// MARK: UICollectionViewDelegate
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
return false
}
override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return false
}
override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
}
*/
}
|
mit
|
738ad451dab95b6a432b71e17ec2f9cc
| 33.962963 | 170 | 0.6875 | 5.809231 | false | false | false | false |
mightydeveloper/swift
|
validation-test/compiler_crashers_fixed/1022-swift-genericsignature-get.swift
|
13
|
398
|
// RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
A? = b: B<T> == i: C<A> {
self.f == [self.E == j> {
}
}
class A {
protocol c {
func f<c
typealias e where T: Hashable> e(a()
func f: AnyObject, g<T>Bool)) -> V>("
typealias B : B, U)
|
apache-2.0
|
38f8afadeb45f70f8a78eefa34d68914
| 23.875 | 87 | 0.653266 | 2.948148 | false | true | false | false |
samnm/material-components-ios
|
components/Palettes/tests/unit/PaletteTests.swift
|
5
|
3780
|
/*
Copyright 2016-present the Material Components for iOS 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 XCTest
import MaterialComponents.MaterialPalettes
class PaletteTests: XCTestCase {
// Creates a UIColor from a 24-bit RGB color encoded as an integer.
func colorFromRGB(_ rgbValue: UInt32) -> UIColor {
return UIColor(
red:CGFloat((rgbValue & 0xFF0000) >> 16) / 255,
green:CGFloat((rgbValue & 0x00FF00) >> 8) / 255,
blue:CGFloat((rgbValue & 0x0000FF) >> 0) / 255,
alpha:1)
}
func testBasics() {
let color = MDCPalette.red.tint50
XCTAssertEqual(color, colorFromRGB(0xFFEBEE))
}
func testCaching() {
let first = MDCPalette.red
let second = MDCPalette.red
XCTAssertTrue(first === second)
}
func testAccentlessPalette() {
let brownPalette = MDCPalette.brown
XCTAssertNil(brownPalette.accent100)
}
func testGeneratedPalette() {
let palette = MDCPalette(generatedFrom: UIColor(red: 1, green: 0, blue: 0, alpha: 1))
XCTAssertNotNil(palette.tint50)
XCTAssertNotNil(palette.tint100)
XCTAssertNotNil(palette.tint200)
XCTAssertNotNil(palette.tint300)
XCTAssertNotNil(palette.tint400)
XCTAssertNotNil(palette.tint500)
XCTAssertNotNil(palette.tint600)
XCTAssertNotNil(palette.tint700)
XCTAssertNotNil(palette.tint800)
XCTAssertNotNil(palette.tint900)
XCTAssertNotNil(palette.accent100)
XCTAssertNotNil(palette.accent200)
XCTAssertNotNil(palette.accent400)
XCTAssertNotNil(palette.accent700)
}
func testCustomPalette() {
let tints: [MDCPaletteTint: UIColor] = [
.tint50Name: UIColor(white: 0, alpha: 1),
.tint100Name: UIColor(white: 0.1, alpha: 1),
.tint200Name: UIColor(white: 0.2, alpha: 1),
.tint300Name: UIColor(white: 0.3, alpha: 1),
.tint400Name: UIColor(white: 0.4, alpha: 1),
.tint500Name: UIColor(white: 0.5, alpha: 1),
.tint600Name: UIColor(white: 0.6, alpha: 1),
.tint700Name: UIColor(white: 0.7, alpha: 1),
.tint800Name: UIColor(white: 0.8, alpha: 1),
.tint900Name: UIColor(white: 0.9, alpha: 1)
]
let accents: [MDCPaletteAccent: UIColor] = [
.accent100Name: UIColor(white: 1, alpha: 0),
.accent200Name: UIColor(white: 1, alpha: 0.25),
.accent400Name: UIColor(white: 1, alpha: 0.75),
.accent700Name: UIColor(white: 1, alpha: 1)
]
let palette = MDCPalette(tints: tints, accents: accents)
XCTAssertEqual(palette.tint50, tints[.tint50Name])
XCTAssertEqual(palette.tint100, tints[.tint100Name])
XCTAssertEqual(palette.tint200, tints[.tint200Name])
XCTAssertEqual(palette.tint300, tints[.tint300Name])
XCTAssertEqual(palette.tint400, tints[.tint400Name])
XCTAssertEqual(palette.tint500, tints[.tint500Name])
XCTAssertEqual(palette.tint600, tints[.tint600Name])
XCTAssertEqual(palette.tint700, tints[.tint700Name])
XCTAssertEqual(palette.tint800, tints[.tint800Name])
XCTAssertEqual(palette.tint900, tints[.tint900Name])
XCTAssertEqual(palette.accent100, accents[.accent100Name])
XCTAssertEqual(palette.accent200, accents[.accent200Name])
XCTAssertEqual(palette.accent400, accents[.accent400Name])
XCTAssertEqual(palette.accent700, accents[.accent700Name])
}
}
|
apache-2.0
|
749b1b481d1370530018e3db4db6feb6
| 37.181818 | 89 | 0.719577 | 3.776224 | false | true | false | false |
jpush/jchat-swift
|
ContacterModule/ViewController/JCMoreResultViewController.swift
|
1
|
8497
|
//
// JCMoreResultViewController.swift
// JChat
//
// Created by deng on 2017/5/8.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
import JMessage
class JCMoreResultViewController: UIViewController {
var message: JMSGMessage?
var fromUser: JMSGUser!
weak var delegate: JCSearchResultViewController?
var searchResultView: JCSearchResultViewController!
var searchController: UISearchController!
var users: [JMSGUser] = []
var groups: [JMSGGroup] = []
fileprivate var selectGroup: JMSGGroup!
fileprivate var selectUser: JMSGUser!
//MARK: - life cycle
override func viewDidLoad() {
super.viewDidLoad()
_init()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
navigationController?.navigationBar.isHidden = true
if searchController != nil {
searchController.searchBar.isHidden = false
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidAppear(animated)
navigationController?.navigationBar.isHidden = false
}
deinit {
searchResultView.removeObserver(self, forKeyPath: "filteredUsersArray")
searchResultView.removeObserver(self, forKeyPath: "filteredGroupsArray")
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "filteredUsersArray" {
users = searchResultView.filteredUsersArray
}
if keyPath == "filteredGroupsArray" {
groups = searchResultView.filteredGroupsArray
}
tableView.reloadData()
}
fileprivate lazy var tableView: UITableView = {
var tableView = UITableView(frame: CGRect(x: 0, y: 64, width: self.view.width, height: self.view.height - 64))
tableView.delegate = self
tableView.dataSource = self
tableView.keyboardDismissMode = .onDrag
tableView.register(JCContacterCell.self, forCellReuseIdentifier: "JCContacterCell")
return tableView
}()
//MARK: - private func
private func _init() {
navigationController?.automaticallyAdjustsScrollViewInsets = false
automaticallyAdjustsScrollViewInsets = false
navigationController?.navigationBar.isHidden = true
view.backgroundColor = UIColor(netHex: 0xe8edf3)
view.addSubview(tableView)
searchResultView.addObserver(self, forKeyPath: "filteredUsersArray", options: .new, context: nil)
searchResultView.addObserver(self, forKeyPath: "filteredGroupsArray", options: .new, context: nil)
}
fileprivate func sendBusinessCard() {
JCAlertView.bulid().setTitle("发送给:\(selectGroup.displayName())")
.setMessage(fromUser!.displayName() + "的名片")
.setDelegate(self)
.addCancelButton("取消")
.addButton("确定")
.setTag(10003)
.show()
}
fileprivate func forwardMessage(_ message: JMSGMessage) {
let alertView = JCAlertView.bulid().setJMessage(message)
.setDelegate(self)
.setTag(10001)
if selectUser == nil {
alertView.setTitle("发送给:\(selectGroup.displayName())")
} else {
alertView.setTitle("发送给:\(selectUser.displayName())")
}
alertView.show()
}
}
//Mark: -
extension JCMoreResultViewController: UITableViewDelegate, UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if users.count > 0 {
return users.count
}
return groups.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 55
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: "JCContacterCell", for: indexPath)
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let cell = cell as? JCContacterCell else {
return
}
if users.count > 0 {
cell.bindDate(users[indexPath.row])
} else {
cell.bindDateWithGroup(group: groups[indexPath.row])
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if users.count > 0 {
let user = users[indexPath.row]
selectUser = user
if let message = message {
forwardMessage(message)
return
}
if fromUser != nil {
sendBusinessCard()
return
}
let vc: UIViewController
if user.isEqual(to: JMSGUser.myInfo()) {
vc = JCMyInfoViewController()
} else {
let v = JCUserInfoViewController()
v.user = user
vc = v
}
if searchController != nil {
searchController.searchBar.resignFirstResponder()
searchController.searchBar.isHidden = true
}
navigationController?.navigationBar.isHidden = false
navigationController?.pushViewController(vc, animated: true)
} else {
let group = groups[indexPath.row]
selectGroup = group
if let message = message {
forwardMessage(message)
return
}
if fromUser != nil {
sendBusinessCard()
return
}
JMSGConversation.createGroupConversation(withGroupId: group.gid) { (result, error) in
let conv = result as! JMSGConversation
let vc = JCChatViewController(conversation: conv)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateConversation), object: nil, userInfo: nil)
if self.searchController != nil {
self.searchController.searchBar.resignFirstResponder()
self.searchController.searchBar.isHidden = true
}
self.navigationController?.navigationBar.isHidden = false
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
}
extension JCMoreResultViewController: UIAlertViewDelegate {
func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
if buttonIndex != 1 {
return
}
switch alertView.tag {
case 10001:
if selectUser != nil {
JMSGMessage.forwardMessage(message!, target: selectUser, optionalContent: JMSGOptionalContent.ex.default)
} else {
JMSGMessage.forwardMessage(message!, target: selectGroup, optionalContent: JMSGOptionalContent.ex.default)
}
case 10003:
if selectUser != nil {
JMSGConversation.createSingleConversation(withUsername: selectUser.username) { (result, error) in
if let conversation = result as? JMSGConversation {
let message = JMSGMessage.ex.createBusinessCardMessage(conversation, self.fromUser.username, self.fromUser.appKey ?? "")
JMSGMessage.send(message, optionalContent: JMSGOptionalContent.ex.default)
}
}
} else {
let msg = JMSGMessage.ex.createBusinessCardMessage(gid: selectGroup.gid, userName: fromUser!.username, appKey: fromUser!.appKey ?? "")
JMSGMessage.send(msg, optionalContent: JMSGOptionalContent.ex.default)
}
default:
break
}
MBProgressHUD_JChat.show(text: "已发送", view: view, 2)
let time: TimeInterval = 2
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: kReloadAllMessage), object: nil)
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) { [weak self] in
self?.delegate?.close()
}
}
}
|
mit
|
38f176fe6e8db1fe028e04a723297b2f
| 36.061404 | 151 | 0.613964 | 5.165037 | false | false | false | false |
335g/FingerTree
|
FingerTree/Node.swift
|
1
|
2418
|
// Copyright © 2015 Yoshiki Kudo. All rights reserved.
import Prelude
// MARK: - Node
public enum Node<V, A: Measurable where V == A.MeasuredValue>: NodeType {
public typealias Value = V
public typealias Annotation = A
case Node2(V, A, A)
case Node3(V, A, A, A)
// MARK: static
static func node2(a: A, _ b: A) -> Node {
return .Node2(a.measure().mappend(b.measure()), a, b)
}
static func node3(a: A, _ b: A, _ c: A) -> Node {
return .Node3(a.measure().mappend(b.measure().mappend(c.measure())), a, b, c)
}
}
// MARK: - Node : Functor
extension Node {
func map<V1, A1: Measurable where V1 == A1.MeasuredValue>(f: A -> A1) -> Node<V1, A1> {
switch self {
case let .Node2(_, a, b):
return Node<V1, A1>.node2(f(a), f(b))
case let .Node3(_, a, b, c):
return Node<V1, A1>.node3(f(a), f(b), f(c))
}
}
func unsafeMap<A1: Measurable where V == A1.MeasuredValue>(f: A -> A1) -> Node<V, A1> {
switch self {
case let .Node2(v, a, b):
return Node<V, A1>.Node2(v, f(a), f(b))
case let .Node3(v, a, b, c):
return Node<V, A1>.Node3(v, f(a), f(b), f(c))
}
}
}
// MARK: - Node _ Transformation
extension Node {
var digit: Digit<A> {
switch self {
case let .Node2(_, a, b):
return .Two(a, b)
case let .Node3(_, a, b, c):
return .Three(a, b, c)
}
}
func reverse<V1, A1: Measurable where V1 == A1.MeasuredValue>(f: A -> A1) -> Node<V1, A1> {
switch self {
case let .Node2(_, a, b):
return Node<V1, A1>.node2(f(b), f(a))
case let .Node3(_, a, b, c):
return Node<V1, A1>.node3(f(c), f(b), f(a))
}
}
}
// MARK: - Node : Foldable
public extension Node {
public func foldr<B>(initial: B, _ f: A -> B -> B) -> B {
switch self {
case let .Node2(_, a, b):
return f(a)(f(b)(initial))
case let .Node3(_, a, b, c):
return f(a)(f(b)(f(c)(initial)))
}
}
func foldl<B>(initial: B, _ f: B -> A -> B) -> B {
switch self {
case let .Node2(_, a, b):
return f(f(initial)(a))(b)
case let .Node3(_, a, b, c):
return f(f(f(initial)(a))(b))(c)
}
}
func foldMap<M: Monoid>(f: A -> M) -> M {
return foldl(M.mempty){ m in
{ m.mappend(f($0)) }
}
}
}
// MARK: - Node : Measurable
public extension Node {
public typealias MeasuredValue = V
public func measure() -> MeasuredValue {
switch self {
case let .Node2(v, _, _):
return v
case let .Node3(v, _, _, _):
return v
}
}
}
|
mit
|
31fdc61eb2dda85e56b802dab73e5ccd
| 19.483051 | 92 | 0.556475 | 2.421844 | false | false | false | false |
nahive/UIColor-WikiColors
|
WikiColors.swift
|
1
|
70340
|
//
// Created by nahive on 12/20/2016.
// Copyright (c) 2016 nahive.io All rights reserved.
//
import UIKit
extension UIColor {
convenience init(hex: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if hex.hasPrefix("#") {
let index = hex.index(hex.startIndex, offsetBy: 1)
let hex = hex.substring(from: index)
let scanner = Scanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexInt64(&hexValue) {
switch (hex.characters.count) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
print("Invalid RGB string, number of characters after # should be either 3, 4, 6 or 8")
}
} else {
print("Scan hex error")
}
} else {
print("Invalid RGB string, missing # as prefix")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
}
public extension UIColor {
static let absoluteZero = UIColor(hex: "#0048BA")
static let acidGreen = UIColor(hex: "#B0BF1A")
static let aero = UIColor(hex: "#7CB9E8")
static let aeroBlue = UIColor(hex: "#C9FFE5")
static let africanViolet = UIColor(hex: "#B284BE")
static let airForceBlueRAF = UIColor(hex: "#5D8AA8")
static let airForceBlueUSAF = UIColor(hex: "#00308F")
static let airSuperiorityBlue = UIColor(hex: "#72A0C1")
static let alabamaCrimson = UIColor(hex: "#AF002A")
static let alabaster = UIColor(hex: "#F2F0E6")
static let aliceBlue = UIColor(hex: "#F0F8FF")
static let alienArmpit = UIColor(hex: "#84DE02")
static let alizarinCrimson = UIColor(hex: "#E32636")
static let alloyOrange = UIColor(hex: "#C46210")
static let almond = UIColor(hex: "#EFDECD")
static let amaranth = UIColor(hex: "#E52B50")
static let amaranthDeepPurple = UIColor(hex: "#9F2B68")
static let amaranthPink = UIColor(hex: "#F19CBB")
static let amaranthPurple = UIColor(hex: "#AB274F")
static let amaranthRed = UIColor(hex: "#D3212D")
static let amazon = UIColor(hex: "#3B7A57")
static let amazonite = UIColor(hex: "#00C4B0")
static let amber = UIColor(hex: "#FFBF00")
static let amberSAEECE = UIColor(hex: "#FF7E00")
static let americanRose = UIColor(hex: "#FF033E")
static let amethyst = UIColor(hex: "#9966CC")
static let androidGreen = UIColor(hex: "#A4C639")
static let antiFlashWhite = UIColor(hex: "#F2F3F4")
static let antiqueBrass = UIColor(hex: "#CD9575")
static let antiqueBronze = UIColor(hex: "#665D1E")
static let antiqueFuchsia = UIColor(hex: "#915C83")
static let antiqueRuby = UIColor(hex: "#841B2D")
static let antiqueWhite = UIColor(hex: "#FAEBD7")
static let aoEnglish = UIColor(hex: "#008000")
static let appleGreen = UIColor(hex: "#8DB600")
static let apricot = UIColor(hex: "#FBCEB1")
static let aqua = UIColor(hex: "#00FFFF")
static let aquamarine = UIColor(hex: "#7FFFD4")
static let arcticLime = UIColor(hex: "#D0FF14")
static let armyGreen = UIColor(hex: "#4B5320")
static let arsenic = UIColor(hex: "#3B444B")
static let artichoke = UIColor(hex: "#8F9779")
static let arylideYellow = UIColor(hex: "#E9D66B")
static let ashGrey = UIColor(hex: "#B2BEB5")
static let asparagus = UIColor(hex: "#87A96B")
static let atomicTangerine = UIColor(hex: "#FF9966")
static let auburn = UIColor(hex: "#A52A2A")
static let aureolin = UIColor(hex: "#FDEE00")
static let auroMetalSaurus = UIColor(hex: "#6E7F80")
static let avocado = UIColor(hex: "#568203")
static let awesome = UIColor(hex: "#FF2052")
static let aztecGold = UIColor(hex: "#C39953")
static let azure = UIColor(hex: "#007FFF")
static let azureWebColor = UIColor(hex: "#F0FFFF")
static let azureMist = UIColor(hex: "#F0FFFF")
static let azureishWhite = UIColor(hex: "#DBE9F4")
static let babyBlue = UIColor(hex: "#89CFF0")
static let babyBlueEyes = UIColor(hex: "#A1CAF1")
static let babyPink = UIColor(hex: "#F4C2C2")
static let babyPowder = UIColor(hex: "#FEFEFA")
static let bakerMillerPink = UIColor(hex: "#FF91AF")
static let ballBlue = UIColor(hex: "#21ABCD")
static let bananaMania = UIColor(hex: "#FAE7B5")
static let bananaYellow = UIColor(hex: "#FFE135")
static let bangladeshGreen = UIColor(hex: "#006A4E")
static let barbiePink = UIColor(hex: "#E0218A")
static let barnRed = UIColor(hex: "#7C0A02")
static let batteryChargedBlue = UIColor(hex: "#1DACD6")
static let battleshipGrey = UIColor(hex: "#848482")
static let bazaar = UIColor(hex: "#98777B")
static let beauBlue = UIColor(hex: "#BCD4E6")
static let beaver = UIColor(hex: "#9F8170")
static let begonia = UIColor(hex: "#FA6E79")
static let beige = UIColor(hex: "#F5F5DC")
static let bdazzledBlue = UIColor(hex: "#2E5894")
static let bigDipOruby = UIColor(hex: "#9C2542")
static let bigFootFeet = UIColor(hex: "#E88E5A")
static let bisque = UIColor(hex: "#FFE4C4")
static let bistre = UIColor(hex: "#3D2B1F")
static let bistreBrown = UIColor(hex: "#967117")
static let bitterLemon = UIColor(hex: "#CAE00D")
static let bitterLime = UIColor(hex: "#BFFF00")
static let bittersweet = UIColor(hex: "#FE6F5E")
static let bittersweetShimmer = UIColor(hex: "#BF4F51")
static let black = UIColor(hex: "#000000")
static let blackBean = UIColor(hex: "#3D0C02")
static let blackCoral = UIColor(hex: "#54626F")
static let blackLeatherJacket = UIColor(hex: "#253529")
static let blackOlive = UIColor(hex: "#3B3C36")
static let blackShadows = UIColor(hex: "#BFAFB2")
static let blanchedAlmond = UIColor(hex: "#FFEBCD")
static let blastOffBronze = UIColor(hex: "#A57164")
static let bleuDeFrance = UIColor(hex: "#318CE7")
static let blizzardBlue = UIColor(hex: "#ACE5EE")
static let blond = UIColor(hex: "#FAF0BE")
static let blue = UIColor(hex: "#0000FF")
static let blueCrayola = UIColor(hex: "#1F75FE")
static let blueMunsell = UIColor(hex: "#0093AF")
static let blueNCS = UIColor(hex: "#0087BD")
static let bluePantone = UIColor(hex: "#0018A8")
static let bluePigment = UIColor(hex: "#333399")
static let blueRYB = UIColor(hex: "#0247FE")
static let blueBell = UIColor(hex: "#A2A2D0")
static let blueBolt = UIColor(hex: "#00B9FB")
static let blueGray = UIColor(hex: "#6699CC")
static let blueGreen = UIColor(hex: "#0D98BA")
static let blueJeans = UIColor(hex: "#5DADEC")
static let blueLagoon = UIColor(hex: "#ACE5EE")
static let blueMagentaViolet = UIColor(hex: "#553592")
static let blueSapphire = UIColor(hex: "#126180")
static let blueViolet = UIColor(hex: "#8A2BE2")
static let blueYonder = UIColor(hex: "#5072A7")
static let blueberry = UIColor(hex: "#4F86F7")
static let bluebonnet = UIColor(hex: "#1C1CF0")
static let blush = UIColor(hex: "#DE5D83")
static let bole = UIColor(hex: "#79443B")
static let bondiBlue = UIColor(hex: "#0095B6")
static let bone = UIColor(hex: "#E3DAC9")
static let boogerBuster = UIColor(hex: "#DDE26A")
static let bostonUniversityRed = UIColor(hex: "#CC0000")
static let bottleGreen = UIColor(hex: "#006A4E")
static let boysenberry = UIColor(hex: "#873260")
static let brandeisBlue = UIColor(hex: "#0070FF")
static let brass = UIColor(hex: "#B5A642")
static let brickRed = UIColor(hex: "#CB4154")
static let brightCerulean = UIColor(hex: "#1DACD6")
static let brightGreen = UIColor(hex: "#66FF00")
static let brightLavender = UIColor(hex: "#BF94E4")
static let brightLilac = UIColor(hex: "#D891EF")
static let brightMaroon = UIColor(hex: "#C32148")
static let brightNavyBlue = UIColor(hex: "#1974D2")
static let brightPink = UIColor(hex: "#FF007F")
static let brightTurquoise = UIColor(hex: "#08E8DE")
static let brightUbe = UIColor(hex: "#D19FE8")
static let brightYellowCrayola = UIColor(hex: "#FFAA1D")
static let brilliantAzure = UIColor(hex: "#3399FF")
static let brilliantLavender = UIColor(hex: "#F4BBFF")
static let brilliantRose = UIColor(hex: "#FF55A3")
static let brinkPink = UIColor(hex: "#FB607F")
static let britishRacingGreen = UIColor(hex: "#004225")
static let bronze = UIColor(hex: "#CD7F32")
static let bronzeYellow = UIColor(hex: "#737000")
static let brownTraditional = UIColor(hex: "#964B00")
static let brownWeb = UIColor(hex: "#A52A2A")
static let brownNose = UIColor(hex: "#6B4423")
static let brownSugar = UIColor(hex: "#AF6E4D")
static let brownYellow = UIColor(hex: "#cc9966")
static let brunswickGreen = UIColor(hex: "#1B4D3E")
static let bubbleGum = UIColor(hex: "#FFC1CC")
static let bubbles = UIColor(hex: "#E7FEFF")
static let budGreen = UIColor(hex: "#7BB661")
static let buff = UIColor(hex: "#F0DC82")
static let bulgarianRose = UIColor(hex: "#480607")
static let burgundy = UIColor(hex: "#800020")
static let burlywood = UIColor(hex: "#DEB887")
static let burnishedBrown = UIColor(hex: "#A17A74")
static let burntOrange = UIColor(hex: "#CC5500")
static let burntSienna = UIColor(hex: "#E97451")
static let burntUmber = UIColor(hex: "#8A3324")
static let buttonBlue = UIColor(hex: "#24A0ED")
static let byzantine = UIColor(hex: "#BD33A4")
static let byzantium = UIColor(hex: "#702963")
static let cadet = UIColor(hex: "#536872")
static let cadetBlue = UIColor(hex: "#5F9EA0")
static let cadetGrey = UIColor(hex: "#91A3B0")
static let cadmiumGreen = UIColor(hex: "#006B3C")
static let cadmiumOrange = UIColor(hex: "#ED872D")
static let cadmiumRed = UIColor(hex: "#E30022")
static let cadmiumYellow = UIColor(hex: "#FFF600")
static let caféAuLait = UIColor(hex: "#A67B5B")
static let caféNoir = UIColor(hex: "#4B3621")
static let calPolyPomonaGreen = UIColor(hex: "#1E4D2B")
static let cambridgeBlue = UIColor(hex: "#A3C1AD")
static let camel = UIColor(hex: "#C19A6B")
static let cameoPink = UIColor(hex: "#EFBBCC")
static let camouflageGreen = UIColor(hex: "#78866B")
static let canary = UIColor(hex: "#FFFF99")
static let canaryYellow = UIColor(hex: "#FFEF00")
static let candyAppleRed = UIColor(hex: "#FF0800")
static let candyPink = UIColor(hex: "#E4717A")
static let capri = UIColor(hex: "#00BFFF")
static let caputMortuum = UIColor(hex: "#592720")
static let cardinal = UIColor(hex: "#C41E3A")
static let caribbeanGreen = UIColor(hex: "#00CC99")
static let carmine = UIColor(hex: "#960018")
static let carmineMP = UIColor(hex: "#D70040")
static let carminePink = UIColor(hex: "#EB4C42")
static let carmineRed = UIColor(hex: "#FF0038")
static let carnationPink = UIColor(hex: "#FFA6C9")
static let carnelian = UIColor(hex: "#B31B1B")
static let carolinaBlue = UIColor(hex: "#56A0D3")
static let carrotOrange = UIColor(hex: "#ED9121")
static let castletonGreen = UIColor(hex: "#00563F")
static let catalinaBlue = UIColor(hex: "#062A78")
static let catawba = UIColor(hex: "#703642")
static let cedarChest = UIColor(hex: "#C95A49")
static let ceil = UIColor(hex: "#92A1CF")
static let celadon = UIColor(hex: "#ACE1AF")
static let celadonBlue = UIColor(hex: "#007BA7")
static let celadonGreen = UIColor(hex: "#2F847C")
static let celeste = UIColor(hex: "#B2FFFF")
static let celestialBlue = UIColor(hex: "#4997D0")
static let cerise = UIColor(hex: "#DE3163")
static let cerisePink = UIColor(hex: "#EC3B83")
static let cerulean = UIColor(hex: "#007BA7")
static let ceruleanBlue = UIColor(hex: "#2A52BE")
static let ceruleanFrost = UIColor(hex: "#6D9BC3")
static let cGBlue = UIColor(hex: "#007AA5")
static let cGRed = UIColor(hex: "#E03C31")
static let chamoisee = UIColor(hex: "#A0785A")
static let champagne = UIColor(hex: "#F7E7CE")
static let champagnePink = UIColor(hex: "#F1DDCF")
static let charcoal = UIColor(hex: "#36454F")
static let charlestonGreen = UIColor(hex: "#232B2B")
static let charmPink = UIColor(hex: "#E68FAC")
static let chartreuseTraditional = UIColor(hex: "#DFFF00")
static let chartreuseWeb = UIColor(hex: "#7FFF00")
static let cherry = UIColor(hex: "#DE3163")
static let cherryBlossomPink = UIColor(hex: "#FFB7C5")
static let chestnut = UIColor(hex: "#954535")
static let chinaPink = UIColor(hex: "#DE6FA1")
static let chinaRose = UIColor(hex: "#A8516E")
static let chineseRed = UIColor(hex: "#AA381E")
static let chineseViolet = UIColor(hex: "#856088")
static let chlorophyllGreen = UIColor(hex: "#4AFF00")
static let chocolateTraditional = UIColor(hex: "#7B3F00")
static let chocolateWeb = UIColor(hex: "#D2691E")
static let chromeYellow = UIColor(hex: "#FFA700")
static let cinereous = UIColor(hex: "#98817B")
static let cinnabar = UIColor(hex: "#E34234")
static let cinnamon = UIColor(hex: "#D2691E")
static let cinnamonSatin = UIColor(hex: "#CD607E")
static let citrine = UIColor(hex: "#E4D00A")
static let citron = UIColor(hex: "#9FA91F")
static let claret = UIColor(hex: "#7F1734")
static let classicRose = UIColor(hex: "#FBCCE7")
static let cobaltBlue = UIColor(hex: "#0047AB")
static let cocoaBrown = UIColor(hex: "#D2691E")
static let coconut = UIColor(hex: "#965A3E")
static let coffee = UIColor(hex: "#6F4E37")
static let columbiaBlue = UIColor(hex: "#C4D8E2")
static let congoPink = UIColor(hex: "#F88379")
static let coolBlack = UIColor(hex: "#002E63")
static let coolGrey = UIColor(hex: "#8C92AC")
static let copper = UIColor(hex: "#B87333")
static let copperCrayola = UIColor(hex: "#DA8A67")
static let copperPenny = UIColor(hex: "#AD6F69")
static let copperRed = UIColor(hex: "#CB6D51")
static let copperRose = UIColor(hex: "#996666")
static let coquelicot = UIColor(hex: "#FF3800")
static let coral = UIColor(hex: "#FF7F50")
static let coralPink = UIColor(hex: "#F88379")
static let coralRed = UIColor(hex: "#FF4040")
static let coralReef = UIColor(hex: "#FD7C6E")
static let cordovan = UIColor(hex: "#893F45")
static let corn = UIColor(hex: "#FBEC5D")
static let cornellRed = UIColor(hex: "#B31B1B")
static let cornflowerBlue = UIColor(hex: "#6495ED")
static let cornsilk = UIColor(hex: "#FFF8DC")
static let cosmicCobalt = UIColor(hex: "#2E2D88")
static let cosmicLatte = UIColor(hex: "#FFF8E7")
static let coyoteBrown = UIColor(hex: "#81613C")
static let cottonCandy = UIColor(hex: "#FFBCD9")
static let cream = UIColor(hex: "#FFFDD0")
static let crimson = UIColor(hex: "#DC143C")
static let crimsonGlory = UIColor(hex: "#BE0032")
static let crimsonRed = UIColor(hex: "#990000")
static let cultured = UIColor(hex: "#F5F5F5")
static let cyan = UIColor(hex: "#00FFFF")
static let cyanAzure = UIColor(hex: "#4E82B4")
static let cyanBlueAzure = UIColor(hex: "#4682BF")
static let cyanCobaltBlue = UIColor(hex: "#28589C")
static let cyanCornflowerBlue = UIColor(hex: "#188BC2")
static let cyanProcess = UIColor(hex: "#00B7EB")
static let cyberGrape = UIColor(hex: "#58427C")
static let cyberYellow = UIColor(hex: "#FFD300")
static let cyclamen = UIColor(hex: "#F56FA1")
static let daffodil = UIColor(hex: "#FFFF31")
static let dandelion = UIColor(hex: "#F0E130")
static let darkBlue = UIColor(hex: "#00008B")
static let darkBlueGray = UIColor(hex: "#666699")
static let darkBrown = UIColor(hex: "#654321")
static let darkBrownTangelo = UIColor(hex: "#88654E")
static let darkByzantium = UIColor(hex: "#5D3954")
static let darkCandyAppleRed = UIColor(hex: "#A40000")
static let darkCerulean = UIColor(hex: "#08457E")
static let darkChestnut = UIColor(hex: "#986960")
static let darkCoral = UIColor(hex: "#CD5B45")
static let darkCyan = UIColor(hex: "#008B8B")
static let darkElectricBlue = UIColor(hex: "#536878")
static let darkGoldenrod = UIColor(hex: "#B8860B")
static let darkGrayX11 = UIColor(hex: "#A9A9A9")
static let darkGreen = UIColor(hex: "#013220")
static let darkGreenX11 = UIColor(hex: "#006400")
static let darkGunmetal = UIColor(hex: "#1F262A")
static let darkImperialBlue = UIColor(hex: "#00416A")
static let darkJungleGreen = UIColor(hex: "#1A2421")
static let darkKhaki = UIColor(hex: "#BDB76B")
static let darkLava = UIColor(hex: "#483C32")
static let darkLavender = UIColor(hex: "#734F96")
static let darkLiver = UIColor(hex: "#534B4F")
static let darkLiverHorses = UIColor(hex: "#543D37")
static let darkMagenta = UIColor(hex: "#8B008B")
static let darkMediumGray = UIColor(hex: "#A9A9A9")
static let darkMidnightBlue = UIColor(hex: "#003366")
static let darkMossGreen = UIColor(hex: "#4A5D23")
static let darkOliveGreen = UIColor(hex: "#556B2F")
static let darkOrange = UIColor(hex: "#FF8C00")
static let darkOrchid = UIColor(hex: "#9932CC")
static let darkPastelBlue = UIColor(hex: "#779ECB")
static let darkPastelGreen = UIColor(hex: "#03C03C")
static let darkPastelPurple = UIColor(hex: "#966FD6")
static let darkPastelRed = UIColor(hex: "#C23B22")
static let darkPink = UIColor(hex: "#E75480")
static let darkPowderBlue = UIColor(hex: "#003399")
static let darkPuce = UIColor(hex: "#4F3A3C")
static let darkPurple = UIColor(hex: "#301934")
static let darkRaspberry = UIColor(hex: "#872657")
static let darkRed = UIColor(hex: "#8B0000")
static let darkSalmon = UIColor(hex: "#E9967A")
static let darkScarlet = UIColor(hex: "#560319")
static let darkSeaGreen = UIColor(hex: "#8FBC8F")
static let darkSienna = UIColor(hex: "#3C1414")
static let darkSkyBlue = UIColor(hex: "#8CBED6")
static let darkSlateBlue = UIColor(hex: "#483D8B")
static let darkSlateGray = UIColor(hex: "#2F4F4F")
static let darkSpringGreen = UIColor(hex: "#177245")
static let darkTan = UIColor(hex: "#918151")
static let darkTangerine = UIColor(hex: "#FFA812")
static let darkTaupe = UIColor(hex: "#483C32")
static let darkTerraCotta = UIColor(hex: "#CC4E5C")
static let darkTurquoise = UIColor(hex: "#00CED1")
static let darkVanilla = UIColor(hex: "#D1BEA8")
static let darkViolet = UIColor(hex: "#9400D3")
static let darkYellow = UIColor(hex: "#9B870C")
static let dartmouthGreen = UIColor(hex: "#00703C")
static let davysGrey = UIColor(hex: "#555555")
static let debianRed = UIColor(hex: "#D70A53")
static let deepAquamarine = UIColor(hex: "#40826D")
static let deepCarmine = UIColor(hex: "#A9203E")
static let deepCarminePink = UIColor(hex: "#EF3038")
static let deepCarrotOrange = UIColor(hex: "#E9692C")
static let deepCerise = UIColor(hex: "#DA3287")
static let deepChampagne = UIColor(hex: "#FAD6A5")
static let deepChestnut = UIColor(hex: "#B94E48")
static let deepCoffee = UIColor(hex: "#704241")
static let deepFuchsia = UIColor(hex: "#C154C1")
static let deepGreen = UIColor(hex: "#056608")
static let deepGreenCyanTurquoise = UIColor(hex: "#0E7C61")
static let deepJungleGreen = UIColor(hex: "#004B49")
static let deepKoamaru = UIColor(hex: "#333366")
static let deepLemon = UIColor(hex: "#F5C71A")
static let deepLilac = UIColor(hex: "#9955BB")
static let deepMagenta = UIColor(hex: "#CC00CC")
static let deepMaroon = UIColor(hex: "#820000")
static let deepMauve = UIColor(hex: "#D473D4")
static let deepMossGreen = UIColor(hex: "#355E3B")
static let deepPeach = UIColor(hex: "#FFCBA4")
static let deepPink = UIColor(hex: "#FF1493")
static let deepPuce = UIColor(hex: "#A95C68")
static let deepRed = UIColor(hex: "#850101")
static let deepRuby = UIColor(hex: "#843F5B")
static let deepSaffron = UIColor(hex: "#FF9933")
static let deepSkyBlue = UIColor(hex: "#00BFFF")
static let deepSpaceSparkle = UIColor(hex: "#4A646C")
static let deepSpringBud = UIColor(hex: "#556B2F")
static let deepTaupe = UIColor(hex: "#7E5E60")
static let deepTuscanRed = UIColor(hex: "#66424D")
static let deepViolet = UIColor(hex: "#330066")
static let deer = UIColor(hex: "#BA8759")
static let denim = UIColor(hex: "#1560BD")
static let denimBlue = UIColor(hex: "#2243B6")
static let desaturatedCyan = UIColor(hex: "#669999")
static let desert = UIColor(hex: "#C19A6B")
static let desertSand = UIColor(hex: "#EDC9AF")
static let desire = UIColor(hex: "#EA3C53")
static let diamond = UIColor(hex: "#B9F2FF")
static let dimGray = UIColor(hex: "#696969")
static let dingyDungeon = UIColor(hex: "#C53151")
static let dirt = UIColor(hex: "#9B7653")
static let dodgerBlue = UIColor(hex: "#1E90FF")
static let dogwoodRose = UIColor(hex: "#D71868")
static let dollarBill = UIColor(hex: "#85BB65")
static let dolphinGray = UIColor(hex: "#828E84")
static let donkeyBrown = UIColor(hex: "#664C28")
static let drab = UIColor(hex: "#967117")
static let dukeBlue = UIColor(hex: "#00009C")
static let dustStorm = UIColor(hex: "#E5CCC9")
static let dutchWhite = UIColor(hex: "#EFDFBB")
static let earthYellow = UIColor(hex: "#E1A95F")
static let ebony = UIColor(hex: "#555D50")
static let ecru = UIColor(hex: "#C2B280")
static let eerieBlack = UIColor(hex: "#1B1B1B")
static let eggplant = UIColor(hex: "#614051")
static let eggshell = UIColor(hex: "#F0EAD6")
static let egyptianBlue = UIColor(hex: "#1034A6")
static let electricBlue = UIColor(hex: "#7DF9FF")
static let electricCrimson = UIColor(hex: "#FF003F")
static let electricCyan = UIColor(hex: "#00FFFF")
static let electricGreen = UIColor(hex: "#00FF00")
static let electricIndigo = UIColor(hex: "#6F00FF")
static let electricLavender = UIColor(hex: "#F4BBFF")
static let electricLime = UIColor(hex: "#CCFF00")
static let electricPurple = UIColor(hex: "#BF00FF")
static let electricUltramarine = UIColor(hex: "#3F00FF")
static let electricViolet = UIColor(hex: "#8F00FF")
static let electricYellow = UIColor(hex: "#FFFF33")
static let emerald = UIColor(hex: "#50C878")
static let eminence = UIColor(hex: "#6C3082")
static let englishGreen = UIColor(hex: "#1B4D3E")
static let englishLavender = UIColor(hex: "#B48395")
static let englishRed = UIColor(hex: "#AB4B52")
static let englishVermillion = UIColor(hex: "#CC474B")
static let englishViolet = UIColor(hex: "#563C5C")
static let etonBlue = UIColor(hex: "#96C8A2")
static let eucalyptus = UIColor(hex: "#44D7A8")
static let fallow = UIColor(hex: "#C19A6B")
static let faluRed = UIColor(hex: "#801818")
static let fandango = UIColor(hex: "#B53389")
static let fandangoPink = UIColor(hex: "#DE5285")
static let fashionFuchsia = UIColor(hex: "#F400A1")
static let fawn = UIColor(hex: "#E5AA70")
static let feldgrau = UIColor(hex: "#4D5D53")
static let feldspar = UIColor(hex: "#FDD5B1")
static let fernGreen = UIColor(hex: "#4F7942")
static let ferrariRed = UIColor(hex: "#FF2800")
static let fieldDrab = UIColor(hex: "#6C541E")
static let fieryRose = UIColor(hex: "#FF5470")
static let firebrick = UIColor(hex: "#B22222")
static let fireEngineRed = UIColor(hex: "#CE2029")
static let flame = UIColor(hex: "#E25822")
static let flamingoPink = UIColor(hex: "#FC8EAC")
static let flattery = UIColor(hex: "#6B4423")
static let flavescent = UIColor(hex: "#F7E98E")
static let flax = UIColor(hex: "#EEDC82")
static let flirt = UIColor(hex: "#A2006D")
static let floralWhite = UIColor(hex: "#FFFAF0")
static let fluorescentOrange = UIColor(hex: "#FFBF00")
static let fluorescentPink = UIColor(hex: "#FF1493")
static let fluorescentYellow = UIColor(hex: "#CCFF00")
static let folly = UIColor(hex: "#FF004F")
static let forestGreenTraditional = UIColor(hex: "#014421")
static let forestGreenWeb = UIColor(hex: "#228B22")
static let frenchBeige = UIColor(hex: "#A67B5B")
static let frenchBistre = UIColor(hex: "#856D4D")
static let frenchBlue = UIColor(hex: "#0072BB")
static let frenchFuchsia = UIColor(hex: "#FD3F92")
static let frenchLilac = UIColor(hex: "#86608E")
static let frenchLime = UIColor(hex: "#9EFD38")
static let frenchMauve = UIColor(hex: "#D473D4")
static let frenchPink = UIColor(hex: "#FD6C9E")
static let frenchPlum = UIColor(hex: "#811453")
static let frenchPuce = UIColor(hex: "#4E1609")
static let frenchRaspberry = UIColor(hex: "#C72C48")
static let frenchRose = UIColor(hex: "#F64A8A")
static let frenchSkyBlue = UIColor(hex: "#77B5FE")
static let frenchViolet = UIColor(hex: "#8806CE")
static let frenchWine = UIColor(hex: "#AC1E44")
static let freshAir = UIColor(hex: "#A6E7FF")
static let frostbite = UIColor(hex: "#E936A7")
static let fuchsia = UIColor(hex: "#FF00FF")
static let fuchsiaCrayola = UIColor(hex: "#C154C1")
static let fuchsiaPink = UIColor(hex: "#FF77FF")
static let fuchsiaPurple = UIColor(hex: "#CC397B")
static let fuchsiaRose = UIColor(hex: "#C74375")
static let fulvous = UIColor(hex: "#E48400")
static let fuzzyWuzzy = UIColor(hex: "#CC6666")
static let gainsboro = UIColor(hex: "#DCDCDC")
static let gamboge = UIColor(hex: "#E49B0F")
static let gambogeOrangeBrown = UIColor(hex: "#996600")
static let gargoyleGas = UIColor(hex: "#FFDF46")
static let genericViridian = UIColor(hex: "#007F66")
static let ghostWhite = UIColor(hex: "#F8F8FF")
static let giantsClub = UIColor(hex: "#B05C52")
static let giantsOrange = UIColor(hex: "#FE5A1D")
static let ginger = UIColor(hex: "#B06500")
static let glaucous = UIColor(hex: "#6082B6")
static let glitter = UIColor(hex: "#E6E8FA")
static let glossyGrape = UIColor(hex: "#AB92B3")
static let gOGreen = UIColor(hex: "#00AB66")
static let goldMetallic = UIColor(hex: "#D4AF37")
static let goldWebGolden = UIColor(hex: "#FFD700")
static let goldFusion = UIColor(hex: "#85754E")
static let goldenBrown = UIColor(hex: "#996515")
static let goldenPoppy = UIColor(hex: "#FCC200")
static let goldenYellow = UIColor(hex: "#FFDF00")
static let goldenrod = UIColor(hex: "#DAA520")
static let graniteGray = UIColor(hex: "#676767")
static let grannySmithApple = UIColor(hex: "#A8E4A0")
static let grape = UIColor(hex: "#6F2DA8")
static let gray = UIColor(hex: "#808080")
static let grayHTMLCSSGray = UIColor(hex: "#808080")
static let grayX11Gray = UIColor(hex: "#BEBEBE")
static let grayAsparagus = UIColor(hex: "#465945")
static let grayBlue = UIColor(hex: "#8C92AC")
static let greenColorWheelX11Green = UIColor(hex: "#00FF00")
static let greenCrayola = UIColor(hex: "#1CAC78")
static let greenHTMLCSSColor = UIColor(hex: "#008000")
static let greenMunsell = UIColor(hex: "#00A877")
static let greenNCS = UIColor(hex: "#009F6B")
static let greenPantone = UIColor(hex: "#00AD43")
static let greenPigment = UIColor(hex: "#00A550")
static let greenRYB = UIColor(hex: "#66B032")
static let greenBlue = UIColor(hex: "#1164B4")
static let greenCyan = UIColor(hex: "#009966")
static let greenLizard = UIColor(hex: "#A7F432")
static let greenSheen = UIColor(hex: "#6EAEA1")
static let greenYellow = UIColor(hex: "#ADFF2F")
static let grizzly = UIColor(hex: "#885818")
static let grullo = UIColor(hex: "#A99A86")
static let guppieGreen = UIColor(hex: "#00FF7F")
static let gunmetal = UIColor(hex: "#2a3439")
static let halayàÚbe = UIColor(hex: "#663854")
static let hanBlue = UIColor(hex: "#446CCF")
static let hanPurple = UIColor(hex: "#5218FA")
static let hansaYellow = UIColor(hex: "#E9D66B")
static let harlequin = UIColor(hex: "#3FFF00")
static let harlequinGreen = UIColor(hex: "#46CB18")
static let harletdCrimson = UIColor(hex: "#C90016")
static let harvestGold = UIColor(hex: "#DA9100")
static let heartGold = UIColor(hex: "#808000")
static let heatWave = UIColor(hex: "#FF7A00")
static let heidelbergRed = UIColor(hex: "#960018")
static let heliotrope = UIColor(hex: "#DF73FF")
static let heliotropeGray = UIColor(hex: "#AA98A9")
static let heliotropeMagenta = UIColor(hex: "#AA00BB")
static let hollywoodCerise = UIColor(hex: "#F400A1")
static let honeydew = UIColor(hex: "#F0FFF0")
static let honoluluBlue = UIColor(hex: "#006DB0")
static let hookersGreen = UIColor(hex: "#49796B")
static let hotMagenta = UIColor(hex: "#FF1DCE")
static let hotPink = UIColor(hex: "#FF69B4")
static let hunterGreen = UIColor(hex: "#355E3B")
static let iceberg = UIColor(hex: "#71A6D2")
static let icterine = UIColor(hex: "#FCF75E")
static let iguanaGreen = UIColor(hex: "#71BC78")
static let illuminatingEmerald = UIColor(hex: "#319177")
static let imperial = UIColor(hex: "#602F6B")
static let imperialBlue = UIColor(hex: "#002395")
static let imperialPurple = UIColor(hex: "#66023C")
static let imperialRed = UIColor(hex: "#ED2939")
static let inchworm = UIColor(hex: "#B2EC5D")
static let independence = UIColor(hex: "#4C516D")
static let indiaGreen = UIColor(hex: "#138808")
static let indianRed = UIColor(hex: "#CD5C5C")
static let indianYellow = UIColor(hex: "#E3A857")
static let indigo = UIColor(hex: "#4B0082")
static let indigoDye = UIColor(hex: "#091F92")
static let indigoWeb = UIColor(hex: "#4B0082")
static let infraRed = UIColor(hex: "#FF496C")
static let interdimensionalBlue = UIColor(hex: "#360CCC")
static let internationalKleinBlue = UIColor(hex: "#002FA7")
static let internationalOrangeAerospace = UIColor(hex: "#FF4F00")
static let internationalOrangeEngineering = UIColor(hex: "#BA160C")
static let internationalOrangeGoldenGateBridge = UIColor(hex: "#C0362C")
static let iris = UIColor(hex: "#5A4FCF")
static let irresistible = UIColor(hex: "#B3446C")
static let isabelline = UIColor(hex: "#F4F0EC")
static let islamicGreen = UIColor(hex: "#009000")
static let italianSkyBlue = UIColor(hex: "#B2FFFF")
static let ivory = UIColor(hex: "#FFFFF0")
static let jade = UIColor(hex: "#00A86B")
static let japaneseCarmine = UIColor(hex: "#9D2933")
static let japaneseIndigo = UIColor(hex: "#264348")
static let japaneseViolet = UIColor(hex: "#5B3256")
static let jasmine = UIColor(hex: "#F8DE7E")
static let jasper = UIColor(hex: "#D73B3E")
static let jazzberryJam = UIColor(hex: "#A50B5E")
static let jellyBean = UIColor(hex: "#DA614E")
static let jet = UIColor(hex: "#343434")
static let jonquil = UIColor(hex: "#F4CA16")
static let jordyBlue = UIColor(hex: "#8AB9F1")
static let juneBud = UIColor(hex: "#BDDA57")
static let jungleGreen = UIColor(hex: "#29AB87")
static let kellyGreen = UIColor(hex: "#4CBB17")
static let kenyanCopper = UIColor(hex: "#7C1C05")
static let keppel = UIColor(hex: "#3AB09E")
static let keyLime = UIColor(hex: "#E8F48C")
static let khakiHTMLCSSKhaki = UIColor(hex: "#C3B091")
static let khakiX11LightKhaki = UIColor(hex: "#F0E68C")
static let kiwi = UIColor(hex: "#8EE53F")
static let kobe = UIColor(hex: "#882D17")
static let kobi = UIColor(hex: "#E79FC4")
static let kobicha = UIColor(hex: "#6B4423")
static let kombuGreen = UIColor(hex: "#354230")
static let kSUPurple = UIColor(hex: "#512888")
static let kUCrimson = UIColor(hex: "#E8000D")
static let laSalleGreen = UIColor(hex: "#087830")
static let languidLavender = UIColor(hex: "#D6CADD")
static let lapisLazuli = UIColor(hex: "#26619C")
static let laserLemon = UIColor(hex: "#FFFF66")
static let laurelGreen = UIColor(hex: "#A9BA9D")
static let lava = UIColor(hex: "#CF1020")
static let lavenderFloral = UIColor(hex: "#B57EDC")
static let lavenderWeb = UIColor(hex: "#E6E6FA")
static let lavenderBlue = UIColor(hex: "#CCCCFF")
static let lavenderBlush = UIColor(hex: "#FFF0F5")
static let lavenderGray = UIColor(hex: "#C4C3D0")
static let lavenderIndigo = UIColor(hex: "#9457EB")
static let lavenderMagenta = UIColor(hex: "#EE82EE")
static let lavenderMist = UIColor(hex: "#E6E6FA")
static let lavenderPink = UIColor(hex: "#FBAED2")
static let lavenderPurple = UIColor(hex: "#967BB6")
static let lavenderRose = UIColor(hex: "#FBA0E3")
static let lawnGreen = UIColor(hex: "#7CFC00")
static let lemon = UIColor(hex: "#FFF700")
static let lemonChiffon = UIColor(hex: "#FFFACD")
static let lemonCurry = UIColor(hex: "#CCA01D")
static let lemonGlacier = UIColor(hex: "#FDFF00")
static let lemonLime = UIColor(hex: "#E3FF00")
static let lemonMeringue = UIColor(hex: "#F6EABE")
static let lemonYellow = UIColor(hex: "#FFF44F")
static let licorice = UIColor(hex: "#1A1110")
static let liberty = UIColor(hex: "#545AA7")
static let lightApricot = UIColor(hex: "#FDD5B1")
static let lightBlue = UIColor(hex: "#ADD8E6")
static let lightBrown = UIColor(hex: "#B5651D")
static let lightCarminePink = UIColor(hex: "#E66771")
static let lightCobaltBlue = UIColor(hex: "#88ACE0")
static let lightCoral = UIColor(hex: "#F08080")
static let lightCornflowerBlue = UIColor(hex: "#93CCEA")
static let lightCrimson = UIColor(hex: "#F56991")
static let lightCyan = UIColor(hex: "#E0FFFF")
static let lightDeepPink = UIColor(hex: "#FF5CCD")
static let lightFrenchBeige = UIColor(hex: "#C8AD7F")
static let lightFuchsiaPink = UIColor(hex: "#F984EF")
static let lightGoldenrodYellow = UIColor(hex: "#FAFAD2")
static let lightGray = UIColor(hex: "#D3D3D3")
static let lightGrayishMagenta = UIColor(hex: "#CC99CC")
static let lightGreen = UIColor(hex: "#90EE90")
static let lightHotPink = UIColor(hex: "#FFB3DE")
static let lightKhaki = UIColor(hex: "#F0E68C")
static let lightMediumOrchid = UIColor(hex: "#D39BCB")
static let lightMossGreen = UIColor(hex: "#ADDFAD")
static let lightOrange = UIColor(hex: "#FED8B1")
static let lightOrchid = UIColor(hex: "#E6A8D7")
static let lightPastelPurple = UIColor(hex: "#B19CD9")
static let lightPink = UIColor(hex: "#FFB6C1")
static let lightRedOchre = UIColor(hex: "#E97451")
static let lightSalmon = UIColor(hex: "#FFA07A")
static let lightSalmonPink = UIColor(hex: "#FF9999")
static let lightSeaGreen = UIColor(hex: "#20B2AA")
static let lightSkyBlue = UIColor(hex: "#87CEFA")
static let lightSlateGray = UIColor(hex: "#778899")
static let lightSteelBlue = UIColor(hex: "#B0C4DE")
static let lightTaupe = UIColor(hex: "#B38B6D")
static let lightThulianPink = UIColor(hex: "#E68FAC")
static let lightYellow = UIColor(hex: "#FFFFE0")
static let lilac = UIColor(hex: "#C8A2C8")
static let lilacLuster = UIColor(hex: "#AE98AA")
static let limeColorWheel = UIColor(hex: "#BFFF00")
static let limeWebX11Green = UIColor(hex: "#00FF00")
static let limeGreen = UIColor(hex: "#32CD32")
static let limerick = UIColor(hex: "#9DC209")
static let lincolnGreen = UIColor(hex: "#195905")
static let linen = UIColor(hex: "#FAF0E6")
static let loeen = UIColor(hex: "#15F2FD")
static let liseranPurple = UIColor(hex: "#DE6FA1")
static let littleBoyBlue = UIColor(hex: "#6CA0DC")
static let liver = UIColor(hex: "#674C47")
static let liverDogs = UIColor(hex: "#B86D29")
static let liverOrgan = UIColor(hex: "#6C2E1F")
static let liverChestnut = UIColor(hex: "#987456")
static let livid = UIColor(hex: "#6699CC")
static let lumber = UIColor(hex: "#FFE4CD")
static let lust = UIColor(hex: "#E62020")
static let maastrichtBlue = UIColor(hex: "#001C3D")
static let macaroniAndCheese = UIColor(hex: "#FFBD88")
static let madderLake = UIColor(hex: "#CC3336")
static let magenta = UIColor(hex: "#FF00FF")
static let magentaCrayola = UIColor(hex: "#FF55A3")
static let magentaDye = UIColor(hex: "#CA1F7B")
static let magentaPantone = UIColor(hex: "#D0417E")
static let magentaProcess = UIColor(hex: "#FF0090")
static let magentaHaze = UIColor(hex: "#9F4576")
static let magentaPink = UIColor(hex: "#CC338B")
static let magicMint = UIColor(hex: "#AAF0D1")
static let magicPotion = UIColor(hex: "#FF4466")
static let magnolia = UIColor(hex: "#F8F4FF")
static let mahogany = UIColor(hex: "#C04000")
static let maize = UIColor(hex: "#FBEC5D")
static let majorelleBlue = UIColor(hex: "#6050DC")
static let malachite = UIColor(hex: "#0BDA51")
static let manatee = UIColor(hex: "#979AAA")
static let mandarin = UIColor(hex: "#F37A48")
static let mangoTango = UIColor(hex: "#FF8243")
static let mantis = UIColor(hex: "#74C365")
static let mardiGras = UIColor(hex: "#880085")
static let marigold = UIColor(hex: "#EAA221")
static let maroonCrayola = UIColor(hex: "#C32148")
static let maroonHTMLCSS = UIColor(hex: "#800000")
static let maroonX11 = UIColor(hex: "#B03060")
static let mauve = UIColor(hex: "#E0B0FF")
static let mauveTaupe = UIColor(hex: "#915F6D")
static let mauvelous = UIColor(hex: "#EF98AA")
static let maximumBlue = UIColor(hex: "#47ABCC")
static let maximumBlueGreen = UIColor(hex: "#30BFBF")
static let maximumBluePurple = UIColor(hex: "#ACACE6")
static let maximumGreen = UIColor(hex: "#5E8C31")
static let maximumGreenYellow = UIColor(hex: "#D9E650")
static let maximumPurple = UIColor(hex: "#733380")
static let maximumRed = UIColor(hex: "#D92121")
static let maximumRedPurple = UIColor(hex: "#A63A79")
static let maximumYellow = UIColor(hex: "#FAFA37")
static let maximumYellowRed = UIColor(hex: "#F2BA49")
static let mayGreen = UIColor(hex: "#4C9141")
static let mayaBlue = UIColor(hex: "#73C2FB")
static let meatBrown = UIColor(hex: "#E5B73B")
static let mediumAquamarine = UIColor(hex: "#66DDAA")
static let mediumBlue = UIColor(hex: "#0000CD")
static let mediumCandyAppleRed = UIColor(hex: "#E2062C")
static let mediumCarmine = UIColor(hex: "#AF4035")
static let mediumChampagne = UIColor(hex: "#F3E5AB")
static let mediumElectricBlue = UIColor(hex: "#035096")
static let mediumJungleGreen = UIColor(hex: "#1C352D")
static let mediumLavenderMagenta = UIColor(hex: "#DDA0DD")
static let mediumOrchid = UIColor(hex: "#BA55D3")
static let mediumPersianBlue = UIColor(hex: "#0067A5")
static let mediumPurple = UIColor(hex: "#9370DB")
static let mediumRedViolet = UIColor(hex: "#BB3385")
static let mediumRuby = UIColor(hex: "#AA4069")
static let mediumSeaGreen = UIColor(hex: "#3CB371")
static let mediumSkyBlue = UIColor(hex: "#80DAEB")
static let mediumSlateBlue = UIColor(hex: "#7B68EE")
static let mediumSpringBud = UIColor(hex: "#C9DC87")
static let mediumSpringGreen = UIColor(hex: "#00FA9A")
static let mediumTaupe = UIColor(hex: "#674C47")
static let mediumTurquoise = UIColor(hex: "#48D1CC")
static let mediumTuscanRed = UIColor(hex: "#79443B")
static let mediumVermilion = UIColor(hex: "#D9603B")
static let mediumVioletRed = UIColor(hex: "#C71585")
static let mellowApricot = UIColor(hex: "#F8B878")
static let mellowYellow = UIColor(hex: "#F8DE7E")
static let melon = UIColor(hex: "#FDBCB4")
static let metallicSeaweed = UIColor(hex: "#0A7E8C")
static let metallicSunburst = UIColor(hex: "#9C7C38")
static let mexicanPink = UIColor(hex: "#E4007C")
static let middleBlue = UIColor(hex: "#7ED4E6")
static let middleBlueGreen = UIColor(hex: "#8DD9CC")
static let middleBluePurple = UIColor(hex: "#8B72BE")
static let middleGreen = UIColor(hex: "#4D8C57")
static let middleGreenYellow = UIColor(hex: "#ACBF60")
static let middlePurple = UIColor(hex: "#D982B5")
static let middleRed = UIColor(hex: "#E58E73")
static let middleRedPurple = UIColor(hex: "#A55353")
static let middleYellow = UIColor(hex: "#FFEB00")
static let middleYellowRed = UIColor(hex: "#ECB176")
static let midnight = UIColor(hex: "#702670")
static let midnightBlue = UIColor(hex: "#191970")
static let midnightGreenEagleGreen = UIColor(hex: "#004953")
static let mikadoYellow = UIColor(hex: "#FFC40C")
static let milk = UIColor(hex: "#FDFFF5")
static let mimiPink = UIColor(hex: "#FFDAE9")
static let mindaro = UIColor(hex: "#E3F988")
static let ming = UIColor(hex: "#36747D")
static let minionYellow = UIColor(hex: "#F5E050")
static let mint = UIColor(hex: "#3EB489")
static let mintCream = UIColor(hex: "#F5FFFA")
static let mintGreen = UIColor(hex: "#98FF98")
static let mistyMoss = UIColor(hex: "#BBB477")
static let mistyRose = UIColor(hex: "#FFE4E1")
static let moccasin = UIColor(hex: "#FAEBD7")
static let modeBeige = UIColor(hex: "#967117")
static let moonstoneBlue = UIColor(hex: "#73A9C2")
static let mordantRed19 = UIColor(hex: "#AE0C00")
static let morningBlue = UIColor(hex: "#8DA399")
static let mossGreen = UIColor(hex: "#8A9A5B")
static let mountainMeadow = UIColor(hex: "#30BA8F")
static let mountbattenPink = UIColor(hex: "#997A8D")
static let mSUGreen = UIColor(hex: "#18453B")
static let mughalGreen = UIColor(hex: "#306030")
static let mulberry = UIColor(hex: "#C54B8C")
static let mummysTomb = UIColor(hex: "#828E84")
static let mustard = UIColor(hex: "#FFDB58")
static let myrtleGreen = UIColor(hex: "#317873")
static let mystic = UIColor(hex: "#D65282")
static let mysticMaroon = UIColor(hex: "#AD4379")
static let nadeshikoPink = UIColor(hex: "#F6ADC6")
static let napierGreen = UIColor(hex: "#2A8000")
static let naplesYellow = UIColor(hex: "#FADA5E")
static let navajoWhite = UIColor(hex: "#FFDEAD")
static let navy = UIColor(hex: "#000080")
static let navyPurple = UIColor(hex: "#9457EB")
static let neonCarrot = UIColor(hex: "#FFA343")
static let neonFuchsia = UIColor(hex: "#FE4164")
static let neonGreen = UIColor(hex: "#39FF14")
static let newCar = UIColor(hex: "#214FC6")
static let newYorkPink = UIColor(hex: "#D7837F")
static let nickel = UIColor(hex: "#727472")
static let nonPhotoBlue = UIColor(hex: "#A4DDED")
static let northTexasGreen = UIColor(hex: "#059033")
static let nyanza = UIColor(hex: "#E9FFDB")
static let oceanBlue = UIColor(hex: "#4F42B5")
static let oceanBoatBlue = UIColor(hex: "#0077BE")
static let oceanGreen = UIColor(hex: "#48BF91")
static let ochre = UIColor(hex: "#CC7722")
static let officeGreen = UIColor(hex: "#008000")
static let ogreOdor = UIColor(hex: "#FD5240")
static let oldBurgundy = UIColor(hex: "#43302E")
static let oldGold = UIColor(hex: "#CFB53B")
static let oldHeliotrope = UIColor(hex: "#563C5C")
static let oldLace = UIColor(hex: "#FDF5E6")
static let oldLavender = UIColor(hex: "#796878")
static let oldMauve = UIColor(hex: "#673147")
static let oldMossGreen = UIColor(hex: "#867E36")
static let oldRose = UIColor(hex: "#C08081")
static let oldSilver = UIColor(hex: "#848482")
static let olive = UIColor(hex: "#808000")
static let oliveDrab3 = UIColor(hex: "#6B8E23")
static let oliveDrab7 = UIColor(hex: "#3C341F")
static let olivine = UIColor(hex: "#9AB973")
static let onyx = UIColor(hex: "#353839")
static let operaMauve = UIColor(hex: "#B784A7")
static let orangeColorWheel = UIColor(hex: "#FF7F00")
static let orangeCrayola = UIColor(hex: "#FF7538")
static let orangePantone = UIColor(hex: "#FF5800")
static let orangeRYB = UIColor(hex: "#FB9902")
static let orangeWeb = UIColor(hex: "#FFA500")
static let orangePeel = UIColor(hex: "#FF9F00")
static let orangeRed = UIColor(hex: "#FF4500")
static let orangeSoda = UIColor(hex: "#FA5B3D")
static let orangeYellow = UIColor(hex: "#F8D568")
static let orchid = UIColor(hex: "#DA70D6")
static let orchidPink = UIColor(hex: "#F2BDCD")
static let oriolesOrange = UIColor(hex: "#FB4F14")
static let otterBrown = UIColor(hex: "#654321")
static let outerSpace = UIColor(hex: "#414A4C")
static let outrageousOrange = UIColor(hex: "#FF6E4A")
static let oxfordBlue = UIColor(hex: "#002147")
static let oUCrimsonRed = UIColor(hex: "#990000")
static let pacificBlue = UIColor(hex: "#1CA9C9")
static let pakistanGreen = UIColor(hex: "#006600")
static let palatinateBlue = UIColor(hex: "#273BE2")
static let palatinatePurple = UIColor(hex: "#682860")
static let paleAqua = UIColor(hex: "#BCD4E6")
static let paleBlue = UIColor(hex: "#AFEEEE")
static let paleBrown = UIColor(hex: "#987654")
static let paleCarmine = UIColor(hex: "#AF4035")
static let paleCerulean = UIColor(hex: "#9BC4E2")
static let paleChestnut = UIColor(hex: "#DDADAF")
static let paleCopper = UIColor(hex: "#DA8A67")
static let paleCornflowerBlue = UIColor(hex: "#ABCDEF")
static let paleCyan = UIColor(hex: "#87D3F8")
static let paleGold = UIColor(hex: "#E6BE8A")
static let paleGoldenrod = UIColor(hex: "#EEE8AA")
static let paleGreen = UIColor(hex: "#98FB98")
static let paleLavender = UIColor(hex: "#DCD0FF")
static let paleMagenta = UIColor(hex: "#F984E5")
static let paleMagentaPink = UIColor(hex: "#FF99CC")
static let palePink = UIColor(hex: "#FADADD")
static let palePlum = UIColor(hex: "#DDA0DD")
static let paleRedViolet = UIColor(hex: "#DB7093")
static let paleRobinEggBlue = UIColor(hex: "#96DED1")
static let paleSilver = UIColor(hex: "#C9C0BB")
static let paleSpringBud = UIColor(hex: "#ECEBBD")
static let paletaupe = UIColor(hex: "#BC987E")
static let paleturquoise = UIColor(hex: "#AFEEEE")
static let paleViolet = UIColor(hex: "#CC99FF")
static let paleVioletRed = UIColor(hex: "#DB7093")
static let palmLeaf = UIColor(hex: "#6F9940")
static let pansyPurple = UIColor(hex: "#78184A")
static let paoloVeroneseGreen = UIColor(hex: "#009B7D")
static let papayaWhip = UIColor(hex: "#FFEFD5")
static let paradisePink = UIColor(hex: "#E63E62")
static let parisGreen = UIColor(hex: "#50C878")
static let parrotPink = UIColor(hex: "#D998A0")
static let pastelBlue = UIColor(hex: "#AEC6CF")
static let pastelBrown = UIColor(hex: "#836953")
static let pastelGray = UIColor(hex: "#CFCFC4")
static let pastelGreen = UIColor(hex: "#77DD77")
static let pastelMagenta = UIColor(hex: "#F49AC2")
static let pastelOrange = UIColor(hex: "#FFB347")
static let pastelPink = UIColor(hex: "#DEA5A4")
static let pastelPurple = UIColor(hex: "#B39EB5")
static let pastelRed = UIColor(hex: "#FF6961")
static let pastelViolet = UIColor(hex: "#CB99C9")
static let pastelYellow = UIColor(hex: "#FDFD96")
static let patriarch = UIColor(hex: "#800080")
static let paynesGrey = UIColor(hex: "#536878")
static let peach = UIColor(hex: "#FFE5B4")
static let peachOrange = UIColor(hex: "#FFCC99")
static let peachPuff = UIColor(hex: "#FFDAB9")
static let peachYellow = UIColor(hex: "#FADFAD")
static let pear = UIColor(hex: "#D1E231")
static let pearl = UIColor(hex: "#EAE0C8")
static let pearlAqua = UIColor(hex: "#88D8C0")
static let pearlyPurple = UIColor(hex: "#B768A2")
static let peridot = UIColor(hex: "#E6E200")
static let periwinkle = UIColor(hex: "#CCCCFF")
static let permanentGeraniumLake = UIColor(hex: "#E12C2C")
static let persianBlue = UIColor(hex: "#1C39BB")
static let persianGreen = UIColor(hex: "#00A693")
static let persianIndigo = UIColor(hex: "#32127A")
static let persianOrange = UIColor(hex: "#D99058")
static let persianPink = UIColor(hex: "#F77FBE")
static let persianPlum = UIColor(hex: "#701C1C")
static let persianRed = UIColor(hex: "#CC3333")
static let persianRose = UIColor(hex: "#FE28A2")
static let persimmon = UIColor(hex: "#EC5800")
static let peru = UIColor(hex: "#CD853F")
static let pewterBlue = UIColor(hex: "#8BA8B7")
static let phlox = UIColor(hex: "#DF00FF")
static let phthaloBlue = UIColor(hex: "#000F89")
static let phthaloGreen = UIColor(hex: "#123524")
static let pictonBlue = UIColor(hex: "#45B1E8")
static let pictorialCarmine = UIColor(hex: "#C30B4E")
static let piggyPink = UIColor(hex: "#FDDDE6")
static let pineGreen = UIColor(hex: "#01796F")
static let pineapple = UIColor(hex: "#563C5C")
static let pink = UIColor(hex: "#FFC0CB")
static let pinkPantone = UIColor(hex: "#D74894")
static let pinkFlamingo = UIColor(hex: "#FC74FD")
static let pinkLace = UIColor(hex: "#FFDDF4")
static let pinkLavender = UIColor(hex: "#D8B2D1")
static let pinkOrange = UIColor(hex: "#FF9966")
static let pinkPearl = UIColor(hex: "#E7ACCF")
static let pinkRaspberry = UIColor(hex: "#980036")
static let pinkSherbet = UIColor(hex: "#F78FA7")
static let pistachio = UIColor(hex: "#93C572")
static let pixiePowder = UIColor(hex: "#391285")
static let platinum = UIColor(hex: "#E5E4E2")
static let plum = UIColor(hex: "#8E4585")
static let plumWeb = UIColor(hex: "#DDA0DD")
static let plumpPurple = UIColor(hex: "#5946B2")
static let polishedPine = UIColor(hex: "#5DA493")
static let pompAndPower = UIColor(hex: "#86608E")
static let popstar = UIColor(hex: "#BE4F62")
static let portlandOrange = UIColor(hex: "#FF5A36")
static let powderBlue = UIColor(hex: "#B0E0E6")
static let princessPerfume = UIColor(hex: "#FF85CF")
static let princetonOrange = UIColor(hex: "#F58025")
static let prune = UIColor(hex: "#701C1C")
static let prussianBlue = UIColor(hex: "#003153")
static let psychedelicPurple = UIColor(hex: "#DF00FF")
static let puce = UIColor(hex: "#CC8899")
static let puceRed = UIColor(hex: "#722F37")
static let pullmanBrownUPSBrown = UIColor(hex: "#644117")
static let pullmanGreen = UIColor(hex: "#3B331C")
static let pumpkin = UIColor(hex: "#FF7518")
static let purpleHTML = UIColor(hex: "#800080")
static let purpleMunsell = UIColor(hex: "#9F00C5")
static let purpleX11 = UIColor(hex: "#A020F0")
static let purpleHeart = UIColor(hex: "#69359C")
static let purpleMountainMajesty = UIColor(hex: "#9678B6")
static let purpleNavy = UIColor(hex: "#4E5180")
static let purplePizzazz = UIColor(hex: "#FE4EDA")
static let purplePlum = UIColor(hex: "#9C51B6")
static let purpletaupe = UIColor(hex: "#50404D")
static let purpureus = UIColor(hex: "#9A4EAE")
static let quartz = UIColor(hex: "#51484F")
static let queenBlue = UIColor(hex: "#436B95")
static let queenPink = UIColor(hex: "#E8CCD7")
static let quickSilver = UIColor(hex: "#A6A6A6")
static let quinacridoneMagenta = UIColor(hex: "#8E3A59")
static let rackley = UIColor(hex: "#5D8AA8")
static let radicalRed = UIColor(hex: "#FF355E")
static let raisinBlack = UIColor(hex: "#242124")
static let rajah = UIColor(hex: "#FBAB60")
static let raspberry = UIColor(hex: "#E30B5D")
static let raspberryGlace = UIColor(hex: "#915F6D")
static let raspberryPink = UIColor(hex: "#E25098")
static let raspberryRose = UIColor(hex: "#B3446C")
static let rawSienna = UIColor(hex: "#D68A59")
static let rawUmber = UIColor(hex: "#826644")
static let razzleDazzleRose = UIColor(hex: "#FF33CC")
static let razzmatazz = UIColor(hex: "#E3256B")
static let razzmicBerry = UIColor(hex: "#8D4E85")
static let rebeccaPurple = UIColor(hex: "#663399")
static let red = UIColor(hex: "#FF0000")
static let redCrayola = UIColor(hex: "#EE204D")
static let redMunsell = UIColor(hex: "#F2003C")
static let redNCS = UIColor(hex: "#C40233")
static let redPantone = UIColor(hex: "#ED2939")
static let redPigment = UIColor(hex: "#ED1C24")
static let redRYB = UIColor(hex: "#FE2712")
static let redBrown = UIColor(hex: "#A52A2A")
static let redDevil = UIColor(hex: "#860111")
static let redOrange = UIColor(hex: "#FF5349")
static let redPurple = UIColor(hex: "#E40078")
static let redSalsa = UIColor(hex: "#FD3A4A")
static let redViolet = UIColor(hex: "#C71585")
static let redwood = UIColor(hex: "#A45A52")
static let regalia = UIColor(hex: "#522D80")
static let registrationBlack = UIColor(hex: "#000000")
static let resolutionBlue = UIColor(hex: "#002387")
static let rhythm = UIColor(hex: "#777696")
static let richBlack = UIColor(hex: "#004040")
static let richBlackFOGRA29 = UIColor(hex: "#010B13")
static let richBlackFOGRA39 = UIColor(hex: "#010203")
static let richBrilliantLavender = UIColor(hex: "#F1A7FE")
static let richCarmine = UIColor(hex: "#D70040")
static let richElectricBlue = UIColor(hex: "#0892D0")
static let richLavender = UIColor(hex: "#A76BCF")
static let richLilac = UIColor(hex: "#B666D2")
static let richMaroon = UIColor(hex: "#B03060")
static let rifleGreen = UIColor(hex: "#444C38")
static let roastCoffee = UIColor(hex: "#704241")
static let robinEggBlue = UIColor(hex: "#00CCCC")
static let rocketMetallic = UIColor(hex: "#8A7F80")
static let romanSilver = UIColor(hex: "#838996")
static let rose = UIColor(hex: "#FF007F")
static let roseBonbon = UIColor(hex: "#F9429E")
static let roseDust = UIColor(hex: "#9E5E6F")
static let roseEbony = UIColor(hex: "#674846")
static let roseGold = UIColor(hex: "#B76E79")
static let roseMadder = UIColor(hex: "#E32636")
static let rosePink = UIColor(hex: "#FF66CC")
static let roseQuartz = UIColor(hex: "#AA98A9")
static let roseRed = UIColor(hex: "#C21E56")
static let roseTaupe = UIColor(hex: "#905D5D")
static let roseVale = UIColor(hex: "#AB4E52")
static let rosewood = UIColor(hex: "#65000B")
static let rossoCorsa = UIColor(hex: "#D40000")
static let rosyBrown = UIColor(hex: "#BC8F8F")
static let royalAzure = UIColor(hex: "#0038A8")
static let royalBlue = UIColor(hex: "#002366")
static let royalFuchsia = UIColor(hex: "#CA2C92")
static let royalPurple = UIColor(hex: "#7851A9")
static let royalYellow = UIColor(hex: "#FADA5E")
static let ruber = UIColor(hex: "#CE4676")
static let rubineRed = UIColor(hex: "#D10056")
static let ruby = UIColor(hex: "#E0115F")
static let rubyRed = UIColor(hex: "#9B111E")
static let ruddy = UIColor(hex: "#FF0028")
static let ruddyBrown = UIColor(hex: "#BB6528")
static let ruddyPink = UIColor(hex: "#E18E96")
static let rufous = UIColor(hex: "#A81C07")
static let russet = UIColor(hex: "#80461B")
static let russianGreen = UIColor(hex: "#679267")
static let russianViolet = UIColor(hex: "#32174D")
static let rust = UIColor(hex: "#B7410E")
static let rustyRed = UIColor(hex: "#DA2C43")
static let sacramentoStateGreen = UIColor(hex: "#00563F")
static let saddleBrown = UIColor(hex: "#8B4513")
static let safetyOrange = UIColor(hex: "#FF7800")
static let safetyOrangeBlazeOrange = UIColor(hex: "#FF6700")
static let safetyYellow = UIColor(hex: "#EED202")
static let saffron = UIColor(hex: "#F4C430")
static let sage = UIColor(hex: "#BCB88A")
static let stPatricksBlue = UIColor(hex: "#23297A")
static let salmon = UIColor(hex: "#FA8072")
static let salmonPink = UIColor(hex: "#FF91A4")
static let sand = UIColor(hex: "#C2B280")
static let sandDune = UIColor(hex: "#967117")
static let sandstorm = UIColor(hex: "#ECD540")
static let sandyBrown = UIColor(hex: "#F4A460")
static let sandyTan = UIColor(hex: "#FDD9B5")
static let sandyTaupe = UIColor(hex: "#967117")
static let sangria = UIColor(hex: "#92000A")
static let sapGreen = UIColor(hex: "#507D2A")
static let sapphire = UIColor(hex: "#0F52BA")
static let sapphireBlue = UIColor(hex: "#0067A5")
static let sasquatchSocks = UIColor(hex: "#FF4681")
static let satinSheenGold = UIColor(hex: "#CBA135")
static let scarlet = UIColor(hex: "#FF2400")
static let schaussPink = UIColor(hex: "#FF91AF")
static let schoolBusYellow = UIColor(hex: "#FFD800")
static let screaminGreen = UIColor(hex: "#66FF66")
static let seaBlue = UIColor(hex: "#006994")
static let seaFoamGreen = UIColor(hex: "#9FE2BF")
static let seaGreen = UIColor(hex: "#2E8B57")
static let seaSerpent = UIColor(hex: "#4BC7CF")
static let sealBrown = UIColor(hex: "#59260B")
static let seashell = UIColor(hex: "#FFF5EE")
static let selectiveYellow = UIColor(hex: "#FFBA00")
static let sepia = UIColor(hex: "#704214")
static let shadow = UIColor(hex: "#8A795D")
static let shadowBlue = UIColor(hex: "#778BA5")
static let shampoo = UIColor(hex: "#FFCFF1")
static let shamrockGreen = UIColor(hex: "#009E60")
static let sheenGreen = UIColor(hex: "#8FD400")
static let shimmeringBlush = UIColor(hex: "#D98695")
static let shinyShamrock = UIColor(hex: "#5FA778")
static let shockingPink = UIColor(hex: "#FC0FC0")
static let shockingPinkCrayola = UIColor(hex: "#FF6FFF")
static let sienna = UIColor(hex: "#882D17")
static let silver = UIColor(hex: "#C0C0C0")
static let silverChalice = UIColor(hex: "#ACACAC")
static let silverLakeBlue = UIColor(hex: "#5D89BA")
static let silverPink = UIColor(hex: "#C4AEAD")
static let silverSand = UIColor(hex: "#BFC1C2")
static let sinopia = UIColor(hex: "#CB410B")
static let sizzlingRed = UIColor(hex: "#FF3855")
static let sizzlingSunrise = UIColor(hex: "#FFDB00")
static let skobeloff = UIColor(hex: "#007474")
static let skyBlue = UIColor(hex: "#87CEEB")
static let skyMagenta = UIColor(hex: "#CF71AF")
static let slateBlue = UIColor(hex: "#6A5ACD")
static let slateGray = UIColor(hex: "#708090")
static let smaltDarkPowderBlue = UIColor(hex: "#003399")
static let slimyGreen = UIColor(hex: "#299617")
static let smashedPumpkin = UIColor(hex: "#FF6D3A")
static let smitten = UIColor(hex: "#C84186")
static let smoke = UIColor(hex: "#738276")
static let smokeyTopaz = UIColor(hex: "#832A0D")
static let smokyBlack = UIColor(hex: "#100C08")
static let smokyTopaz = UIColor(hex: "#933D41")
static let snow = UIColor(hex: "#FFFAFA")
static let soap = UIColor(hex: "#CEC8EF")
static let solidPink = UIColor(hex: "#893843")
static let sonicSilver = UIColor(hex: "#757575")
static let spartanCrimson = UIColor(hex: "#9E1316")
static let spaceCadet = UIColor(hex: "#1D2951")
static let spanishBistre = UIColor(hex: "#807532")
static let spanishBlue = UIColor(hex: "#0070B8")
static let spanishCarmine = UIColor(hex: "#D10047")
static let spanishCrimson = UIColor(hex: "#E51A4C")
static let spanishGray = UIColor(hex: "#989898")
static let spanishGreen = UIColor(hex: "#009150")
static let spanishOrange = UIColor(hex: "#E86100")
static let spanishPink = UIColor(hex: "#F7BFBE")
static let spanishRed = UIColor(hex: "#E60026")
static let spanishSkyBlue = UIColor(hex: "#00FFFF")
static let spanishViolet = UIColor(hex: "#4C2882")
static let spanishViridian = UIColor(hex: "#007F5C")
static let spicyMix = UIColor(hex: "#8B5f4D")
static let spiroDiscoBall = UIColor(hex: "#0FC0FC")
static let springBud = UIColor(hex: "#A7FC00")
static let springFrost = UIColor(hex: "#87FF2A")
static let springGreen = UIColor(hex: "#00FF7F")
static let starCommandBlue = UIColor(hex: "#007BB8")
static let steelBlue = UIColor(hex: "#4682B4")
static let steelPink = UIColor(hex: "#CC33CC")
static let steelTeal = UIColor(hex: "#5F8A8B")
static let stilDeGrainYellow = UIColor(hex: "#FADA5E")
static let stizza = UIColor(hex: "#990000")
static let stormcloud = UIColor(hex: "#4F666A")
static let straw = UIColor(hex: "#E4D96F")
static let strawberry = UIColor(hex: "#FC5A8D")
static let sugarPlum = UIColor(hex: "#914E75")
static let sunburntCyclops = UIColor(hex: "#FF404C")
static let sunglow = UIColor(hex: "#FFCC33")
static let sunny = UIColor(hex: "#F2F27A")
static let sunray = UIColor(hex: "#E3AB57")
static let sunset = UIColor(hex: "#FAD6A5")
static let sunsetOrange = UIColor(hex: "#FD5E53")
static let superPink = UIColor(hex: "#CF6BA9")
static let sweetBrown = UIColor(hex: "#A83731")
static let tan = UIColor(hex: "#D2B48C")
static let tangelo = UIColor(hex: "#F94D00")
static let tangerine = UIColor(hex: "#F28500")
static let tangerineYellow = UIColor(hex: "#FFCC00")
static let tangoPink = UIColor(hex: "#E4717A")
static let tartOrange = UIColor(hex: "#FB4D46")
static let taupe = UIColor(hex: "#483C32")
static let taupeGray = UIColor(hex: "#8B8589")
static let teaGreen = UIColor(hex: "#D0F0C0")
static let teaRose = UIColor(hex: "#F88379")
static let teal = UIColor(hex: "#008080")
static let tealBlue = UIColor(hex: "#367588")
static let tealDeer = UIColor(hex: "#99E6B3")
static let tealGreen = UIColor(hex: "#00827F")
static let telemagenta = UIColor(hex: "#CF3476")
static let tenneTawny = UIColor(hex: "#CD5700")
static let terraCotta = UIColor(hex: "#E2725B")
static let thistle = UIColor(hex: "#D8BFD8")
static let thulianPink = UIColor(hex: "#DE6FA1")
static let tickleMePink = UIColor(hex: "#FC89AC")
static let tiffanyBlue = UIColor(hex: "#0ABAB5")
static let tigersEye = UIColor(hex: "#E08D3C")
static let timberwolf = UIColor(hex: "#DBD7D2")
static let titaniumYellow = UIColor(hex: "#EEE600")
static let tomato = UIColor(hex: "#FF6347")
static let toolbox = UIColor(hex: "#746CC0")
static let topaz = UIColor(hex: "#FFC87C")
static let tractorRed = UIColor(hex: "#FD0E35")
static let trolleyGrey = UIColor(hex: "#808080")
static let tropicalRainForest = UIColor(hex: "#00755E")
static let tropicalViolet = UIColor(hex: "#CDA4DE")
static let trueBlue = UIColor(hex: "#0073CF")
static let tuftsBlue = UIColor(hex: "#3E8EDE")
static let tulip = UIColor(hex: "#FF878D")
static let tumbleweed = UIColor(hex: "#DEAA88")
static let turkishRose = UIColor(hex: "#B57281")
static let turquoise = UIColor(hex: "#40E0D0")
static let turquoiseBlue = UIColor(hex: "#00FFEF")
static let turquoiseGreen = UIColor(hex: "#A0D6B4")
static let turquoiseSurf = UIColor(hex: "#00C5CD")
static let turtleGreen = UIColor(hex: "#8A9A5B")
static let tuscan = UIColor(hex: "#FAD6A5")
static let tuscanBrown = UIColor(hex: "#6F4E37")
static let tuscanRed = UIColor(hex: "#7C4848")
static let tuscanTan = UIColor(hex: "#A67B5B")
static let tuscany = UIColor(hex: "#C09999")
static let twilightLavender = UIColor(hex: "#8A496B")
static let tyrianPurple = UIColor(hex: "#66023C")
static let uABlue = UIColor(hex: "#0033AA")
static let uARed = UIColor(hex: "#D9004C")
static let ube = UIColor(hex: "#8878C3")
static let uCLABlue = UIColor(hex: "#536895")
static let uCLAGold = UIColor(hex: "#FFB300")
static let uFOGreen = UIColor(hex: "#3CD070")
static let ultramarine = UIColor(hex: "#3F00FF")
static let ultramarineBlue = UIColor(hex: "#4166F5")
static let ultraPink = UIColor(hex: "#FF6FFF")
static let ultraRed = UIColor(hex: "#FC6C85")
static let umber = UIColor(hex: "#635147")
static let unbleachedSilk = UIColor(hex: "#FFDDCA")
static let unitedNationsBlue = UIColor(hex: "#5B92E5")
static let universityOfCaliforniaGold = UIColor(hex: "#B78727")
static let unmellowYellow = UIColor(hex: "#FFFF66")
static let uPForestGreen = UIColor(hex: "#014421")
static let uPMaroon = UIColor(hex: "#7B1113")
static let upsdellRed = UIColor(hex: "#AE2029")
static let urobilin = UIColor(hex: "#E1AD21")
static let uSAFABlue = UIColor(hex: "#004F98")
static let uSCCardinal = UIColor(hex: "#990000")
static let uSCGold = UIColor(hex: "#FFCC00")
static let universityOfTennesseeOrange = UIColor(hex: "#F77F00")
static let utahCrimson = UIColor(hex: "#D3003F")
static let vanDykeBrown = UIColor(hex: "#664228")
static let vanilla = UIColor(hex: "#F3E5AB")
static let vanillaIce = UIColor(hex: "#F38FA9")
static let vegasGold = UIColor(hex: "#C5B358")
static let venetianRed = UIColor(hex: "#C80815")
static let verdigris = UIColor(hex: "#43B3AE")
static let vermilion = UIColor(hex: "#E34234")
static let veronica = UIColor(hex: "#A020F0")
static let veryLightAzure = UIColor(hex: "#74BBFB")
static let veryLightBlue = UIColor(hex: "#6666FF")
static let veryLightMalachiteGreen = UIColor(hex: "#64E986")
static let veryLightTangelo = UIColor(hex: "#FFB077")
static let veryPaleOrange = UIColor(hex: "#FFDFBF")
static let veryPaleYellow = UIColor(hex: "#FFFFBF")
static let violet = UIColor(hex: "#8F00FF")
static let violetColorWheel = UIColor(hex: "#7F00FF")
static let violetRYB = UIColor(hex: "#8601AF")
static let violetWeb = UIColor(hex: "#EE82EE")
static let violetBlue = UIColor(hex: "#324AB2")
static let violetRed = UIColor(hex: "#F75394")
static let viridian = UIColor(hex: "#40826D")
static let viridianGreen = UIColor(hex: "#009698")
static let vistaBlue = UIColor(hex: "#7C9ED9")
static let vividAmber = UIColor(hex: "#CC9900")
static let vividAuburn = UIColor(hex: "#922724")
static let vividBurgundy = UIColor(hex: "#9F1D35")
static let vividCerise = UIColor(hex: "#DA1D81")
static let vividCerulean = UIColor(hex: "#00AAEE")
static let vividCrimson = UIColor(hex: "#CC0033")
static let vividGamboge = UIColor(hex: "#FF9900")
static let vividLimeGreen = UIColor(hex: "#A6D608")
static let vividMalachite = UIColor(hex: "#00CC33")
static let vividMulberry = UIColor(hex: "#B80CE3")
static let vividOrange = UIColor(hex: "#FF5F00")
static let vividOrangePeel = UIColor(hex: "#FFA000")
static let vividOrchid = UIColor(hex: "#CC00FF")
static let vividRaspberry = UIColor(hex: "#FF006C")
static let vividRed = UIColor(hex: "#F70D1A")
static let vividRedTangelo = UIColor(hex: "#DF6124")
static let vividSkyBlue = UIColor(hex: "#00CCFF")
static let vividTangelo = UIColor(hex: "#F07427")
static let vividTangerine = UIColor(hex: "#FFA089")
static let vividVermilion = UIColor(hex: "#E56024")
static let vividViolet = UIColor(hex: "#9F00FF")
static let vividYellow = UIColor(hex: "#FFE302")
static let volt = UIColor(hex: "#CEFF00")
static let wageningenGreen = UIColor(hex: "#34B233")
static let warmBlack = UIColor(hex: "#004242")
static let waterspout = UIColor(hex: "#A4F4F9")
static let weldonBlue = UIColor(hex: "#7C98AB")
static let wenge = UIColor(hex: "#645452")
static let wheat = UIColor(hex: "#F5DEB3")
static let white = UIColor(hex: "#FFFFFF")
static let whiteSmoke = UIColor(hex: "#F5F5F5")
static let wildBlueYonder = UIColor(hex: "#A2ADD0")
static let wildOrchid = UIColor(hex: "#D470A2")
static let wildStrawberry = UIColor(hex: "#FF43A4")
static let wildWatermelon = UIColor(hex: "#FC6C85")
static let willpowerOrange = UIColor(hex: "#FD5800")
static let windsorTan = UIColor(hex: "#A75502")
static let wine = UIColor(hex: "#722F37")
static let wineDregs = UIColor(hex: "#673147")
static let winterSky = UIColor(hex: "#FF007C")
static let winterWizard = UIColor(hex: "#A0E6FF")
static let wintergreenDream = UIColor(hex: "#56887D")
static let wisteria = UIColor(hex: "#C9A0DC")
static let woodBrown = UIColor(hex: "#C19A6B")
static let xanadu = UIColor(hex: "#738678")
static let yaleBlue = UIColor(hex: "#0F4D92")
static let yankeesBlue = UIColor(hex: "#1C2841")
static let yellow = UIColor(hex: "#FFFF00")
static let yellowCrayola = UIColor(hex: "#FCE883")
static let yellowMunsell = UIColor(hex: "#EFCC00")
static let yellowNCS = UIColor(hex: "#FFD300")
static let yellowPantone = UIColor(hex: "#FEDF00")
static let yellowProcess = UIColor(hex: "#FFEF00")
static let yellowRYB = UIColor(hex: "#FEFE33")
static let yellowGreen = UIColor(hex: "#9ACD32")
static let yellowOrange = UIColor(hex: "#FFAE42")
static let yellowRose = UIColor(hex: "#FFF000")
static let yellowSunshine = UIColor(hex: "#FFF700")
static let zaffre = UIColor(hex: "#0014A8")
static let zinnwalditeBrown = UIColor(hex: "#2C1608")
static let zomp = UIColor(hex: "#39A78E")
}
|
unlicense
|
b0afcda36eebccf701aad1e93c31d532
| 51.139362 | 107 | 0.670354 | 3.195058 | false | false | false | false |
iAlexander/Obminka
|
XtraLibraries/Core.data/Form.swift
|
5
|
15067
|
// Form.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// The delegate of the Eureka form.
public protocol FormDelegate : class {
func sectionsHaveBeenAdded(_ sections: [Section], at: IndexSet)
func sectionsHaveBeenRemoved(_ sections: [Section], at: IndexSet)
func sectionsHaveBeenReplaced(oldSections: [Section], newSections: [Section], at: IndexSet)
func rowsHaveBeenAdded(_ rows: [BaseRow], at: [IndexPath])
func rowsHaveBeenRemoved(_ rows: [BaseRow], at: [IndexPath])
func rowsHaveBeenReplaced(oldRows: [BaseRow], newRows: [BaseRow], at: [IndexPath])
func valueHasBeenChanged(for: BaseRow, oldValue: Any?, newValue: Any?)
}
// MARK: Form
/// The class representing the Eureka form.
public final class Form {
/// Defines the default options of the navigation accessory view.
public static var defaultNavigationOptions = RowNavigationOptions.Enabled.union(.SkipCanNotBecomeFirstResponderRow)
/// The default options that define when an inline row will be hidden. Applies only when `inlineRowHideOptions` is nil.
public static var defaultInlineRowHideOptions = InlineRowHideOptions.FirstResponderChanges.union(.AnotherInlineRowIsShown)
/// The options that define when an inline row will be hidden. If nil then `defaultInlineRowHideOptions` are used
public var inlineRowHideOptions: InlineRowHideOptions?
/// Which `UIReturnKeyType` should be used by default. Applies only when `keyboardReturnType` is nil.
public static var defaultKeyboardReturnType = KeyboardReturnTypeConfiguration()
/// Which `UIReturnKeyType` should be used in this form. If nil then `defaultKeyboardReturnType` is used
public var keyboardReturnType: KeyboardReturnTypeConfiguration?
/// This form's delegate
public weak var delegate: FormDelegate?
public init() {}
/**
Returns the row at the given indexPath
*/
public subscript(indexPath: IndexPath) -> BaseRow {
return self[indexPath.section][indexPath.row]
}
/**
Returns the row whose tag is passed as parameter. Uses a dictionary to get the row faster
*/
public func rowBy<T>(tag: String) -> RowOf<T>? where T: Equatable{
let row: BaseRow? = rowBy(tag: tag)
return row as? RowOf<T>
}
/**
Returns the row whose tag is passed as parameter. Uses a dictionary to get the row faster
*/
public func rowBy<Row>(tag: String) -> Row? where Row: RowType{
let row: BaseRow? = rowBy(tag: tag)
return row as? Row
}
/**
Returns the row whose tag is passed as parameter. Uses a dictionary to get the row faster
*/
public func rowBy(tag: String) -> BaseRow? {
return rowsByTag[tag]
}
/**
Returns the section whose tag is passed as parameter.
*/
public func sectionBy(tag: String) -> Section? {
return kvoWrapper._allSections.filter({ $0.tag == tag }).first
}
/**
Method used to get all the values of all the rows of the form. Only rows with tag are included.
- parameter includeHidden: If the values of hidden rows should be included.
- returns: A dictionary mapping the rows tag to its value. [tag: value]
*/
public func values(includeHidden: Bool = false) -> [String: Any?] {
if includeHidden {
return getValues(for: allRows.filter({ $0.tag != nil }))
.merging(getValues(for: allSections.filter({ $0 is MultivaluedSection && $0.tag != nil }) as? [MultivaluedSection]), uniquingKeysWith: {(_, new) in new })
}
return getValues(for: rows.filter({ $0.tag != nil }))
.merging(getValues(for: allSections.filter({ $0 is MultivaluedSection && $0.tag != nil }) as? [MultivaluedSection]), uniquingKeysWith: {(_, new) in new })
}
/**
Set values to the rows of this form
- parameter values: A dictionary mapping tag to value of the rows to be set. [tag: value]
*/
public func setValues(_ values: [String: Any?]) {
for (key, value) in values {
let row: BaseRow? = rowBy(tag: key)
row?.baseValue = value
}
}
/// The visible rows of this form
public var rows: [BaseRow] { return flatMap { $0 } }
/// All the rows of this form. Includes the hidden rows.
public var allRows: [BaseRow] { return kvoWrapper._allSections.map({ $0.kvoWrapper._allRows }).flatMap { $0 } }
/// All the sections of this form. Includes hidden sections.
public var allSections: [Section] { return kvoWrapper._allSections }
/**
* Hides all the inline rows of this form.
*/
public func hideInlineRows() {
for row in self.allRows {
if let inlineRow = row as? BaseInlineRowType {
inlineRow.collapseInlineRow()
}
}
}
// MARK: Private
var rowObservers = [String: [ConditionType: [Taggable]]]()
var rowsByTag = [String: BaseRow]()
var tagToValues = [String: Any]()
lazy var kvoWrapper: KVOWrapper = { [unowned self] in return KVOWrapper(form: self) }()
}
extension Form: Collection {
public var startIndex: Int { return 0 }
public var endIndex: Int { return kvoWrapper.sections.count }
}
extension Form: MutableCollection {
// MARK: MutableCollectionType
public subscript (_ position: Int) -> Section {
get { return kvoWrapper.sections[position] as! Section }
set {
if position > kvoWrapper.sections.count {
assertionFailure("Form: Index out of bounds")
}
if position < kvoWrapper.sections.count {
let oldSection = kvoWrapper.sections[position]
let oldSectionIndex = kvoWrapper._allSections.index(of: oldSection as! Section)!
// Remove the previous section from the form
kvoWrapper._allSections[oldSectionIndex].willBeRemovedFromForm()
kvoWrapper._allSections[oldSectionIndex] = newValue
} else {
kvoWrapper._allSections.append(newValue)
}
kvoWrapper.sections[position] = newValue
newValue.wasAddedTo(form: self)
}
}
public func index(after i: Int) -> Int {
return i+1 <= endIndex ? i+1 : endIndex
}
public func index(before i: Int) -> Int {
return i > startIndex ? i-1 : startIndex
}
public var last: Section? {
return reversed().first
}
}
extension Form : RangeReplaceableCollection {
// MARK: RangeReplaceableCollectionType
public func append(_ formSection: Section) {
kvoWrapper.sections.insert(formSection, at: kvoWrapper.sections.count)
kvoWrapper._allSections.append(formSection)
formSection.wasAddedTo(form: self)
}
public func append<S: Sequence>(contentsOf newElements: S) where S.Iterator.Element == Section {
kvoWrapper.sections.addObjects(from: newElements.map { $0 })
kvoWrapper._allSections.append(contentsOf: newElements)
for section in newElements {
section.wasAddedTo(form: self)
}
}
public func replaceSubrange<C: Collection>(_ subRange: Range<Int>, with newElements: C) where C.Iterator.Element == Section {
for i in subRange.lowerBound..<subRange.upperBound {
if let section = kvoWrapper.sections.object(at: i) as? Section {
section.willBeRemovedFromForm()
kvoWrapper._allSections.remove(at: kvoWrapper._allSections.index(of: section)!)
}
}
kvoWrapper.sections.replaceObjects(in: NSRange(location: subRange.lowerBound, length: subRange.upperBound - subRange.lowerBound),
withObjectsFrom: newElements.map { $0 })
kvoWrapper._allSections.insert(contentsOf: newElements, at: indexForInsertion(at: subRange.lowerBound))
for section in newElements {
section.wasAddedTo(form: self)
}
}
public func removeAll(keepingCapacity keepCapacity: Bool = false) {
// not doing anything with capacity
for section in kvoWrapper._allSections {
section.willBeRemovedFromForm()
}
kvoWrapper.sections.removeAllObjects()
kvoWrapper._allSections.removeAll()
}
private func indexForInsertion(at index: Int) -> Int {
guard index != 0 else { return 0 }
let row = kvoWrapper.sections[index-1]
if let i = kvoWrapper._allSections.index(of: row as! Section) {
return i + 1
}
return kvoWrapper._allSections.count
}
}
extension Form {
// MARK: Private Helpers
class KVOWrapper: NSObject {
@objc dynamic private var _sections = NSMutableArray()
var sections: NSMutableArray { return mutableArrayValue(forKey: "_sections") }
var _allSections = [Section]()
private weak var form: Form?
init(form: Form) {
self.form = form
super.init()
addObserver(self, forKeyPath: "_sections", options: NSKeyValueObservingOptions.new.union(.old), context:nil)
}
deinit {
removeObserver(self, forKeyPath: "_sections")
_sections.removeAllObjects()
_allSections.removeAll()
}
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let newSections = change?[NSKeyValueChangeKey.newKey] as? [Section] ?? []
let oldSections = change?[NSKeyValueChangeKey.oldKey] as? [Section] ?? []
guard let delegateValue = form?.delegate, let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKey.kindKey] else { return }
guard keyPathValue == "_sections" else { return }
switch (changeType as! NSNumber).uintValue {
case NSKeyValueChange.setting.rawValue:
let indexSet = change![NSKeyValueChangeKey.indexesKey] as? IndexSet ?? IndexSet(integer: 0)
delegateValue.sectionsHaveBeenAdded(newSections, at: indexSet)
case NSKeyValueChange.insertion.rawValue:
let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet
delegateValue.sectionsHaveBeenAdded(newSections, at: indexSet)
case NSKeyValueChange.removal.rawValue:
let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet
delegateValue.sectionsHaveBeenRemoved(oldSections, at: indexSet)
case NSKeyValueChange.replacement.rawValue:
let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet
delegateValue.sectionsHaveBeenReplaced(oldSections: oldSections, newSections: newSections, at: indexSet)
default:
assertionFailure()
}
}
}
func dictionaryValuesToEvaluatePredicate() -> [String: Any] {
return tagToValues
}
func addRowObservers(to taggable: Taggable, rowTags: [String], type: ConditionType) {
for rowTag in rowTags {
if rowObservers[rowTag] == nil {
rowObservers[rowTag] = Dictionary()
}
if let _ = rowObservers[rowTag]?[type] {
if !rowObservers[rowTag]![type]!.contains(where: { $0 === taggable }) {
rowObservers[rowTag]?[type]!.append(taggable)
}
} else {
rowObservers[rowTag]?[type] = [taggable]
}
}
}
func removeRowObservers(from taggable: Taggable, rowTags: [String], type: ConditionType) {
for rowTag in rowTags {
guard var arr = rowObservers[rowTag]?[type], let index = arr.index(where: { $0 === taggable }) else { continue }
arr.remove(at: index)
}
}
func nextRow(for row: BaseRow) -> BaseRow? {
let allRows = rows
guard let index = allRows.index(of: row) else { return nil }
guard index < allRows.count - 1 else { return nil }
return allRows[index + 1]
}
func previousRow(for row: BaseRow) -> BaseRow? {
let allRows = rows
guard let index = allRows.index(of: row) else { return nil }
guard index > 0 else { return nil }
return allRows[index - 1]
}
func hideSection(_ section: Section) {
kvoWrapper.sections.remove(section)
}
func showSection(_ section: Section) {
guard !kvoWrapper.sections.contains(section) else { return }
guard var index = kvoWrapper._allSections.index(of: section) else { return }
var formIndex = NSNotFound
while formIndex == NSNotFound && index > 0 {
index = index - 1
let previous = kvoWrapper._allSections[index]
formIndex = kvoWrapper.sections.index(of: previous)
}
kvoWrapper.sections.insert(section, at: formIndex == NSNotFound ? 0 : formIndex + 1 )
}
func getValues(for rows: [BaseRow]) -> [String: Any?] {
return rows.reduce([String: Any?]()) {
var result = $0
result[$1.tag!] = $1.baseValue
return result
}
}
func getValues(for multivaluedSections: [MultivaluedSection]?) -> [String: [Any?]] {
return multivaluedSections?.reduce([String: [Any?]]()) {
var result = $0
result[$1.tag!] = $1.values()
return result
} ?? [:]
}
}
extension Form {
@discardableResult
public func validate(includeHidden: Bool = false) -> [ValidationError] {
let rowsToValidate = includeHidden ? allRows : rows
return rowsToValidate.reduce([ValidationError]()) { res, row in
var res = res
res.append(contentsOf: row.validate())
return res
}
}
}
|
mit
|
25ae45ef26906a9144b3c21150c0b65e
| 38.236979 | 170 | 0.638681 | 4.802996 | false | false | false | false |
tardieu/swift
|
benchmark/single-source/ArrayOfGenericRef.swift
|
21
|
2206
|
//===--- ArrayOfGenericRef.swift ------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This benchmark tests creation and destruction of an array of enum
// and generic type bound to nontrivial types.
//
// For comparison, we always create three arrays of 10,000 words.
protocol Constructible {
associatedtype Element
init(e:Element)
}
class ConstructibleArray<T:Constructible> {
var array: [T]
init(_ e:T.Element) {
array = [T]()
array.reserveCapacity(10_000)
for _ in 0...10_000 {
array.append(T(e:e) as T)
}
}
}
class GenericRef<T> : Constructible {
typealias Element=T
var x: T
required init(e:T) { self.x = e }
}
// Reference to a POD class.
@inline(never)
func genPODRefArray() {
_ = ConstructibleArray<GenericRef<Int>>(3)
// should be a nop
}
class Dummy {}
// Reference to a reference. The nested reference is shared across elements.
@inline(never)
func genCommonRefArray() {
let d = Dummy()
_ = ConstructibleArray<GenericRef<Dummy>>(d)
// should be a nop
}
// Reuse the same enum value for each element.
class RefArray<T> {
var array: [T]
init(_ i:T, count:Int = 10_000) {
array = [T](repeating: i, count: count)
}
}
// enum holding a reference.
@inline(never)
func genRefEnumArray() {
let d = Dummy()
_ = RefArray<Dummy?>(d)
// should be a nop
}
struct GenericVal<T> : Constructible {
typealias Element=T
var x: T
init(e:T) { self.x = e }
}
// Struct holding a reference.
@inline(never)
func genRefStructArray() {
let d = Dummy()
_ = ConstructibleArray<GenericVal<Dummy>>(d)
// should be a nop
}
@inline(never)
public func run_ArrayOfGenericRef(_ N: Int) {
for _ in 0...N {
genPODRefArray()
genCommonRefArray()
genRefEnumArray()
genRefStructArray()
}
}
|
apache-2.0
|
ec6dfe37a7676ab9e086fbd59dbecf44
| 21.979167 | 80 | 0.635086 | 3.518341 | false | false | false | false |
tnantoka/AppBoard
|
AppBoard/Controllers/AppViewController.swift
|
1
|
2060
|
//
// AppViewController.swift
// AppBoard
//
// Created by Tatsuya Tobioka on 3/13/16.
// Copyright © 2016 Tatsuya Tobioka. All rights reserved.
//
import UIKit
import Symday
import QuickResponse
class AppViewController: UIViewController {
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var releasedLabel: UILabel!
@IBOutlet weak var descView: UITextView!
@IBOutlet weak var urlButton: UIButton!
var app: App!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
title = app.name
if let iconURL = NSURL(string: app.icon), data = NSData(contentsOfURL: iconURL) {
iconView.image = UIImage(data: data)
}
nameLabel.text = app.name
releasedLabel.text = Symday().format(app.releasedAt)
descView.text = app.desc
urlButton.setImage(QuickResponse(message: app.url).scaled(8.0).code, forState: .Normal)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func urlButtonDidTap(sender: AnyObject) {
guard let url = NSURL(string: app.url) else { return }
let alertController = UIAlertController(
title: NSLocalizedString("Open in Safari", comment: ""),
message: app.url,
preferredStyle: .Alert
)
alertController.addAction(
UIAlertAction(
title: NSLocalizedString("Open", comment: ""),
style: .Default,
handler: { _ in
UIApplication.sharedApplication().openURL(url)
}
)
)
alertController.addAction(
UIAlertAction(
title: NSLocalizedString("Cancel", comment: ""),
style: .Cancel,
handler: nil
)
)
presentViewController(alertController, animated: true, completion: nil)
}
}
|
mit
|
4df03ec3421809f805f31ef1aad785ba
| 28.414286 | 95 | 0.593492 | 5.009732 | false | false | false | false |
ingresse/ios-sdk
|
IngresseSDK/Model/PendingTransfer.swift
|
1
|
1413
|
//
// Copyright © 2017 Ingresse. All rights reserved.
//
public class PendingTransfer: NSObject, Decodable {
public var id: Int = 0
public var event: Event?
public var venue: Venue?
public var session: Session?
public var ticket: TransferTicket?
public var receivedFrom: Transfer?
public var sessions: [Session] = []
enum CodingKeys: String, CodingKey {
case id
case event
case venue
case session
case ticket
case receivedFrom
case sessions
}
enum SessionCodingKeys: String, CodingKey {
case data
}
public required init(from decoder: Decoder) throws {
guard let container = try? decoder.container(keyedBy: CodingKeys.self) else { return }
id = container.decodeKey(.id, ofType: Int.self)
event = container.safeDecodeKey(.event, to: Event.self)
venue = container.safeDecodeKey(.venue, to: Venue.self)
session = container.safeDecodeKey(.session, to: Session.self)
ticket = container.safeDecodeKey(.ticket, to: TransferTicket.self)
receivedFrom = container.safeDecodeKey(.receivedFrom, to: Transfer.self)
guard
let sessionData = try? container.nestedContainer(keyedBy: SessionCodingKeys.self, forKey: .sessions)
else { return }
sessions = sessionData.decodeKey(.data, ofType: [Session].self)
}
}
|
mit
|
367d3fdb7a82e0080f2732846584571e
| 31.090909 | 112 | 0.655099 | 4.511182 | false | false | false | false |
jonasman/TeslaSwift
|
Sources/TeslaSwift/TeslaSwift.swift
|
1
|
25878
|
//
// TeslaSwift.swift
// TeslaSwift
//
// Created by Joao Nunes on 04/03/16.
// Copyright © 2016 Joao Nunes. All rights reserved.
//
import Foundation
import os.log
public enum TeslaError: Error, Equatable {
case networkError(error: NSError)
case authenticationRequired
case authenticationFailed
case tokenRevoked
case noTokenToRefresh
case tokenRefreshFailed
case invalidOptionsForCommand
case failedToParseData
case failedToReloadVehicle
case internalError
}
let ErrorInfo = "ErrorInfo"
private var nullBody = ""
open class TeslaSwift {
open var debuggingEnabled = false
open fileprivate(set) var token: AuthToken?
open fileprivate(set) var email: String?
fileprivate var password: String?
public init() { }
}
extension TeslaSwift {
public var isAuthenticated: Bool {
return token != nil && (token?.isValid ?? false)
}
#if canImport(WebKit) && canImport(UIKit)
/**
Performs the authentication with the Tesla API for web logins
For MFA users, this is the only way to authenticate.
If the token expires, a token refresh will be done
- returns: A ViewController that your app needs to present. This ViewController will ask the user for his/her Tesla credentials, MFA code if set and then dismiss on successful authentication.
An async function that returns when the token as been retrieved
*/
public func authenticateWeb() -> (TeslaWebLoginViewController?, () async throws -> AuthToken) {
let codeRequest = AuthCodeRequest()
let endpoint = Endpoint.oAuth2Authorization(auth: codeRequest)
var urlComponents = URLComponents(string: endpoint.baseURL())
urlComponents?.path = endpoint.path
urlComponents?.queryItems = endpoint.queryParameters
guard let safeUrlComponents = urlComponents else {
func error() async throws -> AuthToken {
throw TeslaError.authenticationFailed
}
return (nil, error)
}
let teslaWebLoginViewController = TeslaWebLoginViewController(url: safeUrlComponents.url!)
func result() async throws -> AuthToken {
let url = try await teslaWebLoginViewController.result()
let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)
if let queryItems = urlComponents?.queryItems {
for queryItem in queryItems {
if queryItem.name == "code", let code = queryItem.value {
return try await self.getAuthenticationTokenForWeb(code: code)
}
}
}
throw TeslaError.authenticationFailed
}
return (teslaWebLoginViewController, result)
}
#endif
private func getAuthenticationTokenForWeb(code: String) async throws -> AuthToken {
let body = AuthTokenRequestWeb(code: code)
do {
let token: AuthToken = try await request(.oAuth2Token, body: body)
self.token = token
return token
} catch let error {
if case let TeslaError.networkError(error: internalError) = error {
if internalError.code == 302 || internalError.code == 403 {
return try await self.request(.oAuth2TokenCN, body: body)
} else if internalError.code == 401 {
throw TeslaError.authenticationFailed
} else {
throw error
}
} else {
throw error
}
}
}
/**
Performs the token refresh with the Tesla API for Web logins
- returns: The AuthToken.
*/
public func refreshWebToken() async throws -> AuthToken {
guard let token = self.token else { throw TeslaError.noTokenToRefresh }
let body = AuthTokenRequestWeb(grantType: .refreshToken, refreshToken: token.refreshToken)
do {
let authToken: AuthToken = try await request(.oAuth2Token, body: body)
self.token = authToken
return authToken
} catch let error {
if case let TeslaError.networkError(error: internalError) = error {
if internalError.code == 302 || internalError.code == 403 {
//Handle redirection for tesla.cn
return try await self.request(.oAuth2TokenCN, body: body)
} else if internalError.code == 401 {
throw TeslaError.tokenRefreshFailed
} else {
throw error
}
} else {
throw error
}
}
}
/**
Use this method to reuse a previous authentication token
This method is useful if your app wants to ask the user for credentials once and reuse the token skipping authentication
If the token is invalid a new authentication will be required
- parameter token: The previous token
- parameter email: Email is required for streaming
*/
public func reuse(token: AuthToken, email: String? = nil) {
self.token = token
self.email = email
}
/**
Revokes the stored token. Not working
- returns: The token revoke state.
*/
public func revokeWeb() async throws -> Bool {
guard let accessToken = self.token?.accessToken else {
cleanToken()
return false
}
_ = try await checkAuthentication()
self.cleanToken()
let response: BoolResponse = try await request(.oAuth2revoke(token: accessToken), body: nullBody)
return response.response
}
/**
Removes all the information related to the previous authentication
*/
public func logout() {
email = nil
password = nil
cleanToken()
#if canImport(WebKit) && canImport(UIKit)
TeslaWebLoginViewController.removeCookies()
#endif
}
/**
Fetchs the list of your vehicles including not yet delivered ones
- returns: An array of Vehicles.
*/
public func getVehicles() async throws -> [Vehicle] {
_ = try await checkAuthentication()
let response: ArrayResponse<Vehicle> = try await request(.vehicles, body: nullBody)
return response.response
}
/**
Fetchs the list of your products
- returns: An array of Products.
*/
public func getProducts() async throws -> [Product] {
_ = try await checkAuthentication()
let response: ArrayResponse<Product> = try await request(.products, body: nullBody)
return response.response
}
/**
Fetchs the summary of a vehicle
- returns: A Vehicle.
*/
public func getVehicle(_ vehicleID: String) async throws -> Vehicle {
_ = try await checkAuthentication()
let response: Response<Vehicle> = try await request(.vehicleSummary(vehicleID: vehicleID), body: nullBody)
return response.response
}
/**
Fetches the summary of a vehicle
- returns: A Vehicle.
*/
public func getVehicle(_ vehicle: Vehicle) async throws -> Vehicle {
return try await getVehicle(vehicle.id!)
}
/**
Fetches the vehicle data
- returns: A completion handler with all the data
*/
public func getAllData(_ vehicle: Vehicle) async throws -> VehicleExtended {
_ = try await checkAuthentication()
let vehicleID = vehicle.id!
let response: Response<VehicleExtended> = try await request(.allStates(vehicleID: vehicleID), body: nullBody)
return response.response
}
/**
Fetches the vehicle mobile access state
- returns: The mobile access state.
*/
public func getVehicleMobileAccessState(_ vehicle: Vehicle) async throws -> Bool {
_ = try await checkAuthentication()
let vehicleID = vehicle.id!
let response: BoolResponse = try await request(.mobileAccess(vehicleID: vehicleID), body: nullBody)
return response.response
}
/**
Fetches the vehicle charge state
- returns: The charge state.
*/
public func getVehicleChargeState(_ vehicle: Vehicle) async throws -> ChargeState {
_ = try await checkAuthentication()
let vehicleID = vehicle.id!
let response: Response<ChargeState> = try await request(.chargeState(vehicleID: vehicleID), body: nullBody)
return response.response
}
/**
Fetches the vehicle Climate state
- returns: The Climate state.
*/
public func getVehicleClimateState(_ vehicle: Vehicle) async throws -> ClimateState {
_ = try await checkAuthentication()
let vehicleID = vehicle.id!
let response: Response<ClimateState> = try await request(.climateState(vehicleID: vehicleID), body: nullBody)
return response.response
}
/**
Fetches the vehicle drive state
- returns: The drive state.
*/
public func getVehicleDriveState(_ vehicle: Vehicle) async throws -> DriveState {
_ = try await checkAuthentication()
let vehicleID = vehicle.id!
let response: Response<DriveState> = try await request(.driveState(vehicleID: vehicleID), body: nullBody)
return response.response
}
/**
Fetches the vehicle GUI Settings
- returns: The GUI Settings.
*/
public func getVehicleGuiSettings(_ vehicle: Vehicle) async throws -> GuiSettings {
_ = try await checkAuthentication()
let vehicleID = vehicle.id!
let response: Response<GuiSettings> = try await request(.guiSettings(vehicleID: vehicleID), body: nullBody)
return response.response
}
/**
Fetches the vehicle state
- returns: The vehicle state.
*/
public func getVehicleState(_ vehicle: Vehicle) async throws -> VehicleState {
_ = try await checkAuthentication()
let vehicleID = vehicle.id!
let response: Response<VehicleState> = try await request(.vehicleState(vehicleID: vehicleID), body: nullBody)
return response.response
}
/**
Fetches the vehicle config
- returns: The vehicle config
*/
public func getVehicleConfig(_ vehicle: Vehicle) async throws -> VehicleConfig {
_ = try await checkAuthentication()
let vehicleID = vehicle.id!
let response: Response<VehicleConfig> = try await request(.vehicleConfig(vehicleID: vehicleID), body: nullBody)
return response.response
}
/**
Fetches the nearby charging sites
- parameter vehicle: the vehicle to get nearby charging sites from
- returns: The nearby charging sites
*/
public func getNearbyChargingSites(_ vehicle: Vehicle) async throws -> NearbyChargingSites {
_ = try await checkAuthentication()
let vehicleID = vehicle.id!
let response: Response<NearbyChargingSites> = try await request(.nearbyChargingSites(vehicleID: vehicleID), body: nullBody)
return response.response
}
/**
Wakes up the vehicle
- returns: The current Vehicle
*/
public func wakeUp(_ vehicle: Vehicle) async throws -> Vehicle {
_ = try await checkAuthentication()
let vehicleID = vehicle.id!
let response: Response<Vehicle> = try await request(.wakeUp(vehicleID: vehicleID), body: nullBody)
return response.response
}
/**
Sends a command to the vehicle
- parameter vehicle: the vehicle that will receive the command
- parameter command: the command to send to the vehicle
- returns: A completion handler with the CommandResponse object containing the results of the command.
*/
public func sendCommandToVehicle(_ vehicle: Vehicle, command: VehicleCommand) async throws -> CommandResponse {
_ = try await checkAuthentication()
switch command {
case let .setMaxDefrost(on: state):
let body = MaxDefrostCommandOptions(state: state)
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
case let .triggerHomeLink(coordinates):
let body = HomeLinkCommandOptions(coordinates: coordinates)
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
case let .valetMode(valetActivated, pin):
let body = ValetCommandOptions(valetActivated: valetActivated, pin: pin)
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
case let .openTrunk(options):
let body = options
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
case let .shareToVehicle(address):
let body = address
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
case let .scheduledCharging(enable, time):
let body = ScheduledChargingCommandOptions(enable: enable, time: time)
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
case let .scheduledDeparture(body):
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
case let .chargeLimitPercentage(limit):
let body = ChargeLimitPercentageCommandOptions(limit: limit)
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
case let .setTemperature(driverTemperature, passengerTemperature):
let body = SetTemperatureCommandOptions(driverTemperature: driverTemperature, passengerTemperature: passengerTemperature)
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
case let .setSunRoof(state, percent):
let body = SetSunRoofCommandOptions(state: state, percent: percent)
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
case let .startVehicle(password):
let body = RemoteStartDriveCommandOptions(password: password)
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
case let .speedLimitSetLimit(speed):
let body = SetSpeedLimitOptions(limit: speed)
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
case let .speedLimitActivate(pin):
let body = SpeedLimitPinOptions(pin: pin)
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
case let .speedLimitDeactivate(pin):
let body = SpeedLimitPinOptions(pin: pin)
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
case let .speedLimitClearPin(pin):
let body = SpeedLimitPinOptions(pin: pin)
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
case let .setSeatHeater(seat, level):
let body = RemoteSeatHeaterRequestOptions(seat: seat, level: level)
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
case let .setSteeringWheelHeater(on):
let body = RemoteSteeringWheelHeaterRequestOptions(on: on)
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
case let .sentryMode(activated):
let body = SentryModeCommandOptions(activated: activated)
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
case let .windowControl(state):
let body = WindowControlCommandOptions(command: state)
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
case let .setCharging(amps):
let body = ChargeAmpsCommandOptions(amps: amps)
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
default:
let body = nullBody
return try await request(Endpoint.command(vehicleID: vehicle.id!, command: command), body: body)
}
}
/**
Fetchs the status of your energy site
- returns: The EnergySiteStatus
*/
public func getEnergySiteStatus(siteID: String) async throws -> EnergySiteStatus {
_ = try await checkAuthentication()
let response: Response<EnergySiteStatus> = try await request(.getEnergySiteStatus(siteID: siteID), body: nullBody)
return response.response
}
/**
Fetchs the live status of your energy site
- returns: A completion handler with an array of Products.
*/
public func getEnergySiteLiveStatus(siteID: String) async throws -> EnergySiteLiveStatus {
_ = try await checkAuthentication()
let response: Response<EnergySiteLiveStatus> = try await request(.getEnergySiteLiveStatus(siteID: siteID), body: nullBody)
return response.response
}
/**
Fetchs the info of your energy site
- returns: The EnergySiteInfo.
*/
public func getEnergySiteInfo(siteID: String) async throws -> EnergySiteInfo {
_ = try await checkAuthentication()
let response: Response<EnergySiteInfo> = try await request(.getEnergySiteInfo(siteID: siteID), body: nullBody)
return response.response
}
/**
Fetchs the history of your energy site
- returns: The EnergySiteHistory
*/
public func getEnergySiteHistory(siteID: String, period: EnergySiteHistory.Period) async throws -> EnergySiteHistory {
_ = try await checkAuthentication()
let response: Response<EnergySiteHistory> = try await request(.getEnergySiteHistory(siteID: siteID, period: period), body: nullBody)
return response.response
}
/**
Fetchs the status of your Powerwall battery
- returns: The BatteryStatus
*/
public func getBatteryStatus(batteryID: String) async throws -> BatteryStatus {
_ = try await checkAuthentication()
let response: Response<BatteryStatus> = try await request(.getBatteryStatus(batteryID: batteryID), body: nullBody)
return response.response
}
/**
Fetchs the data of your Powerwall battery
- returns: The BatteryData
*/
public func getBatteryData(batteryID: String) async throws -> BatteryData {
_ = try await checkAuthentication()
let response: Response<BatteryData> = try await request(.getBatteryData(batteryID: batteryID), body: nullBody)
return response.response
}
/**
Fetchs the history of your Powerwall battery
- returns: The BatteryPowerHistory
*/
public func getBatteryPowerHistory(batteryID: String) async throws -> BatteryPowerHistory {
_ = try await checkAuthentication()
let response: Response<BatteryPowerHistory> = try await request(.getBatteryPowerHistory(batteryID: batteryID), body: nullBody)
return response.response
}
}
extension TeslaSwift {
func checkToken() -> Bool {
if let token = self.token {
return token.isValid
} else {
return false
}
}
func cleanToken() {
token = nil
}
func checkAuthentication() async throws -> AuthToken {
guard let token = self.token else { throw TeslaError.authenticationRequired }
if checkToken() {
return token
} else {
if token.refreshToken != nil {
return try await refreshWebToken()
} else {
throw TeslaError.authenticationRequired
}
}
}
private func request<ReturnType: Decodable, BodyType: Encodable>(
_ endpoint: Endpoint, body: BodyType
) async throws -> ReturnType {
let request = prepareRequest(endpoint, body: body)
let debugEnabled = debuggingEnabled
let data: Data
let response: URLResponse
if #available(iOS 15.0, *) {
(data, response) = try await URLSession.shared.data(for: request)
} else {
(data, response) = try await withCheckedThrowingContinuation { continuation in
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data, let response = response {
continuation.resume(with: .success((data, response)))
} else {
continuation.resume(with: .failure(error ?? TeslaError.internalError))
}
}
}
}
guard let httpResponse = response as? HTTPURLResponse else { throw TeslaError.failedToParseData }
var responseString = "\nRESPONSE: \(String(describing: httpResponse.url))"
responseString += "\nSTATUS CODE: \(httpResponse.statusCode)"
if let headers = httpResponse.allHeaderFields as? [String: String] {
responseString += "\nHEADERS: [\n"
headers.forEach {(key: String, value: String) in
responseString += "\"\(key)\": \"\(value)\"\n"
}
responseString += "]"
}
logDebug(responseString, debuggingEnabled: debugEnabled)
if case 200..<300 = httpResponse.statusCode {
do {
let objectString = String.init(data: data, encoding: String.Encoding.utf8) ?? "No Body"
logDebug("RESPONSE BODY: \(objectString)\n", debuggingEnabled: debugEnabled)
let mapped = try teslaJSONDecoder.decode(ReturnType.self, from: data)
return mapped
} catch {
logDebug("ERROR: \(error)", debuggingEnabled: debugEnabled)
throw TeslaError.failedToParseData
}
} else {
let objectString = String.init(data: data, encoding: String.Encoding.utf8) ?? "No Body"
logDebug("RESPONSE BODY ERROR: \(objectString)\n", debuggingEnabled: debugEnabled)
if let wwwAuthenticate = httpResponse.allHeaderFields["Www-Authenticate"] as? String,
wwwAuthenticate.contains("invalid_token") {
throw TeslaError.tokenRevoked
} else if httpResponse.allHeaderFields["Www-Authenticate"] != nil, httpResponse.statusCode == 401 {
throw TeslaError.authenticationFailed
} else if let mapped = try? teslaJSONDecoder.decode(ErrorMessage.self, from: data) {
throw TeslaError.networkError(error: NSError(domain: "TeslaError", code: httpResponse.statusCode, userInfo: [ErrorInfo: mapped]))
} else {
throw TeslaError.networkError(error: NSError(domain: "TeslaError", code: httpResponse.statusCode, userInfo: nil))
}
}
}
func prepareRequest<BodyType: Encodable>(_ endpoint: Endpoint, body: BodyType) -> URLRequest {
var urlComponents = URLComponents(url: URL(string: endpoint.baseURL())!, resolvingAgainstBaseURL: true)
urlComponents?.path = endpoint.path
urlComponents?.queryItems = endpoint.queryParameters
var request = URLRequest(url: urlComponents!.url!)
request.httpMethod = endpoint.method
request.setValue("TeslaSwift", forHTTPHeaderField: "User-Agent")
if let token = self.token?.accessToken {
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
if let body = body as? String, body == nullBody {
// Shrug
} else {
request.httpBody = try? teslaJSONEncoder.encode(body)
request.setValue("application/json", forHTTPHeaderField: "content-type")
}
logDebug("\nREQUEST: \(request)", debuggingEnabled: debuggingEnabled)
logDebug("METHOD: \(request.httpMethod!)", debuggingEnabled: debuggingEnabled)
if let headers = request.allHTTPHeaderFields {
var headersString = "REQUEST HEADERS: [\n"
headers.forEach {(key: String, value: String) in
headersString += "\"\(key)\": \"\(value)\"\n"
}
headersString += "]"
logDebug(headersString, debuggingEnabled: debuggingEnabled)
}
if let body = body as? String, body != nullBody {
// Shrug
} else if let jsonString = body.jsonString {
logDebug("REQUEST BODY: \(jsonString)", debuggingEnabled: debuggingEnabled)
}
return request
}
}
func logDebug(_ format: String, debuggingEnabled: Bool) {
if debuggingEnabled {
print(format)
}
}
public let teslaJSONEncoder: JSONEncoder = {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
encoder.dateEncodingStrategy = .secondsSince1970
return encoder
}()
public let teslaJSONDecoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in
let container = try decoder.singleValueContainer()
if let dateDouble = try? container.decode(Double.self) {
return Date(timeIntervalSince1970: dateDouble)
} else {
let dateString = try container.decode(String.self)
let dateFormatter = ISO8601DateFormatter()
var date = dateFormatter.date(from: dateString)
guard let date = date else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Cannot decode date string \(dateString)")
}
return date
}
})
return decoder
}()
|
mit
|
15f539b6bf79e61669e13b5242823240
| 37.912782 | 196 | 0.643158 | 4.835015 | false | false | false | false |
apple/swift
|
test/SILOptimizer/Inputs/pre_specialized_module_layouts.swift
|
2
|
3343
|
@frozen
public struct SomeData {
public init() {}
}
public class SomeClass {
public init() {}
}
@_specialize(exported: true, where T == Int)
@_specialize(exported: true, where T == Double)
@_specialize(exported: true, where @_noMetadata T : _Class)
@_specialize(exported: true, availability: macOS 10.50, *; where T == SomeData)
public func publicPrespecialized<T>(_ t: T) {
}
@_specialize(exported: true, where T == Int)
@_specialize(exported: true, where @_noMetadata T : _Class)
@_specialize(exported: true, availability: macOS 10.50, *; where T == SomeData)
@inlinable
@inline(never)
public func publicPrespecialized2<T>(_ t: T) { }
@_specialize(exported: true, where T == Int)
@_specialize(exported: true, where @_noMetadata T : _Class)
@_specialize(exported: true, availability: macOS 10.50, *; where T == SomeData)
@inlinable
@inline(never)
public func publicPrespecializedThrows<T>(_ t: T) throws -> T { return t }
@_specialize(exported: true, where T == Int)
@_specialize(exported: true, where T == Double)
@_specialize(exported: true, where @_noMetadata T : _Class)
@_alwaysEmitIntoClient
@inline(never)
internal func internalEmitIntoClientPrespecialized<T>(_ t: T) {
}
@inlinable
public func useInternalEmitIntoClientPrespecialized<T>(_ t: T) {
internalEmitIntoClientPrespecialized(t)
}
@inlinable
public func publicInlineable<T>(_ t: T) {
}
public struct ResilientThing {
public init() {}
}
@usableFromInline
@frozen
internal struct InternalThing2<T> {
@usableFromInline
var x : T
@usableFromInline
init(_ t: T) {
x = t
}
@_specialize(exported: true, where T == Int)
@_specialize(exported: true, where @_noMetadata T : _Class)
@inlinable
func compute() -> T {
return x
}
@inlinable
var computedX : T {
@_specialize(exported: true, where T == Int)
@_specialize(exported: true, where @_noMetadata T : _Class)
get {
return x
}
}
@inlinable
var computedY : T {
@_specialize(exported: true, where T == Int)
@_specialize(exported: true, where @_noMetadata T : _Class)
get {
return x
}
@_specialize(exported: true, where T == Int)
@_specialize(exported: true, where @_noMetadata T : _Class)
set {
x = newValue
}
}
@inlinable
var computedZ : T {
@_specialize(exported: true, where T == Int)
@_specialize(exported: true, where @_noMetadata T : _Class)
_modify {
yield &x
}
@_specialize(exported: true, where T == Int)
@_specialize(exported: true, where @_noMetadata T : _Class)
_read {
yield x
}
}
@inlinable
subscript(_ i: Int) -> T {
@_specialize(exported: true, where T == Int)
@_specialize(exported: true, where @_noMetadata T : _Class)
get {
return x
}
@_specialize(exported: true, where T == Int)
@_specialize(exported: true, where @_noMetadata T : _Class)
set {
}
}
}
@inlinable
public func useInternalThing<T>(_ t: T) {
var x = InternalThing2(t)
print(x.compute())
print(x.computedX)
x.computedY = t
print(x.computedY)
x.computedZ = t
print(x.computedZ)
x[1] = t
print(x[1])
}
@_specialize(exported: true, where @_noMetadata T : _Class, @_noMetadata V : _Class)
public func publicPresepcializedMultipleIndirectResults<T, V>(_ t: T, _ v: V, _ x: Int64)-> (V, Int64, T) {
return (v, x, t)
}
|
apache-2.0
|
eb716e12b666d944aaf5b23e01092dc8
| 23.588235 | 107 | 0.650314 | 3.453512 | false | false | false | false |
powerytg/Accented
|
Accented/Core/API/Requests/ReportPhotoRequest.swift
|
1
|
1770
|
//
// ReportPhotoRequest.swift
// Accented
//
// Created by Tiangong You on 9/13/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
class ReportPhotoRequest: APIRequest {
private var photoId : String
private var reason : ReportReason
private var details : String?
init(photoId : String, reason : ReportReason, details : String?, success : SuccessAction?, failure : FailureAction?) {
self.photoId = photoId
self.reason = reason
self.details = details
super.init(success: success, failure: failure)
ignoreCache = true
url = "\(APIRequest.baseUrl)photos/\(photoId)/report"
parameters["reason"] = reason.rawValue
if let detailReason = details {
parameters["reason_details"] = detailReason
}
}
override func handleSuccess(data: Data, response: HTTPURLResponse?) {
super.handleSuccess(data: data, response: response)
let userInfo : [String : Any] = [RequestParameters.photoId : photoId,
RequestParameters.response : data]
NotificationCenter.default.post(name: APIEvents.didReportPhoto, object: nil, userInfo: userInfo)
if let success = successAction {
success()
}
}
override func handleFailure(_ error: Error) {
super.handleFailure(error)
let userInfo : [String : String] = [RequestParameters.errorMessage : error.localizedDescription]
NotificationCenter.default.post(name: APIEvents.failedReportPhoto, object: nil, userInfo: userInfo)
if let failure = failureAction {
failure(error.localizedDescription)
}
}
}
|
mit
|
6342dbf7774cb544260a72ea51a3323b
| 32.377358 | 122 | 0.624081 | 4.969101 | false | false | false | false |
jdkelley/Udacity-OnTheMap-ExampleApps
|
Playgrounds/GCD-CompleteReference/3-capture.playground/Contents.swift
|
1
|
6974
|
import UIKit
/*:
# Variable Capture
There's one last thing about functions and closure (we know by now they're the same thing) that we need to know.
It's very easy to understand and even seems very natural, but not all languages have this feature. When you add it to the *first-type* nature of Swift's functions and closures, it tyrns them into super powerful tools!
*/
/*:
## typealias
Before we get started, let's take a look at a concept that will be very useful in our examples of variable capture (actually, the fancy name for this is ```capture of lexical environment```. Feel free to drop this in any casual converstaion if you really want to look like a nerd 😃!).
An **alias** is a simple way of calling something or someone that has a complex or funny name.
For example, say you are a huge, professional wrestler and you want your name to scare the crap out of your opponent.
Do you seriously think *Terry Jean Bollette* will do? Of course not! That's why he goes by his typealias *Hulk Hogan*.
*/
//: Did you just call me Terry Jean?!
let terry = UIImage(named: "terry.jpg")
/*:
You're just starting your career as a pop singer, but your parents bestowed upon you the aristocratic sounding name of *Florian Cloud de Bounevialle Armstrong*.
It certainly sounds impressive, but your fans will have a hard time remembering it.
Better go by the ```typealias``` Dido.
*/
let florian = UIImage(named: "dido.jpg")
/*:
In Swift you can also give new names to existing types, and this is extremely useful when the original name is complex.
Something like being able to call *Issur Danielovitch Demsky* *Kirk Douglas*. Much better, don't you think so?
*/
/*:
Let's start with something simple. I don't like having to call a Integer an Int. Can we change that? Of course!
Just use the following template:
```typealias NewName = OldName```
*/
typealias Integer = Int
//: Now I can use ```Integer``` instead of ```Int``` whenever I feel like. It's all the same to the compiler!
let z: Integer = 42
/*:
This truly becomes useful when dealing with funky types, such as those of functions (and closures!)
For example, the type of a function that takes an Int and returns another one, would be
```(Int)->Int```
That can be confusing...
Let's call it a ```IntToInt```:
*/
typealias IntToInt = (Int) -> Int
/*:
Now let's create a typealias for a function that takes no parameters (Void) and returns an Int.
I'll call that an ```IntMaker```:
*/
typealias IntMaker = (Void) -> Int
/*:
## Variable capture, at last!
Now we can finally move on to the main course: how functions (and closures) capture variables.
Take a close look at the function ```makeCounter()``` below.
The code is pretty short, but it will require some close inspection to understand the first time.
*/
// Explain capture with function syntax, as it simpler
func makeCounter() -> IntMaker {
var n = 0
// Functions within functions?
// Yes we can!
func adder() -> Integer {
n = n + 1
return n
}
return adder
}
/*:
QUIZ:
What does it return?
### It returns a function
Yes it does, and there's nothing really special about that. Just like some machines create other machines, some functions can create other functions.
*/
let t101 = UIImage(named: "T101.jpg") // you start by making functions that make functions, then machines that make machines, and then...
/*:
### It contains a function defined within itself!
Yeah, don't panic, that's normal too. Just like you can have machines that contain other machines, and these are only visible from within the containing machine: think of your radio inside your car. No big deal.
It's actually useful to break down a long function by using *inner* functions that do part of the total job.
### adder can *access* the variable *n*!
That's the big deal.
* ```makeCounter``` defines a variable called ```n```, sets it to zero.
* Then, it defines a function called ```adder``` that updates the value of ```n``` and returns it.
* Last but not least, it returns the ```adder``` function.
The real magic is going on inside the ```adder```: **it can access all the variables defined before it!**
Not just n, put also z, which was defined way before.
It doesn't just *access* n, it actually *modifies* it! And here is where things could go very wrong...
Let's create 2 closures of type ```IntMaker``` by calling twice ```makeCounter``` and save them in two variables as below:
*/
let counter1 = makeCounter()
let counter2 = makeCounter()
/*:
#### Both ```counter1``` and ```counter2``` take no arguments and return an Int.
Think very carefully what the output should be:
QUIZ
*/
counter1()
counter1()
counter1()
/*:
#### And now, for the *grand finale*, what do you think this call will return?
QUIZ
Explain why you think it will return the value you expect
*/
counter2()
/*:
### Safe capture
The bottom line is that every time an ```adder``` is created, it takes a copy of all captured variables. Therefore, each closure has its own copy of the environment (the values of all variables that were captured).
This is done for safety and to keep you sane: the value of a variable will never change out of the blue, because, somewhere some closure decided to chnage it. Everybody has it's own copy.
*/
/*:
## Wrapping up!
We've learned quite a few things about Swift in this lesson, so let's recap:
* Functions and closures are the same thing. We just have 2 different sintaxes to express one same thing.
* Functions and closures are first-class citizens of our language: we can treat them like any other type.
* Functions and closure capture variables defined before the closure or function is defined.
It might not seem obvious to you at this point, but those 2 last features make Swift a far more powerful language. They are the base of a different style of programming called *Functional Programming*.
Its popularity is increasing a lot lately. However, you won't need it to finish the Nanodegree program or even land your first job, so don't worry, it's something that you can learn later if you want.
If you are interested, you might want to read any of these books:
* [To Mock a Mockingbird](http://www.amazon.com/To-Mock-Mockingbird-Other-Puzzles/dp/0192801422) by Raymond Smullyan: a gentle introduction to Functional Programming using birds as an analogy.
* [Functional Programming in Swift](https://www.objc.io/books/fpinswift/) by Chris Eidhof and Florian Kugler. This book assumes you already know Swift and teaches you how to use in a functional way.
## On to Grand Central Dispatch
In the meantime, we'll move to the next chapter which deals with *Grand Central Dispatch* (GCD). This is a library that allows us to create background tasks wiht great ease. This is vital to ship great Apps and avoid being rejected from the App Store.
Our newly gained knowledge of closures will make understanding GCD a breeze, so let's move on and learn it! 😉
*/
|
mit
|
968d7531931a944216ac0bf63d960a16
| 37.497238 | 284 | 0.734788 | 3.916807 | false | false | false | false |
D-Pointer/imperium-server
|
swift/Sources/imperium-server/Packets/TCP/JoinPacket.swift
|
1
|
3281
|
import NIO
import Foundation
class JoinPacket : Packet {
var debugDescription: String {
return "[Join game:\(gameId)]"
}
var type: PacketType
let gameId: UInt32
init?(buffer: ByteBuffer) {
self.type = .joinGamePacket
guard let gameId = buffer.getInteger(at: 4, endianness: .big, as: UInt32.self) else {
Log.error("failed to decode game id")
return nil
}
self.gameId = gameId
}
func handle (ctx: ChannelHandlerContext, state: ServerState) throws {
state.mutex.lock()
defer {
state.mutex.unlock()
}
let id = ObjectIdentifier(ctx.channel)
guard let player = state.players[id] else {
Log.error("no player found for id \(id)")
throw PacketException.playerNotFound
}
// player already has a game?
if player.game != nil {
// send "already has game"
var buffer = ctx.channel.allocator.buffer(capacity: 4)
buffer.writeInteger(UInt16(2))
buffer.writeInteger(PacketType.alreadyHasGamePacket.rawValue)
state.send(buffer: buffer, channel: ctx.channel)
return
}
// find the game
guard let game = state.games[gameId] else {
// send "invalid game"
var buffer = ctx.channel.allocator.buffer(capacity: 4)
buffer.writeInteger(UInt16(2))
buffer.writeInteger(PacketType.invalidGamePacket.rawValue)
state.send(buffer: buffer, channel: ctx.channel)
return
}
guard !game.started else {
// send "game full"
var buffer = ctx.channel.allocator.buffer(capacity: 4)
buffer.writeInteger(UInt16(2))
buffer.writeInteger(PacketType.gameFullPacket.rawValue)
state.send(buffer: buffer, channel: ctx.channel)
return
}
Log.info("\(player): joined game \(game)")
game.players.append(player)
player.game = game
game.joinTime = Date()
// send "game joined" to both players
sendGameJoined(to: game.players[0], opponent: game.players[1], state: state)
sendGameJoined(to: game.players[1], opponent: game.players[0], state: state)
// broadcast "game removed"
var buffer = ctx.channel.allocator.buffer(capacity: 8)
buffer.writeInteger(UInt16(6))
buffer.writeInteger(PacketType.gameRemovedPacket.rawValue)
buffer.writeInteger(UInt32(game.id))
state.send(buffer: buffer, channels: state.players.map{ (key, value) in
return value.channel
})
}
private func sendGameJoined(to player: Player, opponent: Player, state: ServerState) {
let nameBytes: [UInt8] = Array(opponent.name.utf8)
let length = 2 + 4 + 2 + nameBytes.count
var buffer = player.channel.allocator.buffer(capacity: 2 + length)
buffer.writeInteger(UInt16(length))
buffer.writeInteger(PacketType.gameJoinedPacket.rawValue)
buffer.writeInteger(player.id)
buffer.writeInteger(UInt16(nameBytes.count))
buffer.writeBytes(nameBytes)
state.send(buffer: buffer, channel: player.channel)
}
}
|
gpl-2.0
|
0e2d57c745b296f1b870f5bf8dd88e58
| 31.485149 | 93 | 0.608961 | 4.317105 | false | false | false | false |
KaiCode2/swift-corelibs-foundation
|
Foundation/NSXMLNode.swift
|
1
|
30833
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//import libxml2
import CoreFoundation
/*!
@typedef NSXMLNodeKind
*/
public enum NSXMLNodeKind : UInt {
case InvalidKind
case DocumentKind
case ElementKind
case AttributeKind
case NamespaceKind
case ProcessingInstructionKind
case CommentKind
case TextKind
case DTDKind
case EntityDeclarationKind
case AttributeDeclarationKind
case ElementDeclarationKind
case NotationDeclarationKind
}
// initWithKind options
// NSXMLNodeOptionsNone
// NSXMLNodePreserveAll
// NSXMLNodePreserveNamespaceOrder
// NSXMLNodePreserveAttributeOrder
// NSXMLNodePreserveEntities
// NSXMLNodePreservePrefixes
// NSXMLNodeIsCDATA
// NSXMLNodeExpandEmptyElement
// NSXMLNodeCompactEmptyElement
// NSXMLNodeUseSingleQuotes
// NSXMLNodeUseDoubleQuotes
// Output options
// NSXMLNodePrettyPrint
/*!
@class NSXMLNode
@abstract The basic unit of an XML document.
*/
public class NSXMLNode : NSObject, NSCopying {
public override func copy() -> AnyObject {
return copyWithZone(nil)
}
internal let _xmlNode: _CFXMLNodePtr
public func copyWithZone(_ zone: NSZone) -> AnyObject {
let newNode = _CFXMLCopyNode(_xmlNode, true)
return NSXMLNode._objectNodeForNode(newNode)
}
/*!
@method initWithKind:
@abstract Invokes @link initWithKind:options: @/link with options set to NSXMLNodeOptionsNone
*/
public convenience init(kind: NSXMLNodeKind) {
self.init(kind: kind, options: NSXMLNodeOptionsNone)
}
/*!
@method initWithKind:options:
@abstract Inits a node with fidelity options as description NSXMLNodeOptions.h
*/
public init(kind: NSXMLNodeKind, options: Int) {
switch kind {
case .DocumentKind:
let docPtr = _CFXMLNewDoc("1.0")
_CFXMLDocSetStandalone(docPtr, false) // same default as on Darwin
_xmlNode = _CFXMLNodePtr(docPtr)
case .ElementKind:
_xmlNode = _CFXMLNewNode(nil, "")
case .AttributeKind:
_xmlNode = _CFXMLNodePtr(_CFXMLNewProperty(nil, "", ""))
case .DTDKind:
_xmlNode = _CFXMLNewDTD(nil, "", "", "")
default:
fatalError("invalid node kind for this initializer")
}
super.init()
let unmanaged = Unmanaged<NSXMLNode>.passUnretained(self)
let ptr = unmanaged.toOpaque()
_CFXMLNodeSetPrivateData(_xmlNode, ptr)
}
/*!
@method document:
@abstract Returns an empty document.
*/
public class func document() -> AnyObject {
return NSXMLDocument(rootElement: nil)
}
/*!
@method documentWithRootElement:
@abstract Returns a document
@param element The document's root node.
*/
public class func documentWithRootElement(_ element: NSXMLElement) -> AnyObject {
return NSXMLDocument(rootElement: element)
}
/*!
@method elementWithName:
@abstract Returns an element <tt><name></name></tt>.
*/
public class func elementWithName(_ name: String) -> AnyObject {
return NSXMLElement(name: name)
}
/*!
@method elementWithName:URI:
@abstract Returns an element whose full QName is specified.
*/
public class func elementWithName(_ name: String, URI: String) -> AnyObject {
return NSXMLElement(name: name, URI: URI)
}
/*!
@method elementWithName:stringValue:
@abstract Returns an element with a single text node child <tt><name>string</name></tt>.
*/
public class func elementWithName(_ name: String, stringValue string: String) -> AnyObject {
return NSXMLElement(name: name, stringValue: string)
}
/*!
@method elementWithName:children:attributes:
@abstract Returns an element children and attributes <tt><name attr1="foo" attr2="bar"><-- child1 -->child2</name></tt>.
*/
public class func elementWithName(_ name: String, children: [NSXMLNode]?, attributes: [NSXMLNode]?) -> AnyObject {
let element = NSXMLElement(name: name)
element.setChildren(children)
element.attributes = attributes
return element
}
/*!
@method attributeWithName:stringValue:
@abstract Returns an attribute <tt>name="stringValue"</tt>.
*/
public class func attributeWithName(_ name: String, stringValue: String) -> AnyObject {
let attribute = _CFXMLNewProperty(nil, name, stringValue)
return NSXMLNode(ptr: attribute)
}
/*!
@method attributeWithLocalName:URI:stringValue:
@abstract Returns an attribute whose full QName is specified.
*/
public class func attributeWithName(_ name: String, URI: String, stringValue: String) -> AnyObject {
let attribute = NSXMLNode.attributeWithName(name, stringValue: stringValue) as! NSXMLNode
// attribute.URI = URI
return attribute
}
/*!
@method namespaceWithName:stringValue:
@abstract Returns a namespace <tt>xmlns:name="stringValue"</tt>.
*/
public class func namespaceWithName(_ name: String, stringValue: String) -> AnyObject { NSUnimplemented() }
/*!
@method processingInstructionWithName:stringValue:
@abstract Returns a processing instruction <tt><?name stringValue></tt>.
*/
public class func processingInstructionWithName(_ name: String, stringValue: String) -> AnyObject {
let node = _CFXMLNewProcessingInstruction(name, stringValue)
return NSXMLNode(ptr: node)
}
/*!
@method commentWithStringValue:
@abstract Returns a comment <tt><--stringValue--></tt>.
*/
public class func commentWithStringValue(_ stringValue: String) -> AnyObject {
let node = _CFXMLNewComment(stringValue)
return NSXMLNode(ptr: node)
}
/*!
@method textWithStringValue:
@abstract Returns a text node.
*/
public class func textWithStringValue(_ stringValue: String) -> AnyObject {
let node = _CFXMLNewTextNode(stringValue)
return NSXMLNode(ptr: node)
}
/*!
@method DTDNodeWithXMLString:
@abstract Returns an element, attribute, entity, or notation DTD node based on the full XML string.
*/
public class func DTDNodeWithXMLString(_ string: String) -> AnyObject? {
guard let node = _CFXMLParseDTDNode(string) else { return nil }
return NSXMLDTDNode(ptr: node)
}
/*!
@method kind
@abstract Returns an element, attribute, entity, or notation DTD node based on the full XML string.
*/
public var kind: NSXMLNodeKind {
switch _CFXMLNodeGetType(_xmlNode) {
case _kCFXMLTypeElement:
return .ElementKind
case _kCFXMLTypeAttribute:
return .AttributeKind
case _kCFXMLTypeDocument:
return .DocumentKind
case _kCFXMLTypeDTD:
return .DTDKind
case _kCFXMLDTDNodeTypeElement:
return .ElementDeclarationKind
case _kCFXMLDTDNodeTypeEntity:
return .EntityDeclarationKind
case _kCFXMLDTDNodeTypeNotation:
return .NotationDeclarationKind
case _kCFXMLDTDNodeTypeAttribute:
return .AttributeDeclarationKind
default:
return .InvalidKind
}
} //primitive
/*!
@method name
@abstract Sets the nodes name. Applicable for element, attribute, namespace, processing-instruction, document type declaration, element declaration, attribute declaration, entity declaration, and notation declaration.
*/
public var name: String? {
get {
return String(cString: _CFXMLNodeGetName(_xmlNode))
}
set {
if let newName = newValue {
_CFXMLNodeSetName(_xmlNode, newName)
} else {
_CFXMLNodeSetName(_xmlNode, "")
}
}
}
private var _objectValue: AnyObject? = nil
/*!
@method objectValue
@abstract Sets the content of the node. Setting the objectValue removes all existing children including processing instructions and comments. Setting the object value on an element creates a single text node child.
*/
public var objectValue: AnyObject? {
get {
if let value = _objectValue {
return value
} else {
return stringValue?._bridgeToObject()
}
}
set {
_objectValue = newValue
if let describableValue = newValue as? CustomStringConvertible {
stringValue = "\(describableValue.description)"
} else if let value = newValue {
stringValue = "\(value)"
} else {
stringValue = nil
}
}
}//primitive
/*!
@method stringValue:
@abstract Sets the content of the node. Setting the stringValue removes all existing children including processing instructions and comments. Setting the string value on an element creates a single text node child. The getter returns the string value of the node, which may be either its content or child text nodes, depending on the type of node. Elements are recursed and text nodes concatenated in document order with no intervening spaces.
*/
public var stringValue: String? {
get {
switch kind {
case .EntityDeclarationKind:
return _CFXMLGetEntityContent(_CFXMLEntityPtr(_xmlNode))?._swiftObject
default:
return _CFXMLNodeGetContent(_xmlNode)?._swiftObject
}
}
set {
_removeAllChildNodesExceptAttributes() // in case anyone is holding a reference to any of these children we're about to destroy
if let string = newValue {
let newContent = _CFXMLEncodeEntities(_CFXMLNodeGetDocument(_xmlNode), string)?._swiftObject ?? ""
_CFXMLNodeSetContent(_xmlNode, newContent)
} else {
_CFXMLNodeSetContent(_xmlNode, nil)
}
}
}
private func _removeAllChildNodesExceptAttributes() {
for node in _childNodes {
if node.kind != NSXMLNodeKind.AttributeKind {
_CFXMLUnlinkNode(node._xmlNode)
_childNodes.remove(node)
}
}
}
internal func _removeAllChildren() {
var nextChild = _CFXMLNodeGetFirstChild(_xmlNode)
while let child = nextChild {
_CFXMLUnlinkNode(child)
nextChild = _CFXMLNodeGetNextSibling(child)
}
_childNodes.removeAll(keepingCapacity: true)
}
/*!
@method setStringValue:resolvingEntities:
@abstract Sets the content as with @link setStringValue: @/link, but when "resolve" is true, character references, predefined entities and user entities available in the document's dtd are resolved. Entities not available in the dtd remain in their entity form.
*/
public func setStringValue(_ string: String, resolvingEntities resolve: Bool) {
guard resolve else {
stringValue = string
return
}
_removeAllChildNodesExceptAttributes()
var entities: [(Range<Int>, String)] = []
var entityChars: [Character] = []
var inEntity = false
var startIndex = 0
for (index, char) in string.characters.enumerated() {
if char == "&" {
inEntity = true
startIndex = index
continue
}
if char == ";" && inEntity {
inEntity = false
let min = startIndex
let max = index + 1
entities.append((min..<max, String(entityChars)))
startIndex = 0
entityChars.removeAll()
}
if inEntity {
entityChars.append(char)
}
}
var result: [Character] = Array(string.characters)
let doc = _CFXMLNodeGetDocument(_xmlNode)!
for (range, entity) in entities {
var entityPtr = _CFXMLGetDocEntity(doc, entity)
if entityPtr == nil {
entityPtr = _CFXMLGetDTDEntity(doc, entity)
}
if entityPtr == nil {
entityPtr = _CFXMLGetParameterEntity(doc, entity)
}
if let validEntity = entityPtr {
let replacement = _CFXMLGetEntityContent(validEntity)?._swiftObject ?? ""
result.replaceSubrange(range, with: replacement.characters)
} else {
result.replaceSubrange(range, with: []) // This appears to be how Darwin Foundation does it
}
}
stringValue = String(result)
} //primitive
/*!
@method index
@abstract A node's index amongst its siblings.
*/
public var index: Int {
if let siblings = self.parent?.children,
let index = siblings.index(of: self) {
return index
}
return 0
} //primitive
/*!
@method level
@abstract The depth of the node within the tree. Documents and standalone nodes are level 0.
*/
public var level: Int {
var result = 0
var nextParent = _CFXMLNodeGetParent(_xmlNode)
while let parent = nextParent {
result += 1
nextParent = _CFXMLNodeGetParent(parent)
}
return result
}
/*!
@method rootDocument
@abstract The encompassing document or nil.
*/
public var rootDocument: NSXMLDocument? {
guard let doc = _CFXMLNodeGetDocument(_xmlNode) else { return nil }
return NSXMLNode._objectNodeForNode(_CFXMLNodePtr(doc)) as? NSXMLDocument
}
/*!
@method parent
@abstract The parent of this node. Documents and standalone Nodes have a nil parent; there is not a 1-to-1 relationship between parent and children, eg a namespace cannot be a child but has a parent element.
*/
/*@NSCopying*/ public var parent: NSXMLNode? {
guard let parentPtr = _CFXMLNodeGetParent(_xmlNode) else { return nil }
return NSXMLNode._objectNodeForNode(parentPtr)
} //primitive
/*!
@method childCount
@abstract The amount of children, relevant for documents, elements, and document type declarations. Use this instead of [[self children] count].
*/
public var childCount: Int {
return _CFXMLNodeGetElementChildCount(_xmlNode)
} //primitive
/*!
@method children
@abstract An immutable array of child nodes. Relevant for documents, elements, and document type declarations.
*/
public var children: [NSXMLNode]? {
switch kind {
case .DocumentKind:
fallthrough
case .ElementKind:
fallthrough
case .DTDKind:
return Array<NSXMLNode>(self as NSXMLNode)
default:
return nil
}
} //primitive
/*!
@method childAtIndex:
@abstract Returns the child node at a particular index.
*/
public func childAtIndex(_ index: Int) -> NSXMLNode? {
precondition(index >= 0)
precondition(index < childCount)
return self[self.index(startIndex, offsetBy: index)]
} //primitive
/*!
@method previousSibling:
@abstract Returns the previous sibling, or nil if there isn't one.
*/
/*@NSCopying*/ public var previousSibling: NSXMLNode? {
guard let prev = _CFXMLNodeGetPrevSibling(_xmlNode) else { return nil }
return NSXMLNode._objectNodeForNode(prev)
}
/*!
@method nextSibling:
@abstract Returns the next sibling, or nil if there isn't one.
*/
/*@NSCopying*/ public var nextSibling: NSXMLNode? {
guard let next = _CFXMLNodeGetNextSibling(_xmlNode) else { return nil }
return NSXMLNode._objectNodeForNode(next)
}
/*!
@method previousNode:
@abstract Returns the previous node in document order. This can be used to walk the tree backwards.
*/
/*@NSCopying*/ public var previousNode: NSXMLNode? {
if let previousSibling = self.previousSibling {
if let lastChild = _CFXMLNodeGetLastChild(previousSibling._xmlNode) {
return NSXMLNode._objectNodeForNode(lastChild)
} else {
return previousSibling
}
} else if let parent = self.parent {
return parent
} else {
return nil
}
}
/*!
@method nextNode:
@abstract Returns the next node in document order. This can be used to walk the tree forwards.
*/
/*@NSCopying*/ public var nextNode: NSXMLNode? {
if let children = _CFXMLNodeGetFirstChild(_xmlNode) {
return NSXMLNode._objectNodeForNode(children)
} else if let next = nextSibling {
return next
} else if let parent = self.parent {
return parent.nextSibling
} else {
return nil
}
}
/*!
@method detach:
@abstract Detaches this node from its parent.
*/
public func detach() {
guard let parentPtr = _CFXMLNodeGetParent(_xmlNode) else { return }
_CFXMLUnlinkNode(_xmlNode)
guard let parentNodePtr = _CFXMLNodeGetPrivateData(parentPtr) else { return }
let parent = Unmanaged<NSXMLNode>.fromOpaque(parentNodePtr).takeUnretainedValue()
parent._childNodes.remove(self)
} //primitive
/*!
@method XPath
@abstract Returns the XPath to this node, for example foo/bar[2]/baz.
*/
public var XPath: String? {
guard _CFXMLNodeGetDocument(_xmlNode) != nil else { return nil }
var pathComponents: [String?] = []
var parent = _CFXMLNodeGetParent(_xmlNode)
if parent != nil {
let parentObj = NSXMLNode._objectNodeForNode(parent!)
let siblingsWithSameName = parentObj.filter { $0.name == self.name }
if siblingsWithSameName.count > 1 {
guard let index = siblingsWithSameName.index(of: self) else { return nil }
pathComponents.append("\(self.name ?? "")[\(index + 1)]")
} else {
pathComponents.append(self.name)
}
} else {
return self.name
}
while true {
if let parentNode = _CFXMLNodeGetParent(parent!) {
let grandparent = NSXMLNode._objectNodeForNode(parentNode)
let possibleParentNodes = grandparent.filter { $0.name == self.parent?.name }
let count = possibleParentNodes.reduce(0) {
return $0.0 + 1
}
if count <= 1 {
pathComponents.append(NSXMLNode._objectNodeForNode(parent!).name)
} else {
var parentNumber = 1
for possibleParent in possibleParentNodes {
if possibleParent == self.parent {
break
}
parentNumber += 1
}
pathComponents.append("\(self.parent?.name ?? "")[\(parentNumber)]")
}
parent = _CFXMLNodeGetParent(parent!)
} else {
pathComponents.append(NSXMLNode._objectNodeForNode(parent!).name)
break
}
}
return pathComponents.reversed().flatMap({ return $0 }).joined(separator: "/")
}
/*!
@method localName
@abstract Returns the local name bar if this attribute or element's name is foo:bar
*/
public var localName: String? {
return _CFXMLNodeLocalName(_xmlNode)?._swiftObject
} //primitive
/*!
@method prefix
@abstract Returns the prefix foo if this attribute or element's name if foo:bar
*/
public var prefix: String? {
return _CFXMLNodePrefix(_xmlNode)?._swiftObject
} //primitive
/*!
@method URI
@abstract Set the URI of this element, attribute, or document. For documents it is the URI of document origin. Getter returns the URI of this element, attribute, or document. For documents it is the URI of document origin and is automatically set when using initWithContentsOfURL.
*/
public var URI: String? { //primitive
get {
return _CFXMLNodeURI(_xmlNode)?._swiftObject
}
set {
if let URI = newValue {
_CFXMLNodeSetURI(_xmlNode, URI)
} else {
_CFXMLNodeSetURI(_xmlNode, nil)
}
}
}
/*!
@method localNameForName:
@abstract Returns the local name bar in foo:bar.
*/
public class func localNameForName(_ name: String) -> String {
// return name.withCString {
// var length: Int32 = 0
// let result = xmlSplitQName3(UnsafePointer<xmlChar>($0), &length)
// return String.fromCString(UnsafePointer<CChar>(result)) ?? ""
// }
NSUnimplemented()
}
/*!
@method localNameForName:
@abstract Returns the prefix foo in the name foo:bar.
*/
public class func prefixForName(_ name: String) -> String? {
// return name.withCString {
// var result: UnsafeMutablePointer<xmlChar> = nil
// let unused = xmlSplitQName2(UnsafePointer<xmlChar>($0), &result)
// defer {
// xmlFree(result)
// xmlFree(UnsafeMutablePointer<xmlChar>(unused))
// }
// return String.fromCString(UnsafePointer<CChar>(result))
// }
NSUnimplemented()
}
/*!
@method predefinedNamespaceForPrefix:
@abstract Returns the namespace belonging to one of the predefined namespaces xml, xs, or xsi
*/
public class func predefinedNamespaceForPrefix(_ name: String) -> NSXMLNode? { NSUnimplemented() }
/*!
@method description
@abstract Used for debugging. May give more information than XMLString.
*/
public override var description: String {
return XMLString
}
/*!
@method XMLString
@abstract The representation of this node as it would appear in an XML document.
*/
public var XMLString: String {
return XMLStringWithOptions(NSXMLNodeOptionsNone)
}
/*!
@method XMLStringWithOptions:
@abstract The representation of this node as it would appear in an XML document, with various output options available.
*/
public func XMLStringWithOptions(_ options: Int) -> String {
return _CFXMLStringWithOptions(_xmlNode, UInt32(options))._swiftObject
}
/*!
@method canonicalXMLStringPreservingComments:
@abstract W3 canonical form (http://www.w3.org/TR/xml-c14n). The input option NSXMLNodePreserveWhitespace should be set for true canonical form.
*/
public func canonicalXMLStringPreservingComments(_ comments: Bool) -> String { NSUnimplemented() }
/*!
@method nodesForXPath:error:
@abstract Returns the nodes resulting from applying an XPath to this node using the node as the context item ("."). normalizeAdjacentTextNodesPreservingCDATA:NO should be called if there are adjacent text nodes since they are not allowed under the XPath/XQuery Data Model.
@returns An array whose elements are a kind of NSXMLNode.
*/
public func nodesForXPath(_ xpath: String) throws -> [NSXMLNode] {
guard let nodes = _CFXMLNodesForXPath(_xmlNode, xpath) else {
NSUnimplemented()
}
var result: [NSXMLNode] = []
for i in 0..<CFArrayGetCount(nodes) {
let nodePtr = CFArrayGetValueAtIndex(nodes, i)!
result.append(NSXMLNode._objectNodeForNode(_CFXMLNodePtr(nodePtr)))
}
return result
}
/*!
@method objectsForXQuery:constants:error:
@abstract Returns the objects resulting from applying an XQuery to this node using the node as the context item ("."). Constants are a name-value dictionary for constants declared "external" in the query. normalizeAdjacentTextNodesPreservingCDATA:NO should be called if there are adjacent text nodes since they are not allowed under the XPath/XQuery Data Model.
@returns An array whose elements are kinds of NSArray, NSData, NSDate, NSNumber, NSString, NSURL, or NSXMLNode.
*/
public func objectsForXQuery(_ xquery: String, constants: [String : AnyObject]?) throws -> [AnyObject] { NSUnimplemented() }
public func objectsForXQuery(_ xquery: String) throws -> [AnyObject] { NSUnimplemented() }
internal var _childNodes: Set<NSXMLNode> = []
deinit {
for node in _childNodes {
node.detach()
}
switch kind {
case .DocumentKind:
_CFXMLFreeDocument(_CFXMLDocPtr(_xmlNode))
case .DTDKind:
_CFXMLFreeDTD(_CFXMLDTDPtr(_xmlNode))
case .AttributeKind:
_CFXMLFreeProperty(_xmlNode)
default:
_CFXMLFreeNode(_xmlNode)
}
}
internal init(ptr: _CFXMLNodePtr) {
precondition(_CFXMLNodeGetPrivateData(ptr) == nil, "Only one NSXMLNode per xmlNodePtr allowed")
_xmlNode = ptr
super.init()
if let parent = _CFXMLNodeGetParent(_xmlNode) {
let parentNode = NSXMLNode._objectNodeForNode(parent)
parentNode._childNodes.insert(self)
}
let unmanaged = Unmanaged<NSXMLNode>.passUnretained(self)
_CFXMLNodeSetPrivateData(_xmlNode, unmanaged.toOpaque())
}
internal class func _objectNodeForNode(_ node: _CFXMLNodePtr) -> NSXMLNode {
switch _CFXMLNodeGetType(node) {
case _kCFXMLTypeElement:
return NSXMLElement._objectNodeForNode(node)
case _kCFXMLTypeDocument:
return NSXMLDocument._objectNodeForNode(node)
case _kCFXMLTypeDTD:
return NSXMLDTD._objectNodeForNode(node)
case _kCFXMLDTDNodeTypeEntity:
fallthrough
case _kCFXMLDTDNodeTypeElement:
fallthrough
case _kCFXMLDTDNodeTypeNotation:
fallthrough
case _kCFXMLDTDNodeTypeAttribute:
return NSXMLDTDNode._objectNodeForNode(node)
default:
if let _private = _CFXMLNodeGetPrivateData(node) {
let unmanaged = Unmanaged<NSXMLNode>.fromOpaque(_private)
return unmanaged.takeUnretainedValue()
}
return NSXMLNode(ptr: node)
}
}
// libxml2 believes any node can have children, though NSXMLNode disagrees.
// Nevertheless, this belongs here so that NSXMLElement and NSXMLDocument can share
// the same implementation.
internal func _insertChild(_ child: NSXMLNode, atIndex index: Int) {
precondition(index >= 0)
precondition(index <= childCount)
precondition(child.parent == nil)
_childNodes.insert(child)
if index == 0 {
let first = _CFXMLNodeGetFirstChild(_xmlNode)!
_CFXMLNodeAddPrevSibling(first, child._xmlNode)
} else {
let currChild = childAtIndex(index - 1)!._xmlNode
_CFXMLNodeAddNextSibling(currChild, child._xmlNode)
}
} //primitive
// see above
internal func _insertChildren(_ children: [NSXMLNode], atIndex index: Int) {
for (childIndex, node) in children.enumerated() {
_insertChild(node, atIndex: index + childIndex)
}
}
/*!
@method removeChildAtIndex:atIndex:
@abstract Removes a child at a particular index.
*/
// See above!
internal func _removeChildAtIndex(_ index: Int) {
guard let child = childAtIndex(index) else {
fatalError("index out of bounds")
}
_childNodes.remove(child)
_CFXMLUnlinkNode(child._xmlNode)
} //primitive
// see above
internal func _setChildren(_ children: [NSXMLNode]?) {
_removeAllChildren()
guard let children = children else {
return
}
for child in children {
_addChild(child)
}
} //primitive
/*!
@method addChild:
@abstract Adds a child to the end of the existing children.
*/
// see above
internal func _addChild(_ child: NSXMLNode) {
precondition(child.parent == nil)
_CFXMLNodeAddChild(_xmlNode, child._xmlNode)
_childNodes.insert(child)
}
/*!
@method replaceChildAtIndex:withNode:
@abstract Replaces a child at a particular index with another child.
*/
// see above
internal func _replaceChildAtIndex(_ index: Int, withNode node: NSXMLNode) {
let child = childAtIndex(index)!
_childNodes.remove(child)
_CFXMLNodeReplaceNode(child._xmlNode, node._xmlNode)
_childNodes.insert(node)
}
}
internal protocol _NSXMLNodeCollectionType: Collection { }
extension NSXMLNode: _NSXMLNodeCollectionType {
public struct Index: Comparable {
private let node: _CFXMLNodePtr?
private let offset: Int?
}
public subscript(index: Index) -> NSXMLNode {
return NSXMLNode._objectNodeForNode(index.node!)
}
public var startIndex: Index {
let node = _CFXMLNodeGetFirstChild(_xmlNode)
return Index(node: node, offset: node.map { _ in 0 })
}
public var endIndex: Index {
return Index(node: nil, offset: nil)
}
public func index(after i: Index) -> Index {
precondition(i.node != nil, "can't increment endIndex")
let nextNode = _CFXMLNodeGetNextSibling(i.node!)
return Index(node: nextNode, offset: nextNode.map { _ in i.offset! + 1 } )
}
}
public func ==(lhs: NSXMLNode.Index, rhs: NSXMLNode.Index) -> Bool {
return lhs.offset == rhs.offset
}
public func <(lhs: NSXMLNode.Index, rhs: NSXMLNode.Index) -> Bool {
switch (lhs.offset, rhs.offset) {
case (nil, nil):
return false
case (nil, _):
return false
case (_, nil):
return true
case (let lhsOffset, let rhsOffset):
return lhsOffset < rhsOffset
}
}
|
apache-2.0
|
1ff419674e34987f2ccd5c364c48c5ff
| 32.369048 | 451 | 0.614666 | 4.739164 | false | false | false | false |
Isahkaren/Mememe
|
Mememe/Mememe/MememeViewController.swift
|
1
|
6148
|
//
// MememeViewController.swift
// Mememe
//
// Created by Isabela Karen de Oliveira Gomes on 14/11/16.
// Copyright © 2016 Isabela Karen de Oliveira Gomes. All rights reserved.
//
import UIKit
class MememeViewController: UIViewController, UINavigationControllerDelegate, UITextFieldDelegate {
// MARK: - Properties
@IBOutlet weak var txtTop: UITextField!
@IBOutlet weak var txtBottom: UITextField!
@IBOutlet weak var imgMain: UIImageView!
@IBOutlet weak var btnShare: UIBarButtonItem!
@IBOutlet weak var navigationBar: UINavigationBar!
@IBOutlet weak var toolBar: UIToolbar!
@IBOutlet weak var btnCamera: UIBarButtonItem!
// MARK: - textField Attributes
let textFieldAttributes = [
NSStrokeColorAttributeName : UIColor.black,
NSForegroundColorAttributeName : UIColor.white,
NSFontAttributeName : UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSStrokeWidthAttributeName : -4
] as [String : Any]
func textFieldStyle(textField: UITextField) {
textField.defaultTextAttributes = textFieldAttributes
textField.textAlignment = NSTextAlignment.center
}
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
textFieldStyle(textField: txtTop)
textFieldStyle(textField: txtBottom)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
subscribeToKeyboardNotifications()
if imgMain.image == nil{
btnShare.isEnabled = false
} else {
btnShare.isEnabled = true
}
btnCamera.isEnabled = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeFromKeyboardNotifications()
}
// MARK: - Keyboard Properties
func subscribeToKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)
}
func unsubscribeFromKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
}
func keyboardWillShow(_ notification:Notification) {
if txtBottom.isFirstResponder {
self.view.frame.origin.y -= getKeyboardHeight(notification);
}
else if txtTop.isFirstResponder {
self.view.frame.origin.y = 0;
}
}
func getKeyboardHeight(_ notification:Notification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.cgRectValue.height
}
func keyboardWillHide (notification: Notification) {
self.view.frame.origin.y = 0
}
// MARK: - Keyboard Dismiss
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// MARK: - Actions
@IBAction func btnCamera(_ sender: UIBarButtonItem) {
pick(sourceType: .camera)
}
@IBAction func btnShare(_ sender: UIButton) {
let share = generateMemedImage()
let controller = UIActivityViewController(activityItems: [share], applicationActivities: nil)
self.present(controller, animated: true, completion: nil)
controller.completionWithItemsHandler = {(activity, completed, items, error) in
if (completed) {
self.save()
}
}
}
@IBAction func btnBack_Clicked(_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func btnAlbum(_ sender: UIBarButtonItem) {
pick(sourceType: .photoLibrary)
}
@IBAction func btnCancel(_ sender: UIBarButtonItem) {
imgMain.image = nil
txtTop.text = "TOP"
txtBottom.text = "BOTTOM"
}
// MARK: - functions Meme Generate and Save
func generateMemedImage() -> UIImage {
navigationBar.isHidden = true
toolBar.isHidden = true
UIGraphicsBeginImageContext(self.view.frame.size)
self.view.drawHierarchy(in: self.view.frame, afterScreenUpdates: true)
let memedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
navigationBar.isHidden = false
toolBar.isHidden = false
return memedImage
}
func save() {
let meme = ImageSalve(textTop: txtTop.text!, textBottom: txtBottom.text!, originalImage: imgMain.image!,imageMeme: generateMemedImage())
let object = UIApplication.shared.delegate
let appDelegate = object as! AppDelegate
appDelegate.memes.append(meme)
self.dismiss(animated: true, completion: nil)
}
}
// MARK: - Extension Image Picker
extension MememeViewController: UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage]
picker.delegate = self
picker.allowsEditing = true
self.imgMain.image = image as! UIImage?
picker.dismiss(animated: true, completion: nil)
}
func pick(sourceType:UIImagePickerControllerSourceType){
let camera = UIImagePickerController()
camera.delegate = self
camera.sourceType = sourceType
self.present(camera, animated: true, completion: nil)
}
}
|
mit
|
153293328ec1ad0d4ef6b8c3ea514920
| 31.52381 | 146 | 0.652188 | 5.542831 | false | false | false | false |
tresorit/ZeroKit-Realm-encrypted-tasks
|
ios/Pods/RealmLoginKit/RealmLoginKit Apple/RealmLoginKit/Models/UIStateCoordination/LoginViewControllerTransitioning.swift
|
2
|
3674
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2017 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import UIKit
class LoginViewControllerTransitioning: NSObject, UIViewControllerAnimatedTransitioning {
public var isDismissing = false
public var statusBarView: UIView?
public var contentView: UIView?
public var controlView: UIView?
public var effectsView: UIVisualEffectView?
public var backgroundView: UIView?
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.75
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let duration = self.transitionDuration(using: transitionContext)
let containerView = transitionContext.containerView
let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
let statusBarAlpha = statusBarView!.alpha
let animateStatusBar = statusBarAlpha > CGFloat(0.0)
// Hold onto a reference to the effect
let effect = effectsView?.effect
// Make sure both view controllers are full screen
fromViewController?.view.frame = containerView.bounds
toViewController?.view.frame = containerView.bounds
// set up the initial animation state
contentView?.frame.origin.y = !isDismissing ? containerView.frame.maxY : containerView.bounds.minY
backgroundView?.alpha = !isDismissing ? 0.0 : 1.0
effectsView?.effect = !isDismissing ? nil : effect
controlView?.alpha = !isDismissing ? 0.0 : 1.0
if animateStatusBar {
statusBarView?.alpha = !isDismissing ? 0.0 : statusBarAlpha
}
if !isDismissing {
containerView.addSubview(toViewController!.view)
}
else {
if fromViewController?.modalPresentationStyle != .overFullScreen {
containerView.insertSubview(toViewController!.view, at: 0)
}
}
// perform the animation
UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.5, options: [], animations: {
self.contentView?.frame.origin.y = !self.isDismissing ? containerView.bounds.minY : containerView.bounds.maxY
self.backgroundView?.alpha = !self.isDismissing ? 1.0 : 0.0
self.effectsView?.effect = !self.isDismissing ? effect : nil
self.controlView?.alpha = !self.isDismissing ? 1.0 : 0.0
if animateStatusBar {
self.statusBarView?.alpha = !self.isDismissing ? statusBarAlpha : 0.0
}
}) { complete in
self.effectsView?.effect = effect
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
|
bsd-3-clause
|
39f3813124b47c8c957a670ce1905489
| 41.229885 | 142 | 0.656505 | 5.5 | false | false | false | false |
HTWDD/HTWDresden-iOS
|
HTWDD/Components/Canteen/Main/MealsViewController.swift
|
1
|
2870
|
//
// MealsViewController.swift
// HTWDD
//
// Created by Mustafa Karademir on 11.07.19.
// Copyright © 2019 HTW Dresden. All rights reserved.
//
import UIKit
import RxSwift
class MealsViewController: UITableViewController {
// MARK: - Properties
var viewModel: MealsViewModel!
private var items: [Meals] = [] {
didSet {
tableView.reloadData()
}
}
private let stateView: EmptyResultsView = {
return EmptyResultsView().also {
$0.isHidden = true
}
}()
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.apply {
$0.estimatedRowHeight = 200
$0.rowHeight = UITableView.automaticDimension
}
}
}
// MARK: - Setup
extension MealsViewController {
private func setup() {
tableView.apply {
$0.separatorStyle = .none
$0.backgroundColor = UIColor.htw.veryLightGrey
$0.backgroundView = stateView
$0.register(MealHeaderViewCell.self)
$0.register(MealViewCell.self)
}
viewModel
.load()
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] items in
guard let self = self else { return }
self.items = items
if items.isEmpty {
self.stateView.setup(with: EmptyResultsView.Configuration(icon: "😦", title: R.string.localizable.canteenNoResultsTitle(), message: R.string.localizable.canteenNoResultsMessage(), hint: nil, action: nil))
}
}, onError: { error in
Log.error(error)
})
.disposed(by: rx_disposeBag)
}
}
// MARK: - TableView Datasource
extension MealsViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch items[indexPath.row] {
case .header(let model):
let cell = tableView.dequeueReusableCell(MealHeaderViewCell.self, for: indexPath)!
cell.setup(with: model)
return cell
case .meal(let model):
let cell = tableView.dequeueReusableCell(MealViewCell.self, for: indexPath)!
cell.setup(with: model)
return cell
}
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = .clear
}
}
|
gpl-2.0
|
a2bc2ba40ca6a3f81c004fa91be6ee07
| 28.244898 | 223 | 0.580251 | 4.949914 | false | false | false | false |
wuzhenli/MyDailyTestDemo
|
swiftTest/swifter-tips+swift+3.0/Swifter.playground/Pages/class-cluster.xcplaygroundpage/Contents.swift
|
2
|
870
|
import UIKit
class Drinking {
typealias LiquidColor = UIColor
var color: LiquidColor {
return .clear
}
class func drinking(name: String) -> Drinking {
var drinking: Drinking
switch name {
case "Coke":
drinking = Coke()
case "Beer":
drinking = Beer()
default:
drinking = Drinking()
}
return drinking
}
}
class Coke: Drinking {
override var color: LiquidColor {
return .black
}
}
class Beer: Drinking {
override var color: LiquidColor {
return .yellow
}
}
let coke = Drinking.drinking(name: "Coke")
coke.color // Black
let beer = Drinking.drinking(name: "Beer")
beer.color // Yellow
let cokeClass = NSStringFromClass(type(of: coke)) //Coke
let beerClass = NSStringFromClass(type(of: beer)) //Beer
|
apache-2.0
|
e1dd130fd29666bf96615be29b1acc64
| 17.913043 | 56 | 0.586207 | 4.046512 | false | false | false | false |
sgr-ksmt/ElastiQ
|
Sources/GeoQueries.swift
|
1
|
2502
|
//
// GeoQueries.swift
// ElastiQ
//
// Created by suguru-kishimoto on 2017/09/12.
// Copyright © 2017年 Suguru Kishimoto. All rights reserved.
//
import Foundation
extension ElastiQ {
public struct GeoQueries {
private init() {}
public struct GeoDistance: QueryParameter {
public typealias Location = (key: String, lat: Latitude, lon: Longitude)
public typealias Latitude = QueryNumberValue
public typealias Longitude = QueryNumberValue
public enum Distance {
case mi(QueryNumberValue)
case yd(QueryNumberValue)
case ft(QueryNumberValue)
case `in`(QueryNumberValue)
case km(QueryNumberValue)
case m(QueryNumberValue)
case cm(QueryNumberValue)
case mm(QueryNumberValue)
case nauticalMile(QueryNumberValue)
var value: String {
switch self {
case .mi(let value): return "\(value)mi"
case .yd(let value): return "\(value)yd"
case .ft(let value): return "\(value)ft"
case .in(let value): return "\(value)in"
case .km(let value): return "\(value)km"
case .m(let value): return "\(value)m"
case .cm(let value): return "\(value)cm"
case .mm(let value): return "\(value)mm"
case .nauticalMile(let value): return "\(value)NM"
}
}
}
public enum DistanceType: String {
case arc // Default
case plane
}
public let parameterName: String = "geo_distance"
let location: Location
let distance: Distance?
let distanceType: DistanceType?
init(location: Location, distance: Distance? = nil, distanceType: DistanceType? = nil) {
self.location = location
self.distance = distance
self.distanceType = distanceType
}
public var body: Any {
var body: [AnyHashable: Any] = [:]
body[location.key] = ["lat": location.lat, "lon": location.lon]
body["distance"] = distance?.value
body["distance_type"] = distanceType?.rawValue
return body
}
}
}
}
|
mit
|
a98334f38da4a16da567952fd91bb49a
| 33.708333 | 100 | 0.511405 | 5.079268 | false | false | false | false |
tkareine/MiniFuture
|
Source/Try.swift
|
1
|
2001
|
import Foundation
public enum Try<T> {
case success(T)
case failure(Error)
public func flatMap<U>(_ f: (T) throws -> Try<U>) -> Try<U> {
switch self {
case .success(let value):
do {
return try f(value)
} catch {
return .failure(error)
}
case .failure(let error):
return .failure(error)
}
}
public func map<U>(_ f: (T) throws -> U) -> Try<U> {
return flatMap { e in
do {
return .success(try f(e))
} catch {
return .failure(error)
}
}
}
public func value() throws -> T {
switch self {
case .success(let value):
return value
case .failure(let error):
throw error
}
}
public var isSuccess: Bool {
switch self {
case .success:
return true
case .failure:
return false
}
}
public var isFailure: Bool {
return !isSuccess
}
}
extension Try: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
switch self {
case .success(let value):
return "Try.success(\(value))"
case .failure(let error):
return "Try.failure(\(error))"
}
}
public var debugDescription: String {
switch self {
case .success(let value):
return "Try.success(\(String(reflecting: value)))"
case .failure(let error):
return "Try.failure(\(String(reflecting: error)))"
}
}
}
/**
* Try enumeration does not adopt Equatable protocol, because that would limit
* the allowed values of generic type T. Instead, we provide `==` operator.
*/
public func ==<T: Equatable>(lhs: Try<T>, rhs: Try<T>) -> Bool {
switch (lhs, rhs) {
case (.success(let lhs), .success(let rhs)):
return lhs == rhs
case (.failure(let lhs as NSError), .failure(let rhs as NSError)):
return lhs.domain == rhs.domain
&& lhs.code == rhs.code
default:
return false
}
}
public func !=<T: Equatable>(lhs: Try<T>, rhs: Try<T>) -> Bool {
return !(lhs == rhs)
}
|
mit
|
01407a90edfe2e25c132d0cc1fd42fed
| 20.989011 | 78 | 0.591204 | 3.796964 | false | false | false | false |
madewithray/ray-broadcast
|
RayBroadcast/AdvertiseViewController.swift
|
1
|
5038
|
//
// AdvertiseViewController.swift
// RayBroadcast
//
// Created by Sean Ooi on 7/3/15.
// Copyright (c) 2015 Yella Inc. All rights reserved.
//
import UIKit
import CoreLocation
import CoreBluetooth
class AdvertiseViewController: UIViewController {
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var majorLabel: UILabel!
@IBOutlet weak var minorLabel: UILabel!
@IBOutlet weak var regionLabel: UILabel!
@IBOutlet weak var majorValueLabel: UILabel!
@IBOutlet weak var minorValueLabel: UILabel!
@IBOutlet weak var regionValueLabel: UILabel!
@IBOutlet weak var dotImageView: UIImageView!
var beacon: [String: AnyObject]?
var pulseEffect: LFTPulseAnimation! = nil
var peripheralManager: CBPeripheralManager! = nil
var peripheralState = "Unknown"
override func viewDidLoad() {
super.viewDidLoad()
title = "Advertise"
descriptionLabel.text = "Advertising beacon data:"
majorLabel.text = "Major:"
majorLabel.font = UIFont.boldSystemFontOfSize(16)
minorLabel.text = "Minor:"
minorLabel.font = UIFont.boldSystemFontOfSize(16)
regionLabel.text = "Region:"
regionLabel.font = UIFont.boldSystemFontOfSize(16)
if let beacon = beacon {
majorValueLabel.text = String(beacon["major"] as? Int ?? 0)
minorValueLabel.text = String(beacon["minor"] as? Int ?? 0)
regionValueLabel.text = beacon["identifier"] as? String ?? "No Identifier"
}
dotImageView.contentMode = .ScaleAspectFit
dotImageView.image = UIImage(named: "Dot")
peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
advertise()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
peripheralManager.stopAdvertising()
}
deinit {
peripheralManager = nil
if pulseEffect != nil {
pulseEffect.removeFromSuperlayer()
pulseEffect = nil
}
println("deinit")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func advertise() {
if peripheralManager.state == .PoweredOn {
if peripheralManager.isAdvertising {
peripheralManager.stopAdvertising()
if pulseEffect != nil {
pulseEffect.removeFromSuperlayer()
pulseEffect = nil
}
}
else {
if let
beacon = beacon,
uuid = beacon["uuid"] as? String,
major = beacon["major"] as? Int,
minor = beacon["minor"] as? Int,
identifier = beacon["identifier"] as? String
{
let beaconRegion = CLBeaconRegion(
proximityUUID: NSUUID(UUIDString: uuid),
major: UInt16(major),
minor: UInt16(minor),
identifier: identifier)
let manufacturerData = identifier.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
var beaconData = beaconRegion.peripheralDataWithMeasuredPower(1) as [NSObject : AnyObject]
beaconData[CBAdvertisementDataLocalNameKey] = "Ray Beacon"
beaconData[CBAdvertisementDataTxPowerLevelKey] = -12
beaconData[CBAdvertisementDataManufacturerDataKey] = manufacturerData
beaconData[CBAdvertisementDataServiceUUIDsKey] = [CBUUID(NSUUID: NSUUID(UUIDString: uuid))]
peripheralManager.startAdvertising(beaconData)
if pulseEffect == nil {
pulseEffect = LFTPulseAnimation(repeatCount: Float.infinity, radius: 100, position: dotImageView.center)
view.layer.insertSublayer(pulseEffect, below: dotImageView.layer)
}
}
}
}
else {
let alertController = UIAlertController(title: "Bluetooth Error", message: peripheralState, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Cancel, handler: {[unowned self] (action) -> Void in
if let navigationController = self.navigationController {
navigationController.popViewControllerAnimated(true)
}
})
alertController.addAction(okAction)
presentViewController(alertController, animated: true, completion: nil)
}
}
}
|
mit
|
57ffcc3b3d3d1239670f0d98ffc68324
| 35.507246 | 128 | 0.577809 | 5.764302 | false | false | false | false |
OpenKitten/MongoKitten
|
Sources/MongoKittenCore/Commands/Insert.swift
|
2
|
1112
|
import MongoCore
public struct InsertCommand: Codable {
/// This variable _must_ be the first encoded value, so keep it above all others
private let insert: String
public var collection: String { return insert }
public var documents: [Document]
public var ordered: Bool?
public var writeConcern: WriteConcern?
public var bypassDocumentValidation: Bool?
public init(documents: [Document], inCollection collection: String) {
self.insert = collection
self.documents = documents
}
}
public struct InsertReply: Decodable, Error, CustomDebugStringConvertible {
private enum CodingKeys: String, CodingKey {
case ok, writeErrors, writeConcernError
case insertCount = "n"
}
public let ok: Int
public let insertCount: Int
public let writeErrors: [MongoWriteError]?
public let writeConcernError: WriteConcernError?
public var debugDescription: String {
if ok == 1 {
return "InsertReply(insertCount: \(insertCount))"
} else {
return "InsertError"
}
}
}
|
mit
|
552d3d476372e78d6f89fa9ee0210bb0
| 28.263158 | 84 | 0.666367 | 4.834783 | false | false | false | false |
EgeTart/ImageClip
|
ImageClip/HTTPRequestSerializer.swift
|
1
|
11997
|
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// HTTPRequestSerializer.swift
//
// Created by Dalton Cherry on 6/3/14.
// Copyright (c) 2014 Vluxe. All rights reserved.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
extension String {
/**
A simple extension to the String object to encode it for web request.
- returns: Encoded version of of string it was called as.
*/
var escaped: String {
return CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,self,"[].",":/?&=;+!@#$()',*",CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)) as String
}
}
/// Default Serializer for serializing an object to an HTTP request. This applies to form serialization, parameter encoding, etc.
public class HTTPRequestSerializer: NSObject {
let contentTypeKey = "Content-Type"
/// headers for the request.
public var headers = Dictionary<String,String>()
/// encoding for the request.
public var stringEncoding: UInt = NSUTF8StringEncoding
/// Send request if using cellular network or not. Defaults to true.
public var allowsCellularAccess = true
/// If the request should handle cookies of not. Defaults to true.
public var HTTPShouldHandleCookies = true
/// If the request should use piplining or not. Defaults to false.
public var HTTPShouldUsePipelining = false
/// How long the timeout interval is. Defaults to 60 seconds.
public var timeoutInterval: NSTimeInterval = 60
/// Set the request cache policy. Defaults to UseProtocolCachePolicy.
public var cachePolicy: NSURLRequestCachePolicy = NSURLRequestCachePolicy.UseProtocolCachePolicy
/// Set the network service. Defaults to NetworkServiceTypeDefault.
public var networkServiceType = NSURLRequestNetworkServiceType.NetworkServiceTypeDefault
/// Initializes a new HTTPRequestSerializer Object.
public override init() {
super.init()
}
/**
Creates a new NSMutableURLRequest object with configured options.
- parameter url: The url you would like to make a request to.
- parameter method: The HTTP method/verb for the request.
- returns: A new NSMutableURLRequest with said options.
*/
public func newRequest(url: NSURL, method: HTTPMethod) -> NSMutableURLRequest {
let request = NSMutableURLRequest(URL: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval)
request.HTTPMethod = method.rawValue
request.cachePolicy = self.cachePolicy
request.timeoutInterval = self.timeoutInterval
request.allowsCellularAccess = self.allowsCellularAccess
request.HTTPShouldHandleCookies = self.HTTPShouldHandleCookies
request.HTTPShouldUsePipelining = self.HTTPShouldUsePipelining
request.networkServiceType = self.networkServiceType
for (key,val) in self.headers {
request.addValue(val, forHTTPHeaderField: key)
}
return request
}
/**
Creates a new NSMutableURLRequest object with configured options.
- parameter url: The url you would like to make a request to.
- parameter method: The HTTP method/verb for the request.
- parameter parameters: The parameters are HTTP parameters you would like to send.
- returns: A new NSMutableURLRequest with said options or an error.
*/
public func createRequest(url: NSURL, method: HTTPMethod, parameters: Dictionary<String,AnyObject>?) -> (request: NSURLRequest, error: NSError?) {
let request = newRequest(url, method: method)
var isMulti = false
//do a check for upload objects to see if we are multi form
if let params = parameters {
isMulti = isMultiForm(params)
}
if isMulti {
if(method != .POST && method != .PUT && method != .PATCH) {
request.HTTPMethod = HTTPMethod.POST.rawValue // you probably wanted a post
}
let boundary = "Boundary+\(arc4random())\(arc4random())"
if parameters != nil {
request.HTTPBody = dataFromParameters(parameters!,boundary: boundary)
}
if request.valueForHTTPHeaderField(contentTypeKey) == nil {
request.setValue("multipart/form-data; boundary=\(boundary)",
forHTTPHeaderField:contentTypeKey)
}
return (request,nil)
}
var queryString = ""
if parameters != nil {
queryString = self.stringFromParameters(parameters!)
}
if isURIParam(method) {
let para = (request.URL!.query != nil) ? "&" : "?"
var newUrl = "\(request.URL!.absoluteString)"
if queryString.characters.count > 0 {
newUrl += "\(para)\(queryString)"
}
request.URL = NSURL(string: newUrl)
} else {
let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
if request.valueForHTTPHeaderField(contentTypeKey) == nil {
request.setValue("application/x-www-form-urlencoded; charset=\(charset)",
forHTTPHeaderField:contentTypeKey)
}
request.HTTPBody = queryString.dataUsingEncoding(self.stringEncoding)
}
return (request,nil)
}
///check for multi form objects
public func isMultiForm(params: Dictionary<String,AnyObject>) -> Bool {
for (_, object) in params {
if object is HTTPUpload {
return true
} else if let subParams = object as? Dictionary<String,AnyObject> {
if isMultiForm(subParams) {
return true
}
}
}
return false
}
///check if enum is a HTTPMethod that requires the params in the URL
public func isURIParam(method: HTTPMethod) -> Bool {
if(method == .GET || method == .HEAD || method == .DELETE) {
return true
}
return false
}
///convert the parameter dict to its HTTP string representation
public func stringFromParameters(parameters: Dictionary<String,AnyObject>) -> String {
return (serializeObject(parameters, key: nil).map({(pair) in
return pair.stringValue()
})).joinWithSeparator("&")
}
///the method to serialized all the objects
func serializeObject(object: AnyObject,key: String?) -> Array<HTTPPair> {
var collect = Array<HTTPPair>()
if let array = object as? Array<AnyObject> {
for nestedValue : AnyObject in array {
collect.appendContentsOf(self.serializeObject(nestedValue,key: "\(key!)[]"))
}
} else if let dict = object as? Dictionary<String,AnyObject> {
for (nestedKey, nestedObject) in dict {
let newKey = key != nil ? "\(key!)[\(nestedKey)]" : nestedKey
collect.appendContentsOf(self.serializeObject(nestedObject, key: newKey))
}
} else {
collect.append(HTTPPair(value: object, key: key))
}
return collect
}
//create a multi form data object of the parameters
func dataFromParameters(parameters: Dictionary<String,AnyObject>,boundary: String) -> NSData {
let mutData = NSMutableData()
let multiCRLF = "\r\n"
let boundSplit = "\(multiCRLF)--\(boundary)\(multiCRLF)".dataUsingEncoding(self.stringEncoding)!
let lastBound = "\(multiCRLF)--\(boundary)--\(multiCRLF)".dataUsingEncoding(self.stringEncoding)!
mutData.appendData("--\(boundary)\(multiCRLF)".dataUsingEncoding(self.stringEncoding)!)
let pairs = serializeObject(parameters, key: nil)
let count = pairs.count-1
var i = 0
for pair in pairs {
var append = true
if let upload = pair.getUpload() {
if let data = upload.data {
mutData.appendData(multiFormHeader(pair.k, fileName: upload.fileName,
type: upload.mimeType, multiCRLF: multiCRLF).dataUsingEncoding(self.stringEncoding)!)
mutData.appendData(data)
} else {
append = false
}
} else {
let str = "\(multiFormHeader(pair.k, fileName: nil, type: nil, multiCRLF: multiCRLF))\(pair.getValue())"
mutData.appendData(str.dataUsingEncoding(self.stringEncoding)!)
}
if append {
if i == count {
mutData.appendData(lastBound)
} else {
mutData.appendData(boundSplit)
}
}
i++
}
return mutData
}
///helper method to create the multi form headers
func multiFormHeader(name: String, fileName: String?, type: String?, multiCRLF: String) -> String {
var str = "Content-Disposition: form-data; name=\"\(name.escaped)\""
if fileName != nil {
str += "; filename=\"\(fileName!)\""
}
str += multiCRLF
if type != nil {
str += "Content-Type: \(type!)\(multiCRLF)"
}
str += multiCRLF
return str
}
/// Creates key/pair of the parameters.
class HTTPPair: NSObject {
var val: AnyObject
var k: String!
init(value: AnyObject, key: String?) {
self.val = value
self.k = key
}
func getUpload() -> HTTPUpload? {
return self.val as? HTTPUpload
}
func getValue() -> String {
var val = ""
if let str = self.val as? String {
val = str
} else if self.val.description != nil {
val = self.val.description
}
return val
}
func stringValue() -> String {
let v = getValue()
if self.k == nil {
return v.escaped
}
return "\(self.k.escaped)=\(v.escaped)"
}
}
}
/// JSON Serializer for serializing an object to an HTTP request. Same as HTTPRequestSerializer, expect instead of HTTP form encoding it does JSON.
public class JSONRequestSerializer: HTTPRequestSerializer {
/**
Creates a new NSMutableURLRequest object with configured options.
- parameter url: The url you would like to make a request to.
- parameter method: The HTTP method/verb for the request.
- parameter parameters: The parameters are HTTP parameters you would like to send.
- returns: A new NSMutableURLRequest with said options or an error.
*/
public override func createRequest(url: NSURL, method: HTTPMethod, parameters: Dictionary<String,AnyObject>?) -> (request: NSURLRequest, error: NSError?) {
if self.isURIParam(method) {
return super.createRequest(url, method: method, parameters: parameters)
}
let request = newRequest(url, method: method)
var error: NSError?
if parameters != nil {
let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
request.setValue("application/json; charset=\(charset)", forHTTPHeaderField: self.contentTypeKey)
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters!, options: NSJSONWritingOptions())
} catch let error1 as NSError {
error = error1
request.HTTPBody = nil
}
}
return (request, error)
}
}
|
mit
|
bc29617f38cf5b2e19a0107211bc0f17
| 40.230241 | 179 | 0.596232 | 5.322538 | false | false | false | false |
sunlijian/sinaBlog_repository
|
sinaBlog_sunlijian/sinaBlog_sunlijian/Classes/Model/IWTabBarItem.swift
|
1
|
3064
|
//
// IWTabBarItem.swift
// sinaBlog_sunlijian
//
// Created by sunlijian on 15/10/15.
// Copyright © 2015年 myCompany. All rights reserved.
//
import UIKit
class IWTabBarItem: UITabBarItem{
// var index: Int = 0
override var badgeValue: String? { //override 是从你烦继承过来的实例变量
didSet{
//didSet 设置完后再调用
setBadgeViewBackgroundImage()
}
}
private func setBadgeViewBackgroundImage()
{
//---------------拿到显示 badgeValue 的控件----------
let target = self.valueForKeyPath("_target") as! UITabBarController
//遍历 tabBar 的子控件
for tabBarChild in target.tabBar.subviews {
//拿到 UITabBarButton
if tabBarChild.isKindOfClass(NSClassFromString("UITabBarButton")!) {
//遍历 UITabBarButton 的子控件
for tabBarButtonChild in tabBarChild.subviews {
//拿到_UIBadgeView
if tabBarButtonChild.isKindOfClass(NSClassFromString("_UIBadgeView")!) {
//遍历_UIBadgeView 的子控件
for badgeViewChild in tabBarButtonChild.subviews {
//拿到_UIBadgeBackground
if badgeViewChild.isKindOfClass(NSClassFromString("_UIBadgeBackground")!) {
//------------利用运行时 获取 bagdeView的实例变量 KVC给实例变量赋值
//获取类的实例变量列表
var count : UInt32 = 0
let ivars = class_copyIvarList(NSClassFromString("_UIBadgeBackground"), &count)
//遍历实例变量列表
for i in 0..<count {
//获取一个实例变量
let ivar = ivars[Int(i)]
//获取 ivar的名称
let ivarName = NSString(CString: ivar_getName(ivar), encoding: NSUTF8StringEncoding)
//获取 ivar的类型
let ivarType = NSString(CString: ivar_getTypeEncoding(ivar), encoding: NSUTF8StringEncoding)
printLog("name=\(ivarName);type=\(ivarType)") //打印结果 name=Optional(_image);type=Optional(@"UIImage")
//当ivarName是 _image 的时候 用 KVC给类的属性进行赋值
if ivarName!.isEqualToString("_image") {
badgeViewChild.setValue(UIImage(named: "main_badge"), forKeyPath: "_image")
}
}
}
}
}
}
}
}
}
}
|
apache-2.0
|
06cf0ecae382e10ebd70398dd9a1c253
| 39.157143 | 136 | 0.452508 | 5.819876 | false | false | false | false |
JakeLin/IBAnimatable
|
Sources/Views/AnimatableStackView.swift
|
2
|
5412
|
//
// Created by Jake Lin on 12/11/15.
// Copyright © 2015 IBAnimatable. All rights reserved.
//
import UIKit
// FIXME: almost same as `AnimatableView`, Need to refactor to encasuplate.
@IBDesignable
open class AnimatableStackView: UIStackView, CornerDesignable, FillDesignable, BorderDesignable,
RotationDesignable, ShadowDesignable, TintDesignable, GradientDesignable,
MaskDesignable, Animatable {
// MARK: - CornerDesignable
@IBInspectable open var cornerRadius: CGFloat = CGFloat.nan {
didSet {
configureCornerRadius()
}
}
open var cornerSides: CornerSides = .allSides {
didSet {
configureCornerRadius()
}
}
@IBInspectable var _cornerSides: String? {
didSet {
cornerSides = CornerSides(rawValue: _cornerSides)
}
}
// MARK: - FillDesignable
@IBInspectable open var fillColor: UIColor? {
didSet {
configureFillColor()
}
}
open var predefinedColor: ColorType? {
didSet {
configureFillColor()
}
}
@IBInspectable var _predefinedColor: String? {
didSet {
predefinedColor = ColorType(string: _predefinedColor)
}
}
@IBInspectable open var opacity: CGFloat = CGFloat.nan {
didSet {
configureOpacity()
}
}
// MARK: - BorderDesignable
open var borderType: BorderType = .solid {
didSet {
configureBorder()
}
}
@IBInspectable var _borderType: String? {
didSet {
borderType = BorderType(string: _borderType)
}
}
@IBInspectable open var borderColor: UIColor? {
didSet {
configureBorder()
}
}
@IBInspectable open var borderWidth: CGFloat = CGFloat.nan {
didSet {
configureBorder()
}
}
open var borderSides: BorderSides = .AllSides {
didSet {
configureBorder()
}
}
@IBInspectable var _borderSides: String? {
didSet {
borderSides = BorderSides(rawValue: _borderSides)
}
}
// MARK: - RotationDesignable
@IBInspectable open var rotate: CGFloat = CGFloat.nan {
didSet {
configureRotate()
}
}
// MARK: - ShadowDesignable
@IBInspectable open var shadowColor: UIColor? {
didSet {
configureShadowColor()
}
}
@IBInspectable open var shadowRadius: CGFloat = CGFloat.nan {
didSet {
configureShadowRadius()
}
}
@IBInspectable open var shadowOpacity: CGFloat = CGFloat.nan {
didSet {
configureShadowOpacity()
}
}
@IBInspectable open var shadowOffset: CGPoint = CGPoint(x: CGFloat.nan, y: CGFloat.nan) {
didSet {
configureShadowOffset()
}
}
// MARK: - TintDesignable
@IBInspectable open var tintOpacity: CGFloat = CGFloat.nan
@IBInspectable open var shadeOpacity: CGFloat = CGFloat.nan
@IBInspectable open var toneColor: UIColor?
@IBInspectable open var toneOpacity: CGFloat = CGFloat.nan
// MARK: - GradientDesignable
open var gradientMode: GradientMode = .linear
@IBInspectable var _gradientMode: String? {
didSet {
gradientMode = GradientMode(string: _gradientMode) ?? .linear
}
}
@IBInspectable open var startColor: UIColor?
@IBInspectable open var endColor: UIColor?
open var predefinedGradient: GradientType?
@IBInspectable var _predefinedGradient: String? {
didSet {
predefinedGradient = GradientType(string: _predefinedGradient)
}
}
open var startPoint: GradientStartPoint = .top
@IBInspectable var _startPoint: String? {
didSet {
startPoint = GradientStartPoint(string: _startPoint, default: .top)
}
}
// MARK: - MaskDesignable
open var maskType: MaskType = .none {
didSet {
configureMask(previousMaskType: oldValue)
configureBorder()
}
}
/// The mask type used in Interface Builder. **Should not** use this property in code.
@IBInspectable var _maskType: String? {
didSet {
maskType = MaskType(string: _maskType)
}
}
// MARK: - Animatable
open var animationType: AnimationType = .none
@IBInspectable var _animationType: String? {
didSet {
animationType = AnimationType(string: _animationType)
}
}
@IBInspectable open var autoRun: Bool = true
@IBInspectable open var duration: Double = Double.nan
@IBInspectable open var delay: Double = Double.nan
@IBInspectable open var damping: CGFloat = CGFloat.nan
@IBInspectable open var velocity: CGFloat = CGFloat.nan
@IBInspectable open var force: CGFloat = CGFloat.nan
@IBInspectable var _timingFunction: String = "" {
didSet {
timingFunction = TimingFunctionType(string: _timingFunction)
}
}
open var timingFunction: TimingFunctionType = .none
// MARK: - Lifecycle
open override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
configureInspectableProperties()
}
open override func awakeFromNib() {
super.awakeFromNib()
configureInspectableProperties()
}
open override func layoutSubviews() {
super.layoutSubviews()
configureAfterLayoutSubviews()
autoRunAnimation()
}
// MARK: - Private
fileprivate func configureInspectableProperties() {
configureAnimatableProperties()
configureTintedColor()
}
fileprivate func configureAfterLayoutSubviews() {
configureMask(previousMaskType: maskType)
configureCornerRadius()
configureBorder()
configureGradient()
}
}
|
mit
|
5b907533810344044d8121c7ac7a051b
| 23.935484 | 118 | 0.673258 | 4.839893 | false | true | false | false |
AgaKhanFoundation/WCF-iOS
|
Steps4Impact/Leaderboard/LeaderboardDataSource.swift
|
1
|
5016
|
/**
* Copyright © 2019 Aga Khan Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
import Foundation
class LeaderboardDataSource: TableViewDataSource {
var cells: [[CellContext]] = []
var completion: (() -> Void)?
var allTeams = [Leaderboard]()
var myTeamRank: Int?
var myTeamId: Int = -1
var expandListDataSource: [CellContext] = []
func reload(completion: @escaping () -> Void) {
self.completion = completion
AKFCausesService.getParticipant(fbid: User.id) { (result) in
if let participant = Participant(json: result.response), let event = participant.events?.first {
if let teamId = participant.team?.id {
self.myTeamId = teamId
}
if let eventId = event.id {
AKFCausesService.getLeaderboard(eventId: eventId) { (result) in
if let teams = result.response?.arrayValue {
self.allTeams.removeAll()
for team in teams {
guard let newLeaderboard = Leaderboard(json: team) else { return }
self.allTeams.append(newLeaderboard)
}
self.configure()
completion()
}
}
}
}
}
}
func newLeaderboardContext(for row: Int) -> LeaderboardContext {
let rank = row+1
let name = allTeams[row].name ?? ""
let distance = allTeams[row].miles ?? 0
let isMyTeam = allTeams[row].id == myTeamId
let context = LeaderboardContext(rank: rank, teamName: name, teamDistance: distance, isMyTeam: isMyTeam)
return context
}
func configure() {
cells.removeAll()
expandListDataSource.removeAll()
allTeams = allTeams.sorted(by: { ($0.distance ?? 0) > ($1.distance ?? 0) })
let count = allTeams.count > 2 ? 3 : allTeams.count
let podium = LeaderboardPodiumContext(count: count, data: allTeams)
cells.append([podium])
var rankTableList = [CellContext]()
myTeamRank = nil
if allTeams.count > 3 {
rankTableList.append(LeaderboardHeaderCellContext())
for index in 3..<allTeams.count {
// Checking if current Team is in the leaderboard and note the current team's rank
if allTeams[index].id == myTeamId {
myTeamRank = index+1
}
// Adding a new section for expand/collapse rows to the list only if the current team's rank is not in top 6
if index == 6 && myTeamRank == nil {
cells.append(rankTableList)
rankTableList.removeAll()
rankTableList.append(ExpandCollapseCellContext())
expandListDataSource.append(ExpandCollapseCellContext(titleText: "Collapse"))
expandListDataSource.append(newLeaderboardContext(for: index))
} else if index > 6 && myTeamRank == nil {
expandListDataSource.append(newLeaderboardContext(for: index))
} else if allTeams[index].id == myTeamId && index > 6 {
cells.append(rankTableList)
rankTableList.removeAll()
rankTableList.append(newLeaderboardContext(for: index))
} else {
rankTableList.append(newLeaderboardContext(for: index))
}
}
// If my team is not present in the leaderboard, remove the expand/collapse section and merge all in one list
if myTeamRank == nil && allTeams.count >= 7 {
expandListDataSource.removeFirst()
rankTableList = cells.removeLast()
rankTableList.append(contentsOf: expandListDataSource)
}
}
cells.append(rankTableList)
if allTeams.count == 0 {
cells = [[
EmptyLeaderboardCellContext(body: Strings.Leaderboard.empty)
]]
}
}
}
|
bsd-3-clause
|
d180295790a97dd245f1a3b26ffcae1a
| 39.443548 | 116 | 0.671186 | 4.399123 | false | false | false | false |
MakeBetterMe/PonyFrameworkOnSwift
|
PonyFrameworkOnSwift/Extensions/UIApplication+/UIApplication+Add.swift
|
1
|
829
|
//
// UIApplication+Add.swift
// WowLib
//
// Created by 小黑 on 16/4/11.
// Copyright © 2016年 wowdsgn. All rights reserved.
//
import Foundation
public extension UIApplication{
class func currentViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return currentViewController(nav.visibleViewController)
}
if let tab = base as? UITabBarController {
if let selected = tab.selectedViewController {
return currentViewController(selected)
}
}
if let presented = base?.presentedViewController {
return currentViewController(presented)
}
return base
}
}
|
mit
|
901b0c080f5d694b9f1be9fd5282776a
| 27.37931 | 150 | 0.643552 | 5.337662 | false | false | false | false |
binarylevel/Tinylog-iOS
|
Tinylog/View Controllers/Settings/TLISettingsTableViewController.swift
|
1
|
12451
|
//
// TLISettingsTableViewController.swift
// Tinylog
//
// Created by Spiros Gerokostas on 18/10/15.
// Copyright © 2015 Spiros Gerokostas. All rights reserved.
//
import UIKit
import MessageUI
import SVProgressHUD
class TLISettingsTableViewController: UITableViewController, MFMailComposeViewControllerDelegate, UIGestureRecognizerDelegate {
let settingsCellIdentifier = "SettingsCellIdentifier"
// MARK: Initializers
override init(style: UITableViewStyle) {
super.init(style: UITableViewStyle.Grouped)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(TLISettingsTableViewController.close(_:)))
self.view.backgroundColor = UIColor(red: 250.0 / 255.0, green: 250.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0)
self.tableView?.backgroundColor = UIColor(red: 250.0 / 255.0, green: 250.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0)
self.title = "Settings"
self.navigationController?.interactivePopGestureRecognizer!.enabled = true
self.navigationController?.interactivePopGestureRecognizer!.delegate = self
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TLISettingsTableViewController.updateFonts), name: TLINotifications.kTLIFontDidChangeNotification as String, object: nil)
}
func updateFonts() {
self.navigationController?.navigationBar.setNeedsDisplay()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tableView.reloadData()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
func configureCell(cell:UITableViewCell, indexPath:NSIndexPath) {
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
cell.textLabel?.font = UIFont.tinylogFontOfSize(17.0)
cell.textLabel?.textColor = UIColor.tinylogTextColor()
let selectedBackgroundView = UIView(frame: cell.frame)
selectedBackgroundView.backgroundColor = UIColor(red: 244.0 / 255.0, green: 244.0 / 255.0, blue: 244.0 / 255.0, alpha: 1.0)
selectedBackgroundView.contentMode = UIViewContentMode.Redraw
cell.selectedBackgroundView = selectedBackgroundView
if indexPath.section == 0 {
if indexPath.row == 0 {
cell.textLabel?.text = "iCloud"
cell.imageView?.image = UIImage(named: "706-cloud")
let switchMode:UISwitch = UISwitch(frame: CGRectMake(0, 0, self.view.frame.size.width, 20.0))
switchMode.addTarget(self, action: #selector(TLISettingsTableViewController.toggleSyncSettings(_:)), forControlEvents: UIControlEvents.ValueChanged)
switchMode.onTintColor = UIColor.tinylogMainColor()
cell.accessoryView = switchMode
cell.accessoryType = UITableViewCellAccessoryType.None
let userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()
let syncModeValue:String = userDefaults.objectForKey(TLIUserDefaults.kTLISyncMode as String) as! String
if syncModeValue == "on" {
switchMode.setOn(true, animated: false)
} else if syncModeValue == "off" {
switchMode.setOn(false, animated: false)
}
}
} else if indexPath.section == 1 {
if indexPath.row == 0 {
cell.textLabel?.text = "Font"
cell.detailTextLabel?.text = TLISettingsFontPickerViewController.textForSelectedKey() as? String
cell.detailTextLabel?.font = UIFont.tinylogFontOfSize(16.0, key: TLISettingsFontPickerViewController.selectedKey()!)
} else if indexPath.row == 1 {
cell.textLabel?.text = "Text Size"
cell.detailTextLabel?.font = UIFont.tinylogFontOfSize(16.0)
let userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()
let useSystemFontSize:String = userDefaults.objectForKey("kSystemFontSize") as! String
if useSystemFontSize == "on" {
cell.detailTextLabel?.text = "System Size"
} else {
let fontSize:Float = userDefaults.floatForKey("kFontSize")
let strFontSize = NSString(format: "%.f", fontSize)
cell.detailTextLabel?.text = strFontSize as String
}
}
} else if indexPath.section == 2 {
if indexPath.row == 0 {
cell.textLabel?.text = "Send Feedback"
} else if indexPath.row == 1 {
cell.textLabel?.text = "Rate Tinylog"
} else if indexPath.row == 2 {
cell.textLabel?.text = "Help"
}
} else if indexPath.section == 3 {
cell.textLabel?.text = "About"
}
}
// MARK: Actions
func toggleSyncSettings(sender: UISwitch) {
let mode:UISwitch = sender as UISwitch
let value:NSString = mode.on == true ? "on" : "off"
let userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(value, forKey: TLIUserDefaults.kTLISyncMode as String)
userDefaults.synchronize()
$.delay(0.2, closure: { () -> () in
let syncManager = TLISyncManager.sharedSyncManager()
if value == "on" {
syncManager.connectToSyncService(IDMICloudService, withCompletion: { (error) -> Void in
if error != nil {
if error.code == 1003 {
SVProgressHUD.showWithMaskType(SVProgressHUDMaskType.Black)
SVProgressHUD.setBackgroundColor(UIColor.tinylogMainColor())
SVProgressHUD.setForegroundColor(UIColor.whiteColor())
SVProgressHUD.setFont(UIFont.tinylogFontOfSize(14.0))
SVProgressHUD.showErrorWithStatus("You are not logged in to iCloud.Tap Settings > iCloud to login.")
}
}
})
} else if value == "off" {
if syncManager.canSynchronize() {
syncManager.disconnectFromSyncServiceWithCompletion({ () -> Void in
})
}
}
})
}
func close(sender:UIButton) {
self.dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 4
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44.0
}
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
header.textLabel!.font = UIFont.regularFontWithSize(16.0)
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "SYNC"
} else if section == 1 {
return "DISPLAY"
} else if section == 2 {
return "FEEDBACK"
} else if section == 3 {
return ""
}
return nil
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
} else if section == 1 {
return 2
} else if section == 2 {
return 3
} else if section == 3 {
return 1
}
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: settingsCellIdentifier)
configureCell(cell, indexPath: indexPath)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var viewController:UIViewController? = nil
if indexPath.section == 0 {
if indexPath.row == 0 {
}
} else if indexPath.section == 1 {
if indexPath.row == 0 {
viewController = TLISettingsFontPickerViewController()
} else if indexPath.row == 1 {
viewController = TLITextSizeViewController()
}
} else if indexPath.section == 2 {
if indexPath.row == 0 {
if MFMailComposeViewController.canSendMail() {
let infoDictionary:NSDictionary = NSBundle.mainBundle().infoDictionary!
let version:NSString = infoDictionary.objectForKey("CFBundleShortVersionString") as! NSString
let build:NSString = infoDictionary.objectForKey("CFBundleVersion") as! NSString
let deviceModel = TLIDeviceInfo.model()
let mailer:MFMailComposeViewController = MFMailComposeViewController()
mailer.mailComposeDelegate = self
mailer.setSubject("Tinylog \(version)")
mailer.setToRecipients(["feedback@tinylogapp.com"])
let systemVersion = UIDevice.currentDevice().systemVersion
let stringBody = "---\nApp: Tinylog \(version) (\(build))\nDevice: \(deviceModel) (\(systemVersion))"
mailer.setMessageBody(stringBody, isHTML: false)
let titleTextDict:NSDictionary = [NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: UIFont.mediumFontWithSize(16.0)]
mailer.navigationBar.titleTextAttributes = titleTextDict as? [String : AnyObject]
mailer.navigationBar.tintColor = UIColor.tinylogMainColor()
self.presentViewController(mailer, animated: true, completion: nil)
mailer.viewControllers.last?.navigationItem.title = "Tinylog"
} else {
let alert:UIAlertView = UIAlertView(title: "Tinylog", message: "Your device doesn't support this feature", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
} else if indexPath.row == 1 {
let path: NSURL = NSURL(string: "https://itunes.apple.com/gr/app/tinylog/id799267191?mt=8")!
UIApplication.sharedApplication().openURL(path)
} else if indexPath.row == 2 {
viewController = TLIHelpTableViewController()
}
} else if indexPath.section == 3 {
if indexPath.row == 0 {
viewController = TLIAboutViewController()
}
}
if viewController != nil {
self.navigationController?.pushViewController(viewController!
, animated: true)
}
}
// MARK: MFMailComposeViewControllerDelegate
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
switch result.rawValue {
case MFMailComposeResultCancelled.rawValue:
break;
case MFMailComposeResultSaved.rawValue:
break;
case MFMailComposeResultSent.rawValue:
break;
case MFMailComposeResultFailed.rawValue:
break;
default:
break;
}
self.dismissViewControllerAnimated(true, completion: { () -> Void in
})
}
}
|
mit
|
3d37a004b3ad33a9db583deba6434a3d
| 42.992933 | 204 | 0.598313 | 5.553078 | false | false | false | false |
benlangmuir/swift
|
test/SILOptimizer/optimize_keypath_objc.swift
|
19
|
969
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -primary-file %s -O -sil-verify-all -emit-sil >%t/output.sil
// RUN: %FileCheck %s < %t/output.sil
// REQUIRES: objc_interop
import Foundation
class Foo: NSObject {
@objc(doesIndeedHaveAKVCString) var hasKVCString: Int = 0
var noKVCString: Int? = 0
}
// CHECK-LABEL: sil hidden @{{.*}}21optimize_keypath_objc12hasKVCString
func hasKVCString() -> String? {
// CHECK-NOT: = keypath
// CHECK: string_literal utf8 "doesIndeedHaveAKVCString"
// CHECK-NOT: = keypath
// CHECK: [[RESULT:%.*]] = enum $Optional<String>, #Optional.some
return (\Foo.hasKVCString)._kvcKeyPathString
}
// CHECK-LABEL: sil hidden @{{.*}}21optimize_keypath_objc11noKVCString
func noKVCString() -> String? {
// CHECK-NOT: = keypath
// CHECK: [[RESULT:%.*]] = enum $Optional<String>, #Optional.none
return (\Foo.noKVCString)._kvcKeyPathString
}
|
apache-2.0
|
f22b8f0fb037bb2e8d5a2732d7e5ff7f
| 32.413793 | 122 | 0.660475 | 3.318493 | false | false | false | false |
JeffESchmitz/RideNiceRide
|
Pods/DATASource/Source/DATASource+NSFetchedResultsControllerDelegate.swift
|
3
|
9712
|
import UIKit
import CoreData
extension DATASource: NSFetchedResultsControllerDelegate {
public func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
if let tableView = self.tableView {
tableView.beginUpdates()
} else if let _ = self.collectionView {
self.sectionChanges = [NSFetchedResultsChangeType: IndexSet]()
self.objectChanges = [NSFetchedResultsChangeType: Set<IndexPath>]()
}
}
public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
self.cachedSectionNames.removeAll()
if let tableView = self.tableView {
let rowAnimationType = self.animations?[type] ?? .automatic
switch type {
case .insert:
tableView.insertSections(IndexSet(integer: sectionIndex), with: rowAnimationType)
break
case .delete:
tableView.deleteSections(IndexSet(integer: sectionIndex), with: rowAnimationType)
break
case .move, .update:
tableView.reloadSections(IndexSet(integer: sectionIndex), with: rowAnimationType)
break
}
} else if let _ = self.collectionView {
switch type {
case .insert, .delete:
if var indexSet = self.sectionChanges[type] {
indexSet.insert(sectionIndex)
self.sectionChanges[type] = indexSet
} else {
self.sectionChanges[type] = IndexSet(integer: sectionIndex)
}
break
case .move, .update:
break
}
}
}
public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
if let tableView = self.tableView {
let rowAnimationType = self.animations?[type] ?? .automatic
switch type {
case .insert:
if let newIndexPath = newIndexPath, let anObject = anObject as? NSManagedObject {
tableView.insertRows(at: [newIndexPath], with: rowAnimationType)
self.delegate?.dataSource?(self, didInsertObject: anObject, atIndexPath: newIndexPath)
}
break
case .delete:
if let indexPath = indexPath, let anObject = anObject as? NSManagedObject {
tableView.deleteRows(at: [indexPath], with: rowAnimationType)
self.delegate?.dataSource?(self, didDeleteObject: anObject, atIndexPath: indexPath)
}
break
case .update:
if let indexPath = indexPath {
if tableView.indexPathsForVisibleRows?.index(of: indexPath) != nil {
if let cell = tableView.cellForRow(at: indexPath) {
self.configure(cell, indexPath: indexPath)
}
if let anObject = anObject as? NSManagedObject {
self.delegate?.dataSource?(self, didUpdateObject: anObject, atIndexPath: indexPath)
}
}
}
break
case .move:
if let indexPath = indexPath, let newIndexPath = newIndexPath {
tableView.deleteRows(at: [indexPath], with: rowAnimationType)
tableView.insertRows(at: [newIndexPath], with: rowAnimationType)
if let anObject = anObject as? NSManagedObject {
self.delegate?.dataSource?(self, didMoveObject: anObject, fromIndexPath: indexPath, toIndexPath: newIndexPath)
}
}
break
}
} else if let _ = self.collectionView {
var changeSet = self.objectChanges[type] ?? Set<IndexPath>()
switch type {
case .insert:
if let newIndexPath = newIndexPath {
changeSet.insert(newIndexPath)
self.objectChanges[type] = changeSet
}
break
case .delete, .update:
if let indexPath = indexPath {
changeSet.insert(indexPath)
self.objectChanges[type] = changeSet
}
break
case .move:
if let indexPath = indexPath, let newIndexPath = newIndexPath {
// Workaround: Updating a UICollectionView element sometimes will trigger a .Move change
// where both indexPaths are the same, as a workaround if this happens, DATASource
// will treat this change as an .Update
if indexPath == newIndexPath {
changeSet.insert(indexPath)
self.objectChanges[.update] = changeSet
} else {
changeSet.insert(indexPath)
changeSet.insert(newIndexPath)
self.objectChanges[type] = changeSet
}
}
break
}
}
}
public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
if let tableView = self.tableView {
tableView.endUpdates()
} else if let _ = self.collectionView {
if let moves = self.objectChanges[.move] {
if moves.count > 0 {
var updatedMoves = Set<IndexPath>()
if let insertSections = self.sectionChanges[.insert], let deleteSections = self.sectionChanges[.delete] {
var generator = moves.makeIterator()
guard let fromIndexPath = generator.next() else { fatalError("fromIndexPath not found. Moves: \(moves), inserted sections: \(insertSections), deleted sections: \(deleteSections)") }
guard let toIndexPath = generator.next() else { fatalError("toIndexPath not found. Moves: \(moves), inserted sections: \(insertSections), deleted sections: \(deleteSections)") }
if deleteSections.contains((fromIndexPath as NSIndexPath).section) {
if insertSections.contains((toIndexPath as NSIndexPath).section) == false {
if var changeSet = self.objectChanges[.insert] {
changeSet.insert(toIndexPath)
self.objectChanges[.insert] = changeSet
} else {
self.objectChanges[.insert] = [toIndexPath]
}
}
} else if insertSections.contains((toIndexPath as NSIndexPath).section) {
if var changeSet = self.objectChanges[.delete] {
changeSet.insert(fromIndexPath)
self.objectChanges[.delete] = changeSet
} else {
self.objectChanges[.delete] = [fromIndexPath]
}
} else {
for move in moves {
updatedMoves.insert(move as IndexPath)
}
}
}
if updatedMoves.count > 0 {
self.objectChanges[.move] = updatedMoves
} else {
self.objectChanges.removeValue(forKey: .move)
}
}
}
if let collectionView = self.collectionView {
collectionView.performBatchUpdates({
if let deletedSections = self.sectionChanges[.delete] {
collectionView.deleteSections(deletedSections as IndexSet)
}
if let insertedSections = self.sectionChanges[.insert] {
collectionView.insertSections(insertedSections as IndexSet)
}
if let deleteItems = self.objectChanges[.delete] {
collectionView.deleteItems(at: Array(deleteItems))
}
if let insertedItems = self.objectChanges[.insert] {
collectionView.insertItems(at: Array(insertedItems))
}
if let reloadItems = self.objectChanges[.update] {
collectionView.reloadItems(at: Array(reloadItems))
}
if let moveItems = self.objectChanges[.move] {
var generator = moveItems.makeIterator()
guard let fromIndexPath = generator.next() else { fatalError("fromIndexPath not found. Move items: \(moveItems)") }
guard let toIndexPath = generator.next() else { fatalError("toIndexPath not found. Move items: \(moveItems)") }
collectionView.moveItem(at: fromIndexPath as IndexPath, to: toIndexPath as IndexPath)
}
}, completion: nil)
}
}
self.delegate?.dataSourceDidChangeContent?(self)
}
}
|
mit
|
ea26331069b6399911d72d9ad610b10f
| 47.80402 | 216 | 0.527286 | 6.389474 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.