repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
WickedColdfront/Slide-iOS | Pods/reddift/reddift/Network/Session+CAPTCHA.swift | 1 | 6686 | //
// Session+CAPTCHA.swift
// reddift
//
// Created by sonson on 2015/05/19.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
#if os(iOS) || os(tvOS)
import UIKit
public typealias CAPTCHAImage = UIImage
#elseif os(macOS)
import Cocoa
public typealias CAPTCHAImage = NSImage
#endif
/**
Parse simple string response for "/api/needs_captcha"
- parameter data: Binary data is returned from reddit.
- returns: Result object. If data is "true" or "false", Result object has boolean, otherwise error object.
*/
func data2Bool(_ data: Data) -> Result<Bool> {
if let decoded = String(data:data, encoding:.utf8) {
if decoded == "true" {
return Result(value:true)
} else if decoded == "false" {
return Result(value:false)
}
}
return Result(error:ReddiftError.needsCAPTCHAResponseIsInvalid as NSError)
}
/**
Parse simple string response for "/api/needs_captcha"
- parameter data: Binary data is returned from reddit.
- returns: Result object. If data is "true" or "false", Result object has boolean, otherwise error object.
*/
func data2Image(_ data: Data) -> Result<CAPTCHAImage> {
#if os(iOS) || os(tvOS)
let captcha = UIImage(data: data)
#elseif os(macOS)
let captcha = NSImage(data: data)
#endif
return Result(fromOptional: captcha, error: ReddiftError.imageOfCAPTCHAIsInvalid as NSError)
}
/**
Parse JSON contains "iden" for CAPTHA.
{"json": {"data": {"iden": "<code>"},"errors": []}}
- parameter json: JSON object, like above sample.
- returns: Result object. When parsing is succeeded, object contains iden as String.
*/
func idenJSON2String(_ json: JSONAny) -> Result<String> {
if let json = json as? JSONDictionary {
if let j = json["json"] as? JSONDictionary {
if let data = j["data"] as? JSONDictionary {
if let iden = data["iden"] as? String {
return Result(value:iden)
}
}
}
}
return Result(error:ReddiftError.identifierOfCAPTCHAIsMalformed as NSError)
}
extension Session {
/**
Check whether CAPTCHAs are needed for API methods that define the "captcha" and "iden" parameters.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
@discardableResult
public func checkNeedsCAPTCHA(_ completion: @escaping (Result<Bool>) -> Void) throws -> URLSessionDataTask {
guard let request = URLRequest.requestForOAuth(with: baseURL, path:"/api/needs_captcha", method:"GET", token:token)
else { throw ReddiftError.canNotCreateURLRequest as NSError }
let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<Bool> in
return Result(from: Response(data: data, urlResponse: response), optional:error)
.flatMap(response2Data)
.flatMap(data2Bool)
}
return executeTask(request, handleResponse: closure, completion: completion)
}
/**
Responds with an iden of a new CAPTCHA.
Use this endpoint if a user cannot read a given CAPTCHA, and wishes to receive a new CAPTCHA.
To request the CAPTCHA image for an iden, use /captcha/iden.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
@discardableResult
public func getIdenForNewCAPTCHA(_ completion: @escaping (Result<String>) -> Void) throws -> URLSessionDataTask {
let parameter = ["api_type":"json"]
guard let request = URLRequest.requestForOAuth(with: baseURL, path:"/api/new_captcha", parameter:parameter, method:"POST", token:token)
else { throw ReddiftError.canNotCreateURLRequest as NSError }
let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<String> in
return Result(from: Response(data: data, urlResponse: response), optional:error)
.flatMap(response2Data)
.flatMap(data2Json)
.flatMap(idenJSON2String)
}
return executeTask(request, handleResponse: closure, completion: completion)
}
/**
Request a CAPTCHA image for given an iden.
An iden is given as the captcha field with a BAD_CAPTCHA error, you should use this endpoint if you get a BAD_CAPTCHA error response.
Responds with a 120x50 image/png which should be displayed to the user.
The user's response to the CAPTCHA should be sent as captcha along with your request.
To request a new CAPTCHA, Session.getIdenForNewCAPTCHA.
- parameter iden: Code to get a new CAPTCHA. Use Session.getIdenForNewCAPTCHA.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
@discardableResult
public func getCAPTCHA(_ iden: String, completion: @escaping (Result<CAPTCHAImage>) -> Void) throws -> URLSessionDataTask {
guard let request = URLRequest.requestForOAuth(with: baseURL, path:"/captcha/" + iden, method:"GET", token:token)
else { throw ReddiftError.canNotCreateURLRequest as NSError }
let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<CAPTCHAImage> in
return Result(from: Response(data: data, urlResponse: response), optional:error)
.flatMap(response2Data)
.flatMap(data2Image)
}
return executeTask(request, handleResponse: closure, completion: completion)
}
/**
Request a CAPTCHA image
Responds with a 120x50 image/png which should be displayed to the user.
The user's response to the CAPTCHA should be sent as captcha along with your request.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func getCAPTCHA(_ completion: @escaping (Result<CAPTCHAImage>) -> Void) throws -> Void {
do {
try getIdenForNewCAPTCHA { (result) -> Void in
switch result {
case .failure(let error):
completion(Result(error: error))
case .success(let iden):
do {
try self.getCAPTCHA(iden, completion:completion)
} catch { completion(Result(error: error as NSError)) }
}
}
} catch { completion(Result(error: error as NSError)) }
}
}
| apache-2.0 | 8f679054b4c8bcf842e29f416f35d0a4 | 41.037736 | 143 | 0.659037 | 4.388707 | false | false | false | false |
chicio/RangeUISlider | RangeUISliderDemo/ChangeScaleProgrammaticViewController.swift | 1 | 8043 | //
// ChangeScaleProgrammaticViewController.swift
// Demo
//
// Created by Fabrizio Duroni on 03/05/2018.
// 2018 Fabrizio Duroni.
//
// swiftlint:disable function_body_length
import UIKit
import RangeUISlider
class ChangeScaleProgrammaticViewController: UIViewController, RangeUISliderDelegate {
private var rangeSlider: RangeUISlider!
private var minValueSelectedLabel: UILabel!
private var maxValueSelectedLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
rangeSlider = RangeUISlider(frame: CGRect(origin: CGPoint(x: 20, y: 20), size: CGSize(width: 100, height: 50)))
rangeSlider.translatesAutoresizingMaskIntoConstraints = false
rangeSlider.delegate = self
rangeSlider.scaleMinValue = 0 // If you don't set any value the default is 0
rangeSlider.scaleMaxValue = 100 // If you don't set any value the default is 1
rangeSlider.defaultValueLeftKnob = 10 // If the scale is the default one insert a value between 0 and 1
rangeSlider.defaultValueRightKnob = 75 // If the scale is the default one insert a value between 0 and 1
rangeSlider.rangeSelectedGradientColor1 = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
rangeSlider.rangeSelectedGradientColor2 = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
rangeSlider.rangeSelectedGradientStartPoint = CGPoint(x: 0, y: 0.5)
rangeSlider.rangeSelectedGradientEndPoint = CGPoint(x: 0, y: 1)
rangeSlider.rangeNotSelectedGradientColor1 = #colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1)
rangeSlider.rangeNotSelectedGradientColor2 = #colorLiteral(red: 0.09019608051, green: 0, blue: 0.3019607961, alpha: 1)
rangeSlider.rangeNotSelectedGradientStartPoint = CGPoint(x: 0, y: 0.5)
rangeSlider.rangeNotSelectedGradientEndPoint = CGPoint(x: 0, y: 1)
rangeSlider.barHeight = 20
rangeSlider.barCorners = 10
rangeSlider.leftKnobColor = #colorLiteral(red: 0.5725490451, green: 0, blue: 0.2313725501, alpha: 1)
rangeSlider.leftKnobWidth = 40
rangeSlider.leftKnobHeight = 40
rangeSlider.leftKnobCorners = 20
rangeSlider.rightKnobColor = #colorLiteral(red: 0.5725490451, green: 0, blue: 0.2313725501, alpha: 1)
rangeSlider.rightKnobWidth = 40
rangeSlider.rightKnobHeight = 40
rangeSlider.rightKnobCorners = 20
self.view.addSubview(rangeSlider)
minValueSelectedLabel = UILabel()
minValueSelectedLabel.translatesAutoresizingMaskIntoConstraints = false
minValueSelectedLabel.accessibilityIdentifier = "minValueSelected"
minValueSelectedLabel.text = "0.0"
self.view.addSubview(minValueSelectedLabel)
maxValueSelectedLabel = UILabel()
maxValueSelectedLabel.translatesAutoresizingMaskIntoConstraints = false
maxValueSelectedLabel.accessibilityIdentifier = "maxValueSelected"
maxValueSelectedLabel.text = "0.0"
self.view.addSubview(maxValueSelectedLabel)
// Setup slide with programmatic autolayout.
NSLayoutConstraint.activate([
NSLayoutConstraint(item: rangeSlider!,
attribute: .leading,
relatedBy: .equal,
toItem: self.view,
attribute: .leading,
multiplier: 1.0,
constant: 20),
NSLayoutConstraint(item: rangeSlider!,
attribute: .trailing,
relatedBy: .equal,
toItem: self.view,
attribute: .trailing,
multiplier: 1.0,
constant: -20),
NSLayoutConstraint(item: rangeSlider!,
attribute: .top,
relatedBy: .equal,
toItem: self.view,
attribute: .top,
multiplier: 1.0,
constant: 100),
NSLayoutConstraint(item: rangeSlider!,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 50),
NSLayoutConstraint(item: minValueSelectedLabel!,
attribute: .top,
relatedBy: .equal,
toItem: rangeSlider,
attribute: .bottom,
multiplier: 1.0,
constant: 20),
NSLayoutConstraint(item: minValueSelectedLabel!,
attribute: .leading,
relatedBy: .equal,
toItem: self.view,
attribute: .leading,
multiplier: 1.0,
constant: 20),
NSLayoutConstraint(item: minValueSelectedLabel!,
attribute: .trailing,
relatedBy: .equal,
toItem: self.view,
attribute: .trailing,
multiplier: 1.0,
constant: -20),
NSLayoutConstraint(item: minValueSelectedLabel!,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 30),
NSLayoutConstraint(item: maxValueSelectedLabel!,
attribute: .top,
relatedBy: .equal,
toItem: minValueSelectedLabel,
attribute: .bottom,
multiplier: 1.0,
constant: 20),
NSLayoutConstraint(item: maxValueSelectedLabel!,
attribute: .leading,
relatedBy: .equal,
toItem: self.view,
attribute: .leading,
multiplier: 1.0,
constant: 20),
NSLayoutConstraint(item: maxValueSelectedLabel!,
attribute: .trailing,
relatedBy: .equal,
toItem: self.view,
attribute: .trailing,
multiplier: 1.0,
constant: -20),
NSLayoutConstraint(item: maxValueSelectedLabel!,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 30)
])
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.rangeSlider.scaleMinValue = 50
self.rangeSlider.scaleMaxValue = 200
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.rangeSlider.changeLeftKnob(value: 60)
self.rangeSlider.changeRightKnob(value: 190)
}
}
func rangeChangeFinished(event: RangeUISliderChangeFinishedEvent) {
print("FINISH: \(event.slider.identifier)")
print("FINISH min: \(event.minValueSelected) - max: \(event.maxValueSelected)")
minValueSelectedLabel.text = event.minValueSelected.description
maxValueSelectedLabel.text = event.maxValueSelected.description
}
func rangeIsChanging(event: RangeUISliderChangeEvent) {
print("min: \(event.minValueSelected) - max: \(event.maxValueSelected)")
}
}
| mit | f52b83a559370e7f76a5489c29e82923 | 46.311765 | 138 | 0.546562 | 5.692144 | false | false | false | false |
akuraru/MuscleAssert-Objective-C | MuscleAssert/Swift/Differ/MUSDictionaryDiffer.swift | 1 | 1193 | //
// MuscleAssert.swift
// MuscleAssert
//
// Created by akuraru on 2016/12/17.
//
//
class MUSDictionaryDiffer: MUSCustomDiffer {
func match(left: Any, right: Any) -> Bool {
return false
}
func diff(left: Any, right: Any, path: String?, delegatge: MUSDeepDiffProtocol) -> [MUSDifference] {
return []
}
}
/*
#import "MUSDictionaryDiffer.h"
#import "MUSDifference.h"
NS_ASSUME_NONNULL_BEGIN
@implementation MUSDictionaryDiffer
- (Class)matchClass {
return [NSDictionary class];
}
- (NSArray<MUSDifference *> *)diff:(id)left right:(id)right path:(nullable NSString *)path delegatge:(id<MUSDeepDiffProtocol>)delegate {
NSSet *set = [NSSet setWithArray:[[right allKeys] arrayByAddingObjectsFromArray:[left allKeys]]];
NSMutableArray *result = [NSMutableArray array];
for (id key in set) {
id rightValue = right[key];
id leftValue = left[key];
NSString *nextPath = path ? [path stringByAppendingFormat:@".%@", [key description]] : [key description];
[result addObjectsFromArray:[delegate diff:rightValue left:leftValue path:nextPath]];
}
return [result copy];
}
@end
NS_ASSUME_NONNULL_END
*/
| mit | f1b8489a50b38d5aeda799c3e720422b | 24.382979 | 136 | 0.674769 | 3.60423 | false | false | false | false |
KeithPiTsui/Pavers | Pavers/Pavers.playground/Pages/ButtonStyles.xcplaygroundpage/Sources/UIButtonStyles.swift | 2 | 2599 | //
// UIButtonStyles.swift
// QWSDKUI
//
// Created by Keith on 21/10/2017.
// Copyright © 2017 Keith. All rights reserved.
//
import PaversUI
import PaversFRP
internal func qwColorTitleBorderButtonStyle(titleColor: UIColor,
borderColor: UIColor,
borderWidth: CGFloat = 1,
radius: CGFloat) -> (UIButton) -> UIButton {
return baseButtonStyle
>>> UIButton.lens.titleColor(forState: .normal) .~ titleColor
>>> UIButton.lens.backgroundColor(forState: .normal) .~ .clear
>>> UIButton.lens.titleColor(forState: .highlighted) .~ titleColor
>>> UIButton.lens.backgroundColor(forState: .highlighted) .~ .clear
>>> UIButton.lens.titleColor(forState: .disabled) .~ titleColor.withAlphaComponent(0.5)
>>> UIButton.lens.layer.borderColor .~ borderColor.cgColor
>>> UIButton.lens.layer.borderWidth .~ borderWidth
>>> roundedStyle(cornerRadius: radius)
}
internal let qwOrangeRedBorderButtonStyle = qwColorTitleBorderButtonStyle(titleColor: .qw_orange_red_100,
borderColor: .qw_orange_red_100,
borderWidth: 1,
radius: 10)
internal let qwGrayBorderButtonStyle = qwColorTitleBorderButtonStyle(titleColor: .qw_gray_100,
borderColor: .qw_gray_100,
borderWidth: 1,
radius: 10)
fileprivate let _orangeRedBackgroundWhiteTitleButtonStyle = baseButtonStyle
>>> UIButton.lens.titleColor(forState: .normal) .~ UIColor.white
>>> UIButton.lens.backgroundColor(forState: .normal) .~ UIColor.qw_orange_red_100
>>> UIButton.lens.titleColor(forState: .highlighted) .~ UIColor.init(white: 1.0, alpha: 0.5)
>>> UIButton.lens.backgroundColor(forState: .highlighted) .~ .qw_orange_red_100
>>> UIButton.lens.titleColor(forState: .disabled) .~ UIColor.white
>>> UIButton.lens.backgroundColor(forState: .disabled) .~ UIColor.qw_orange_red_100.withAlphaComponent(0.5)
internal let orangeRedBackgroundWhiteTitleButtonStyle = _orangeRedBackgroundWhiteTitleButtonStyle
>>> UIButton.lens.layer.borderColor .~ UIColor.qw_orange_red_100.cgColor
>>> UIButton.lens.layer.borderWidth .~ 1.0
>>> roundedStyle(cornerRadius: 4)
| mit | 84d4754aa9b374879d57225d2a7a82cf | 38.969231 | 109 | 0.591224 | 4.948571 | false | false | false | false |
swiftsanyue/TestKitchen | TestKitchen/TestKitchen/classes/ingredient(食材)/recommend(推荐)/main(主要模块)/foodCourse(食材课程)/controller/FoodCourseController.swift | 1 | 11120 | //
// FoodCourseController.swift
// TestKitchen
//
// Created by ZL on 16/11/3.
// Copyright © 2016年 zl. All rights reserved.
//
import UIKit
class FoodCourseController: KTCTabViewController {
//当前的选择了第几集
private var serialIndex: Int = 0
//id
var courseId:String?
//表格
private var tbView:UITableView?
//详情的数据
private var detailData : FoodCourseDetail?
//评论的数据
private var comment: FoodCourseComment?
//评论的分页
private var curPage = 1
//是否有更多
private var hasMore: Bool = true
//创建表格
func creatrTableView(){
automaticallyAdjustsScrollViewInsets = false
tbView = UITableView(frame: CGRectZero,style: .Plain)
tbView?.delegate = self
tbView?.dataSource = self
view.addSubview(tbView!)
//约束
tbView?.snp_makeConstraints(closure: {
[weak self]
(make) in
make.edges.equalTo(self!.view).inset(UIEdgeInsetsMake(64, 0, 0, 0))
})
}
override func viewDidLoad() {
super.viewDidLoad()
//创建表格
creatrTableView()
//下载详情的数据
downloadDetailData()
//下载评论
downloadComment()
}
//下载评论
func downloadComment(){
//methodName=CommentList&page=1&relate_id=22&size=10&token=&type=2&user_id=&version=4.32
var params = [String:String]()
params["methodName"]="CommentList"
params["page"]="\(curPage)"
params["relate_id"]=courseId!
params["size"]="10"
params["type"]="2"
let downloader = KTCDownloader()
downloader.dalegate = self
downloader.downloadType = .IngreFoodCourseComment
downloader.postWithUrl(kHostUrl, params: params)
}
//下载详情的数据
func downloadDetailData(){
if courseId != nil {
let params = ["methodName":"CourseSeriesView","series_id":"\(courseId!)"]
let downloader = KTCDownloader()
downloader.dalegate = self
downloader.downloadType = .IngreFoodCourseDetail
downloader.postWithUrl(kHostUrl, params: params)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension FoodCourseController:KTCDownloaderDelegate{
//下载失败的方法
func downloader(downloader:KTCDownloader,didFailWithError error:NSError){
}
//下载成功
func downloader(downloder:KTCDownloader,didFinishWithData data:NSData?){
if downloder.downloadType == .IngreFoodCourseDetail{
// let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
// print(str)
//详情
if let tmpData = data {
detailData = FoodCourseDetail.parseData(tmpData)
//显示数据
//刷新表格
tbView?.reloadData()
}
}else if downloder.downloadType == .IngreFoodCourseComment{
//评论
// let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
// print(str)
let tmpComment = FoodCourseComment.parseData(data!)
if curPage == 1{
//第一页
comment = tmpComment
}else{
//其他页
let array = NSMutableArray(array: (comment?.data?.data)!)
array.addObjectsFromArray((tmpComment.data?.data)!)
comment?.data?.data?=NSArray(array :array) as! Array<FoodCourseCommentDatail>
}
//刷新表格
tbView?.reloadData()
//判断是否有更多
if comment?.data?.data?.count < NSString(string: (comment?.data?.total)!).integerValue {
hasMore = true
}else{
hasMore = false
}
//加载跟多
addFooterView()
}
}
//添加加载更多的视图
func addFooterView() {
let fView = UIView(frame: CGRectMake(0,0,KScreenW,44))
fView.backgroundColor = UIColor.grayColor()
//显示文字
let label = UILabel(frame: CGRectMake(20,10,KScreenW-20*2,24))
label.textAlignment = .Center
if hasMore {
label.text = "下拉加载更多"
}else {
label.text = "没有更多了!"
}
fView.addSubview(label)
tbView?.tableFooterView = fView
}
}
//MARK: UITableView代理
extension FoodCourseController:UITableViewDelegate,UITableViewDataSource{
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var num = 0
if section == 0 {
//详情
if detailData != nil {
num = 3
}
}else if section == 1 {
//评论
if comment?.data?.data?.count > 0 {
num = (comment?.data?.data?.count)!
}
}
return num
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var h: CGFloat = 0
if indexPath.section == 0 {
if indexPath.row == 0 {
//视频播放
h=160
}else if indexPath.row == 1 {
//文字
let model = detailData?.data?.data![serialIndex]
h = FCSubjectCell.heightForSubjectCell(model!)
}else if indexPath.row == 2 {
//集数
h = FCSerialCell.heightForSerialCell((detailData?.data!.data!.count)!)
}
}else if indexPath.section == 1 {
//评论
h = 80
}
return h
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
if indexPath.row == 0 {
//视频
let cellId = "videoCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? FCVideoCell
if nil == cell {
cell = NSBundle.mainBundle().loadNibNamed("FCVideoCell", owner: nil, options: nil).last as? FCVideoCell
}
//显示数据
let serialModel = detailData?.data?.data![serialIndex]
cell?.cellModel = serialModel
//播放的闭包
cell?.playClosure = {
[weak self]
urlString in
IngreService.handleEvent(urlString, onViewController: self!)
}
cell?.selectionStyle = .None
return cell!
}else if indexPath.row == 1 {
//描述文字
let cellId = "subjectCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? FCSubjectCell
if nil == cell {
cell = NSBundle.mainBundle().loadNibNamed("FCSubjectCell", owner: nil, options: nil).last as? FCSubjectCell
}
//显示数据
let model = detailData?.data?.data![serialIndex]
cell?.cellModel = model
cell?.selectionStyle = .None
return cell!
}else if indexPath.row == 2 {
//集数
let cellId = "serialCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? FCSerialCell
if nil == cell {
cell = FCSerialCell(style: .Default, reuseIdentifier: cellId)
}
//显示数据
cell?.serialNum = detailData?.data?.data?.count
//设置选中的按钮
cell?.selectIndex = serialIndex
cell?.clickClosure = {
[weak self]
index in
self!.serialIndex = index
//刷新表格
self?.tbView?.reloadData()
// self!.tbView?.reloadSections(NSIndexSet(index: 0), withRowAnimation: .None)
}
cell?.selectionStyle = .None
return cell!
}
}else if indexPath.section == 1 {
//评论
let cellId = "commentCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? FCCommentCell
if nil == cell {
cell = NSBundle.mainBundle().loadNibNamed("FCCommentCell", owner: nil, options: nil).last as? FCCommentCell
}
//显示数据
let model = comment?.data?.data![indexPath.row]
cell?.model = model
cell?.selectionStyle = .None
return cell!
}
return UITableViewCell()
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if scrollView.contentOffset.y >= scrollView.contentSize.height - scrollView.bounds.size.height-10 {
//可以加载更多
if hasMore {
//加载下一页
curPage += 1
downloadComment()
}
}
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 1 {
if comment?.data?.data?.count > 0 {
return 60
}
}
return 0
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = NSBundle.mainBundle().loadNibNamed("FCCommentHeader", owner: nil, options: nil).last as! FCCommentHeader
//显示数据
headerView.config((comment?.data?.total)!)
return headerView
}
}
| mit | b5aa638512f8da494ac371775ebdf891 | 29.081461 | 131 | 0.485666 | 5.577604 | false | false | false | false |
skylib/SnapImagePicker | SnapImagePicker/ImagePicker/Entity Gateway/SnapImagePickerEntityGateway.swift | 1 | 3966 | import UIKit
import Photos
class SnapImagePickerEntityGateway {
fileprivate weak var interactor: SnapImagePickerInteractorProtocol?
weak var imageLoader: ImageLoaderProtocol?
fileprivate var requests = [Int: PHImageRequestID]()
init(interactor: SnapImagePickerInteractorProtocol, imageLoader: ImageLoaderProtocol?) {
self.interactor = interactor
self.imageLoader = imageLoader
}
}
extension SnapImagePickerEntityGateway: SnapImagePickerEntityGatewayProtocol {
func fetchAlbum(_ type: AlbumType) {
if let fetchResult = imageLoader?.fetchAssetsFromCollectionWithType(type) , fetchResult.count > 0,
let asset = fetchResult.firstObject {
let _ = imageLoader?.loadImageFromAsset(asset, isPreview: false, withPreviewSize: CGSize.zero) {
[weak self] (image: SnapImagePickerImage) in
assert(Thread.isMainThread)
self?.interactor?.loadedAlbum(type, withMainImage: image, albumSize: fetchResult.count)
}
}
}
fileprivate func loadAssetsFromAlbum(_ type: AlbumType, inRange range: CountableRange<Int>) -> [Int: PHAsset] {
var assets = [Int: PHAsset]()
if let fetchResult = imageLoader?.fetchAssetsFromCollectionWithType(type) {
let start = max(range.lowerBound, 0)
let end = min(range.endIndex, fetchResult.count)
if start < end {
for i in start..<end {
let asset = fetchResult.object(at: i)
assets[i] = asset
}
}
}
return assets
}
func fetchAlbumImagesFromAlbum(_ type: AlbumType, inRange range: CountableRange<Int>, withTargetSize targetSize: CGSize) {
let assets = loadAssetsFromAlbum(type, inRange: range)
let fetchIds = imageLoader?.loadImagesFromAssets(assets, withTargetSize: targetSize) {
[weak self] (results) in
DispatchQueue.main.async {
self?.interactor?.loadedAlbumImagesResult(results, fromAlbum: type)
}
if var tempRequests = self?.requests {
for (index, _) in results {
tempRequests.removeValue(forKey: index)
}
self?.requests = tempRequests
}
}
if let fetchIds = fetchIds {
for (index, id) in fetchIds {
requests[index] = id
}
}
}
func deleteImageRequestsInRange(_ range: CountableRange<Int>) {
var requestIds = [PHImageRequestID]()
for i in range {
if let id = requests[i] {
requestIds.append(id)
requests[i] = nil
}
}
imageLoader?.deleteRequests(requestIds)
}
func fetchMainImageFromAlbum(_ type: AlbumType, atIndex index: Int) {
if let fetchResult = imageLoader?.fetchAssetsFromCollectionWithType(type),
fetchResult.count > index {
let asset = fetchResult.object(at: index)
let _ = imageLoader?.loadImageFromAsset(asset, isPreview: false, withPreviewSize: CGSize(width: SnapImagePickerTheme.maxImageSize, height: SnapImagePickerTheme.maxImageSize)) {
[weak self] (image: SnapImagePickerImage) in
DispatchQueue.main.async {
self?.interactor?.loadedMainImage(image, fromAlbum: type)
}
}
}
}
func fetchImageWithLocalIdentifier(_ localIdentifier: String, fromAlbum type: AlbumType) {
imageLoader?.loadImageWithLocalIdentifier(localIdentifier) {
[weak self] (image) in
DispatchQueue.main.async {
self?.interactor?.loadedMainImage(image, fromAlbum: type)
}
}
}
}
| bsd-3-clause | 9a034fcc525244251614eb1d960a6d67 | 36.771429 | 188 | 0.58825 | 5.345013 | false | false | false | false |
jfosterdavis/Charles | Charles/Level.swift | 1 | 1951 | //
// Level.swift
// Charles
//
// Created by Jacob Foster Davis on 5/27/17.
// Copyright © 2017 Zero Mu, LLC. All rights reserved.
//
import Foundation
import UIKit
/**
A Level object contains information about a certain level of difficulty
- Objects:
- level: an int of the level this is in the game
- name: a string describing the level
- xPRequired: amount of XP required to complete the level
- successThreshold: Float between 0 and 1 denoting percent of a perfect score that must be achieved to earn XP in this level
- punishThreshold: float between 0 and 1 denoting the percent of a perfect score below or at which the user is penalized XP
- canBeLost: Bool if the level can be lost if the user looses too much XP from higher levels
- eligiblePredefinedObjectives an array of elligible UI colors for this level [[UIColor]]
- eligibleRandomColorPrecision? int describing how precise the colors can be. nil if won't be using this
*/
class Level: NSObject {
var level: Int
var name: String
var xPRequired: Int //an array of phrase objects
var successThreshold: Float
var punishThreshold: Float
var canBeLost: Bool //radius of the corners on top
var eligiblePredefinedObjectives: [[UIColor]]?
var eligibleRandomColorPrecision: Int?
// MARK: Initializers
init(level: Int, name: String, xPRequired: Int, successThreshold: Float, punishThreshold: Float, canBeLost: Bool, eligiblePredefinedObjectives: [[UIColor]]?, eligibleRandomColorPrecision: Int? = nil) {
self.level = level
self.name = name
self.xPRequired = xPRequired
self.successThreshold = successThreshold
self.punishThreshold = punishThreshold
self.canBeLost = canBeLost
self.eligiblePredefinedObjectives = eligiblePredefinedObjectives
self.eligibleRandomColorPrecision = eligibleRandomColorPrecision
super.init()
}
}
| apache-2.0 | d71636609c4941844f81bba3501c264c | 37.235294 | 205 | 0.720513 | 4.304636 | false | false | false | false |
werediver/parser | Sources/CLI/LSum.swift | 2 | 1831 | import Foundation
import ParserCore
// START <- LSUM END
//
// LSUM <- LSUM PLUS NUM
// / NUM
//
// NUM <- [0-9]+
//
// PLUS <- "+"
final class LSum {
let left: LSum?
let right: Num
init(left: LSum?, right: Num) {
self.left = left
self.right = right
}
}
final class Num {
let value: Int
init(value: Int) {
self.value = value
}
}
final class Plus {}
enum LSumParser<Core: SomeCore> where
Core.Source == String
{
typealias Parser<Symbol> = GenericParser<Core, Symbol>
static func start() -> Parser<LSum> {
return lsum()
.flatMap { lsum in
Core.end()
.map(const(lsum))
}
}
static func lsum() -> Parser<LSum> {
return GenericParser { this, _ in
Core.oneOf(tag: "LSum",
this.flatMap { lsum in
LSumParser.plus()
.flatMap { _ in LSumParser.num() }
.map { num in
LSum(left: lsum, right: num)
}
},
LSumParser.num()
.map { num in LSum(left: nil, right: num) }
)
}
}
static func num() -> Parser<Num> {
return Core.string(charset: digits)
.attemptMap(tag: "Num") { text in
Int(text)
.map(Num.init)
.map(Either.right)
?? .left(Mismatch(reason: "cannot convert \(String(reflecting: text)) to integer number"))
}
}
static func plus() -> Parser<Plus> {
return Core.subseq("+").map(tag: "Plus") { _ in Plus() }
}
}
private let digits = CharacterSet(charactersIn: "0123456789")
| mit | 5fb72b33c6c79fb1a42f73030ab868ab | 21.8875 | 107 | 0.457127 | 4.006565 | false | false | false | false |
iAugux/Weboot | Weboot/WBTimelineTableViewCell.swift | 1 | 12301 | //
// WeiboTableViewswift
// iAugus
//
// Created by Augus on 5/11/15.
// Copyright (c) 2015 Augus. All rights reserved.
//
import UIKit
class WBTimelineTableViewCell: AUSTinderSwipeCell {
@IBOutlet weak var userImage: UIImageView!{
didSet{
userImage.layer.cornerRadius = 20.0
userImage.clipsToBounds = true
}
}
@IBOutlet weak var screenName: UILabel!{
didSet{
screenName.text = nil
}
}
@IBOutlet weak var originalWeiboText: UILabel!{
didSet{
originalWeiboText.text = nil
}
}
@IBOutlet weak var createdDate: UILabel!{
didSet{
createdDate.text = nil
}
}
@IBOutlet weak var weiboSource: UILabel!{
didSet{
weiboSource.text = nil
}
}
@IBOutlet var retweetedWeiboText: UILabel!{
didSet{
retweetedWeiboText.text = nil
}
}
@IBOutlet var imageViewContainer: UIScrollView!
@IBOutlet var imageViewContainerWidth: NSLayoutConstraint!
@IBOutlet var imageViewContainerHeight: NSLayoutConstraint!
@IBOutlet var retweetedContainerHeight: NSLayoutConstraint!{
didSet{
retweetedContainerHeight.constant = 0
}
}
@IBOutlet var retweetedImageContainer: UIScrollView!
@IBOutlet var retweetedImageContainerHeight: NSLayoutConstraint!
@IBOutlet var retweetedImageContainerWidth: NSLayoutConstraint!
@IBOutlet var commentButton: UIButton!
@IBOutlet var repostButton: UIButton!
@IBOutlet var repostsCount: UILabel!{
didSet{
repostsCount.text = nil
}
}
@IBOutlet var commentsCount: UILabel!{
didSet{
commentsCount.text = nil
}
}
// var images = [UIImageView](count: 9, repeatedValue: UIImageView())
var images: [UIImageView] = []
var retweetedImages: [UIImageView] = []
var imagesBrowser: [SKPhoto] = []
var cellHeight: CGFloat!
override func awakeFromNib() {
super.awakeFromNib()
self.preservesSuperviewLayoutMargins = false
self.separatorInset = UIEdgeInsetsZero
self.layoutMargins = UIEdgeInsetsZero
initOriginalWeiboImages()
initRetweetedWeiboImages()
}
override func layoutSubviews() {
super.layoutSubviews()
}
@IBAction func commentButton(sender: UIButton) {
print("comment tapped")
}
@IBAction func repostButton(sender: UIButton) {
print("repost tapped")
}
func initOriginalWeiboImages(){
imageViewContainer.hidden = true
imageViewContainerHeight.constant = 0
// if set scrollsToTop available , it can not be back to top when you tap status bar
imageViewContainer.scrollsToTop = false
imageViewContainer.showsHorizontalScrollIndicator = false
// set image array
for index in 0 ..< 9 {
images.append(UIImageView())
let image_x: CGFloat = IMAGE_LEADING_SPACE + (kOriginalWeiboImageWidth + 8) * CGFloat(index)
images[index].frame = CGRectMake(image_x, 0, kOriginalWeiboImageWidth, kOriginalWeiboImageWidth)
images[index].contentMode = UIViewContentMode.ScaleAspectFill
images[index].clipsToBounds = true
imageViewContainer.addSubview(images[index])
}
}
func initRetweetedWeiboImages(){
retweetedImageContainer.hidden = true
retweetedImageContainerHeight.constant = 0
retweetedImageContainer.scrollsToTop = false
retweetedImageContainer.showsHorizontalScrollIndicator = false
for index in 0 ..< 9 {
retweetedImages.append(UIImageView())
let image_x: CGFloat = IMAGE_LEADING_SPACE + (kRetweetedWeiboImageWidth + 8) * CGFloat(index)
retweetedImages[index].frame = CGRectMake(image_x, 0, kRetweetedWeiboImageWidth, kRetweetedWeiboImageWidth)
retweetedImages[index].contentMode = UIViewContentMode.ScaleAspectFill
retweetedImages[index].clipsToBounds = true
retweetedImageContainer.addSubview(retweetedImages[index])
}
}
func loadDataToCell(status: Status) {
var totalHeight:CGFloat = WEIBO_HEADER_HEIGHT
// MARK: - original weibo data source
// set weibo text
originalWeiboText.text = status.text
let originalTextSize = originalWeiboText.ausGetLabelSize()
totalHeight += originalTextSize.height + 16.0
createdDate?.text = status.statusTimeString()
weiboSource?.text = status.source
screenName?.text = status.user.screenName
repostsCount?.text = "\(status.repostsCount)"
commentsCount?.text = "\(status.commentsCount)"
// set user image
if let userImageUrl: NSURL = NSURL(string: status.user.profileImageUrl){
userImage.kf_setImageWithURL(userImageUrl, placeholderImage: UIImage(named: "profile_image_placeholder"))
}
// set original weibo images
let numberOfImages = status.images.count
for i in 0..<9 {
images[i].hidden = true
}
if numberOfImages == 0 {
imageViewContainer.hidden = true
imageViewContainerHeight.constant = 0
}
else{
totalHeight += kOriginalWeiboImageWidth + 8.0
imageViewContainer.hidden = false
imageViewContainerHeight.constant = kOriginalWeiboImageWidth
// back to default position when imageViewContainer appears again
imageViewContainer.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
let widthOfImageContainer: CGFloat = (kOriginalWeiboImageWidth + 8) * CGFloat(numberOfImages) + IMAGE_LEADING_SPACE
var imageOfBrowser: SKPhoto
self.imagesBrowser.removeAll()
for i in 0 ..< numberOfImages {
images[i].hidden = false
images[i].tag = i
if widthOfImageContainer < UIScreen.screenWidth() {
imageViewContainerWidth.constant = widthOfImageContainer - 8.0
imageViewContainer.scrollEnabled = false
}else{
imageViewContainerWidth.constant = UIScreen.screenWidth()
imageViewContainer.scrollEnabled = true
}
imageViewContainer.contentSize = CGSizeMake(widthOfImageContainer , kOriginalWeiboImageWidth)
let statusImage = status.images[i] as! StatusImage
let statusImageUrl = NSURL(string: statusImage.thumbnailImageUrl)
images[i].kf_setImageWithURL(statusImageUrl!, placeholderImage: UIImage(named: "image_holder"))
let recognizer = UITapGestureRecognizer(target: self, action: #selector(WBTimelineTableViewCell.imageDidTap(_:)))
images[i].addGestureRecognizer(recognizer)
images[i].userInteractionEnabled = true
imageOfBrowser = SKPhoto.photoWithImageURL(statusImage.originalImageUrl)
imageOfBrowser.shouldCachePhotoURLImage = true
self.imagesBrowser.append(imageOfBrowser)
}
}
// MARK: - retweeted Weibo data source
var retweetedViewHeight: CGFloat = 0.0
if let retweetedStatus = status.retweetedStatus{
// set retweeted weibo text
if let retweetedWeiboText = status.retweetedStatus?.text{
var text = retweetedWeiboText
// carefully: when original weibo has been deleted, there is no user !!! Once you call user, it will crash.
if let retweetedWeiboUserName = retweetedStatus.user?.screenName {
text = "@\(retweetedWeiboUserName): \(retweetedWeiboText)"
}else{
text = "\(retweetedWeiboText)"
}
let retweetedLabel = self.retweetedWeiboText
retweetedLabel.text = text
let textSize = retweetedLabel.ausGetLabelSize()
retweetedViewHeight += textSize.height + 16.0
}
// set retweeted weibo images
let numberOfRetweetedImages = retweetedStatus.images.count
for i in 0..<9 {
retweetedImages[i].hidden = true
}
if numberOfRetweetedImages == 0 {
retweetedImageContainer.hidden = true
retweetedImageContainerHeight.constant = 0
retweetedContainerHeight.constant = retweetedViewHeight
}
else{
retweetedViewHeight += kRetweetedWeiboImageWidth + 8.0
retweetedContainerHeight.constant = retweetedViewHeight
retweetedImageContainer.hidden = false
retweetedImageContainerHeight.constant = kRetweetedWeiboImageWidth
// back to default position when imageViewContainer appears again
retweetedImageContainer.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
let widthOfRetweetedImageContainer: CGFloat = (kRetweetedWeiboImageWidth + 8) * CGFloat(numberOfRetweetedImages) + IMAGE_LEADING_SPACE
var imageOfBrowser: SKPhoto
self.imagesBrowser.removeAll()
for i in 0 ..< numberOfRetweetedImages {
retweetedImages[i].hidden = false
retweetedImages[i].tag = i
if widthOfRetweetedImageContainer < UIScreen.screenWidth() {
retweetedImageContainerWidth.constant = widthOfRetweetedImageContainer - 8.0
retweetedImageContainer.scrollEnabled = false
}else{
retweetedImageContainerWidth.constant = UIScreen.screenWidth()
retweetedImageContainer.scrollEnabled = true
}
retweetedImageContainer.contentSize = CGSizeMake(widthOfRetweetedImageContainer, kRetweetedWeiboImageWidth)
let retweetedStatusImage = retweetedStatus.images[i] as! StatusImage
let retweetedStatusImageUrl = NSURL(string: retweetedStatusImage.thumbnailImageUrl)
retweetedImages[i].kf_setImageWithURL(retweetedStatusImageUrl!, placeholderImage: UIImage(named: "image_holder"))
let recognizer = UITapGestureRecognizer(target: self, action: #selector(WBTimelineTableViewCell.imageDidTap(_:)))
retweetedImages[i].addGestureRecognizer(recognizer)
retweetedImages[i].userInteractionEnabled = true
imageOfBrowser = SKPhoto.photoWithImageURL(retweetedStatusImage.originalImageUrl)
imageOfBrowser.shouldCachePhotoURLImage = true
self.imagesBrowser.append(imageOfBrowser)
}
}
}
else{
retweetedViewHeight = 0.0
retweetedContainerHeight.constant = 0
retweetedWeiboText.text = nil
retweetedImageContainerHeight.constant = 0
for object in retweetedImages{
object.hidden = true
}
}
cellHeight = totalHeight + retweetedViewHeight + 21.0 + 8.0
}
func imageDidTap(sender: UITapGestureRecognizer) {
print("image did tap")
let browser = SKPhotoBrowser(photos: imagesBrowser)
browser.initializePageIndex(sender.view!.tag)
UIApplication.topMostViewController()?.presentViewController(browser, animated: true, completion: nil)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 3e506d3dda585b354c6ab507700ff6bc | 38.426282 | 150 | 0.607999 | 5.7697 | false | false | false | false |
maximkhatskevich/MKHSequence | Sources/OperationFlow/Core.swift | 2 | 2308 | //
// Core.swift
// MKHOperationFlow
//
// Created by Maxim Khatskevich on 2/23/17.
// Copyright © 2017 Maxim Khatskevich. All rights reserved.
//
import Foundation
//===
extension OFL
{
struct Core
{
let name: String
let targetQueue: OperationQueue
let maxRetries: UInt // how many times to retry on failure
fileprivate(set)
var operations: [GenericOperation]
fileprivate(set)
var completion: GenericCompletion?
fileprivate(set)
var failureHandlers: [FailureGeneric]
}
}
//===
extension OFL.Core
{
mutating
func first<Output>(
_ op: @escaping OFL.ManagingOperationNoInput<Output>
) // -> Connector<Output>
{
operations.removeAll()
//===
operations.append { flow, _ in try op(flow) }
}
//===
mutating
func then<Input, Output>(
_ op: @escaping OFL.ManagingOperation<Input, Output>
)
{
operations.append { flow, input in
guard
let typedInput = input as? Input
else
{
throw
InvalidInputType(
expected: Input.self,
actual: type(of: input))
}
//===
return try op(flow, typedInput)
}
}
//===
mutating
func onFailure(
_ handler: @escaping OFL.FailureGeneric
)
{
failureHandlers.append(handler)
}
mutating
func onFailure(
_ handlers: [OFL.FailureGeneric]
)
{
failureHandlers.append(contentsOf: handlers)
}
//===
mutating
func finally<Input>(
_ handler: @escaping OFL.ManagingCompletion<Input>
)
{
completion = { flow, input in
if
let typedInput = input as? Input
{
return handler(flow, typedInput)
}
else
{
throw
InvalidInputType(
expected: Input.self,
actual: type(of: input))
}
}
}
}
| mit | 7f0f3caf28b0dbdbca7749cd1c46abd9 | 19.236842 | 66 | 0.468574 | 5.037118 | false | false | false | false |
herrkaefer/CaseAssistant | CaseAssistant/RecordTextInputTableViewCell.swift | 1 | 1489 | //
// RecordTextInputTableViewCell.swift
// CaseAssistant
//
// Created by HerrKaefer on 15/5/7.
// Copyright (c) 2015年 HerrKaefer. All rights reserved.
//
import UIKit
class RecordTextInputTableViewCell: UITableViewCell {
var customText: String? {
didSet {
customTextView.text = customText
}
}
func evokeKeyboard() {
customTextView.becomeFirstResponder()
}
// func textViewKeyboardAccessoryDoneButtonPressed() {
// customTextView.resignFirstResponder()
// }
@IBOutlet weak var customTextView: UITextView! {
didSet {
customTextView.layer.borderColor = CaseApp.borderColor.cgColor
customTextView.layer.cornerRadius = 5.0
customTextView.layer.borderWidth = 0.5
// set accessory view to show with keyboard, with a "done" button (dismiss keyboard)
// let keyboardToolbar = UIToolbar(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 36))
// let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
// let doneButton = UIBarButtonItem(title: "完成", style: UIBarButtonItemStyle.Plain, target: self, action: "textViewKeyboardAccessoryDoneButtonPressed")
// keyboardToolbar.setItems([flexibleSpace, doneButton], animated: true)
// customTextView.inputAccessoryView = keyboardToolbar
}
}
}
| mpl-2.0 | 7cdbc3d18de3b85dbfecfd8881f1797d | 33.488372 | 162 | 0.670263 | 4.846405 | false | false | false | false |
CoderST/XMLYDemo | XMLYDemo/XMLYDemo/Class/Home/Controller/SubViewController/ListViewController/Model/ListMainModel.swift | 1 | 654 | //
// ListMainModel.swift
// XMLYDemo
//
// Created by xiudou on 2016/12/27.
// Copyright © 2016年 CoderST. All rights reserved.
//
import UIKit
class ListMainModel: BaseModel{
var count : Int64 = 0
var title : String = ""
var list : [ListModel] = [ListModel]()
override func setValue(_ value: Any?, forKey key: String) {
if key == "list"{
guard let dictArray = value as? [[String : AnyObject]] else { return }
for dict in dictArray{
list.append(ListModel(dict: dict))
}
}else{
super.setValue(value, forKey: key)
}
}
}
| mit | d027461e53ac0d547461c9d1e739674d | 22.25 | 82 | 0.548387 | 4.018519 | false | false | false | false |
huonw/swift | test/SILOptimizer/definite-init-wrongscope.swift | 3 | 1592 | // RUN: %target-swift-frontend -primary-file %s -Onone -emit-sil -Xllvm \
// RUN: -sil-print-after=raw-sil-inst-lowering -Xllvm \
// RUN: -sil-print-only-functions=$S3del1MC4fromAcA12WithDelegate_p_tKcfc \
// RUN: -Xllvm -sil-print-debuginfo -o /dev/null 2>&1 | %FileCheck %s
public protocol DelegateA {}
public protocol DelegateB {}
public protocol WithDelegate
{
var delegate: DelegateA? { get }
func f() throws -> Int
}
public enum Err: Swift.Error {
case s(Int)
}
public class C {}
public class M {
let field: C
var value : Int
public init(from d: WithDelegate) throws {
guard let delegate = d.delegate as? DelegateB
else { throw Err.s(0) }
self.field = C()
let i: Int = try d.f()
value = i
}
}
// Make sure the expanded sequence gets the right scope.
// CHECK: [[I:%.*]] = integer_literal $Builtin.Int2, 1, loc {{.*}}:20:12, scope 2
// CHECK: [[V:%.*]] = load [trivial] %2 : $*Builtin.Int2, loc {{.*}}:20:12, scope 2
// CHECK: [[OR:%.*]] = builtin "or_Int2"([[V]] : $Builtin.Int2, [[I]] : $Builtin.Int2) : $Builtin.Int2, loc {{.*}}:20:12, scope 2
// CHECK: store [[OR]] to [trivial] %2 : $*Builtin.Int2, loc {{.*}}:20:12, scope 2
// CHECK: store %{{.*}} to [init] %{{.*}} : $*C, loc {{.*}}:23:20, scope 2
// Make sure the dealloc_stack gets the same scope of the instructions surrounding it.
// CHECK: destroy_addr %0 : $*WithDelegate, loc {{.*}}:26:5, scope 2
// CHECK: dealloc_stack %2 : $*Builtin.Int2, loc {{.*}}:20:12, scope 2
// CHECK: throw %{{.*}} : $Error, loc {{.*}}:20:12, scope 2
| apache-2.0 | 66a9896817f58ff403d0b14a22c18d3f | 37.829268 | 131 | 0.593593 | 3.152475 | false | false | false | false |
devandroid/iOS-Swift-Circular-Progress-View | CircularProgressView/DataLoader.swift | 1 | 3875 | //
// DataLoader.swift
// CircularProgressView
//
// Created by Wagner Truppel on 01/05/2015.
// Copyright (c) 2015 Wagner Truppel. All rights reserved.
//
import Foundation
import CoreGraphics
protocol DataLoaderDelegate
{
func dataLoader(dataLoader: DataLoader, didUpdateDataWithPercentValue value: CGFloat)
func dataLoaderDidFinishLoadingData(dataLoader: DataLoader)
}
class DataLoader
{
let loaderIndexPath: NSIndexPath
var loaderData: DataItem?
static func dataSize() -> Int
{ return data.count }
static func loadDataForIndexPath(indexPath: NSIndexPath, delegate: DataLoaderDelegate)
{
let dataLoader = DataLoader(indexPath: indexPath, delegate: delegate)
dataLoader.loadData()
}
private init(indexPath: NSIndexPath, delegate: DataLoaderDelegate)
{
loaderIndexPath = indexPath
self.delegate = delegate
DataLoader.dataLoaders[indexPath] = self
}
private static var dataLoaders = [NSIndexPath: DataLoader]()
private var delegate: DataLoaderDelegate?
private func loadData()
{ dispatch_async(globalConcurrentBackgroundQueue) { self.countUp() } }
private func countUp()
{
let maxCount = Int(CGFloat.randomUniform(a: 300, b: 1000))
for count in 0..<maxCount
{
dispatch_sync(globalSerialMainQueue) {
let value = CGFloat(count)/CGFloat(maxCount)
self.delegate?.dataLoader(self, didUpdateDataWithPercentValue: value)
}
}
dispatch_sync(globalSerialMainQueue) {
self.loaderData = data[self.loaderIndexPath.row]
self.delegate?.dataLoaderDidFinishLoadingData(self)
}
DataLoader.dataLoaders[self.loaderIndexPath] = nil
}
}
let data: [DataItem] = {
var da = [DataItem]()
da.append(DataItem("arya", "Arya S.", "[email protected]"))
da.append(DataItem("brienne", "Brienne of T.", "[email protected]"))
da.append(DataItem("cersei", "Cersei L.", "[email protected]"))
da.append(DataItem("danny", "Danny T.", "[email protected]"))
da.append(DataItem("ned", "Eddard S.", "[email protected]"))
da.append(DataItem("jaime", "Jaime L.", "[email protected]"))
da.append(DataItem("snow", "Jon S.", "[email protected]"))
da.append(DataItem("margie", "Margaery T.", "[email protected]"))
da.append(DataItem("littlefinger", "Petyr B.", "[email protected]"))
da.append(DataItem("theon", "Theon G.", "[email protected]"))
return da
}()
class DataItem
{
let photoName: String!
let personName: String!
let personEmail: String!
init(_ photoName: String, _ personName: String, _ personEmail: String)
{
self.photoName = photoName
self.personName = personName
self.personEmail = personEmail
}
}
// GCD utils
var globalSerialMainQueue: dispatch_queue_t!
{ return dispatch_get_main_queue() }
var globalConcurrentBackgroundQueue: dispatch_queue_t!
{ return dispatch_get_global_queue(Int(QOS_CLASS_BACKGROUND.value), 0) }
func dispatchTimeFromNowInSeconds(delayInSeconds: Double) -> dispatch_time_t!
{ return dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC))) }
// CG extensions
extension CGFloat
{
// Returns a uniformly distributed random CGFloat in the range [0, 1].
public static var randomUniform01: CGFloat
{ return CGFloat(arc4random_uniform(UInt32.max)) / CGFloat(UInt32.max - 1) }
// Returns a uniformly distributed random CGFloat in the range [min(a,b), max(a,b)].
public static func randomUniform(#a: CGFloat, b: CGFloat) -> CGFloat
{ return a + (b - a) * CGFloat.randomUniform01 }
// Returns a uniformly distributed random boolean.
public static var randomBool: Bool
{ return CGFloat.randomUniform01 <= 0.5 }
}
| mit | 23288db92cdf3c585bed0b244fc47126 | 29.511811 | 90 | 0.677161 | 3.848064 | false | false | false | false |
peaks-cc/iOS11_samplecode | chapter_13/02_MetalShaderColorFill/MetalShaderColorFill/ViewController.swift | 1 | 3359 | //
// ViewController.swift
// MetalShaderColorFill
//
// Created by Shuichi Tsutsumi on 2017/09/10.
// Copyright © 2017 Shuichi Tsutsumi. All rights reserved.
//
import UIKit
import MetalKit
class ViewController: UIViewController, MTKViewDelegate {
private let device = MTLCreateSystemDefaultDevice()!
private var commandQueue: MTLCommandQueue!
private let vertexData: [Float] = [
-1, -1, 0, 1,
1, -1, 0, 1,
-1, 1, 0, 1,
1, 1, 0, 1
]
private var vertexBuffer: MTLBuffer!
private var renderPipeline: MTLRenderPipelineState!
private let renderPassDescriptor = MTLRenderPassDescriptor()
@IBOutlet private weak var mtkView: MTKView!
override func viewDidLoad() {
super.viewDidLoad()
// Metalのセットアップ
setupMetal()
//
makeBuffers()
//
makePipeline()
//
mtkView.enableSetNeedsDisplay = true
// ビューの更新依頼 → draw(in:)が呼ばれる
mtkView.setNeedsDisplay()
}
private func setupMetal() {
// MTLCommandQueueを初期化
commandQueue = device.makeCommandQueue()
// MTKViewのセットアップ
mtkView.device = device
mtkView.delegate = self
}
private func makeBuffers() {
let size = vertexData.count * MemoryLayout<Float>.size
vertexBuffer = device.makeBuffer(bytes: vertexData, length: size, options: [])
}
private func makePipeline() {
guard let library = device.makeDefaultLibrary() else {fatalError()}
let descriptor = MTLRenderPipelineDescriptor()
descriptor.vertexFunction = library.makeFunction(name: "vertexShader")
descriptor.fragmentFunction = library.makeFunction(name: "fragmentShader")
descriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
renderPipeline = try! device.makeRenderPipelineState(descriptor: descriptor)
}
// MARK: - MTKViewDelegate
func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
print("\(self.classForCoder)/" + #function)
}
func draw(in view: MTKView) {
// ドローアブルを取得
guard let drawable = view.currentDrawable else {return}
// コマンドバッファを作成
guard let commandBuffer = commandQueue.makeCommandBuffer() else {fatalError()}
//
renderPassDescriptor.colorAttachments[0].texture = drawable.texture
// エンコーダ生成
guard let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor) else {return}
guard let renderPipeline = renderPipeline else {fatalError()}
renderEncoder.setRenderPipelineState(renderPipeline)
renderEncoder.setVertexBuffer(vertexBuffer, offset: 0, index: 0)
renderEncoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
// エンコード完了
renderEncoder.endEncoding()
// 表示するドローアブルを登録
commandBuffer.present(drawable)
// コマンドバッファをコミット(エンキュー)
commandBuffer.commit()
// 完了まで待つ
commandBuffer.waitUntilCompleted()
}
}
| mit | 78576552694c3995857bd935f2db1e2d | 28.148148 | 120 | 0.642948 | 4.776935 | false | false | false | false |
btanner/Eureka | Source/Rows/Common/FieldRow.swift | 3 | 22902 | // FieldRow.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
import UIKit
public protocol InputTypeInitiable {
init?(string stringValue: String)
}
public protocol FieldRowConformance : FormatterConformance {
var titlePercentage : CGFloat? { get set }
var placeholder : String? { get set }
var placeholderColor : UIColor? { get set }
}
extension Int: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue, radix: 10)
}
}
extension Float: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue)
}
}
extension String: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue)
}
}
extension URL: InputTypeInitiable {}
extension Double: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue)
}
}
open class FormatteableRow<Cell: CellType>: Row<Cell>, FormatterConformance where Cell: BaseCell, Cell: TextInputCell {
/// A formatter to be used to format the user's input
open var formatter: Formatter?
/// If the formatter should be used while the user is editing the text.
open var useFormatterDuringInput = false
open var useFormatterOnDidBeginEditing: Bool?
public required init(tag: String?) {
super.init(tag: tag)
displayValueFor = { [unowned self] value in
guard let v = value else { return nil }
guard let formatter = self.formatter else { return String(describing: v) }
if (self.cell.textInput as? UIView)?.isFirstResponder == true {
return self.useFormatterDuringInput ? formatter.editingString(for: v) : String(describing: v)
}
return formatter.string(for: v)
}
}
}
open class FieldRow<Cell: CellType>: FormatteableRow<Cell>, FieldRowConformance, KeyboardReturnHandler where Cell: BaseCell, Cell: TextFieldCell {
/// Configuration for the keyboardReturnType of this row
open var keyboardReturnType: KeyboardReturnTypeConfiguration?
/// The percentage of the cell that should be occupied by the textField
@available (*, deprecated, message: "Use titlePercentage instead")
open var textFieldPercentage : CGFloat? {
get {
return titlePercentage.map { 1 - $0 }
}
set {
titlePercentage = newValue.map { 1 - $0 }
}
}
/// The percentage of the cell that should be occupied by the title (i.e. the titleLabel and optional imageView combined)
open var titlePercentage: CGFloat?
/// The placeholder for the textField
open var placeholder: String?
/// The textColor for the textField's placeholder
open var placeholderColor: UIColor?
public required init(tag: String?) {
super.init(tag: tag)
}
}
/**
* Protocol for cells that contain a UITextField
*/
public protocol TextInputCell {
var textInput: UITextInput { get }
}
public protocol TextFieldCell: TextInputCell {
var textField: UITextField! { get }
}
extension TextFieldCell {
public var textInput: UITextInput {
return textField
}
}
open class _FieldCell<T> : Cell<T>, UITextFieldDelegate, TextFieldCell where T: Equatable, T: InputTypeInitiable {
@IBOutlet public weak var textField: UITextField!
@IBOutlet public weak var titleLabel: UILabel?
fileprivate var observingTitleText = false
private var awakeFromNibCalled = false
open var dynamicConstraints = [NSLayoutConstraint]()
private var calculatedTitlePercentage: CGFloat = 0.7
public required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
let textField = UITextField()
self.textField = textField
textField.translatesAutoresizingMaskIntoConstraints = false
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupTitleLabel()
contentView.addSubview(titleLabel!)
contentView.addSubview(textField)
NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: nil) { [weak self] _ in
guard let me = self else { return }
guard me.observingTitleText else { return }
me.titleLabel?.removeObserver(me, forKeyPath: "text")
me.observingTitleText = false
}
NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: nil) { [weak self] _ in
guard let me = self else { return }
guard !me.observingTitleText else { return }
me.titleLabel?.addObserver(me, forKeyPath: "text", options: [.new, .old], context: nil)
me.observingTitleText = true
}
NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: nil) { [weak self] _ in
self?.setupTitleLabel()
self?.setNeedsUpdateConstraints()
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func awakeFromNib() {
super.awakeFromNib()
awakeFromNibCalled = true
}
deinit {
textField?.delegate = nil
textField?.removeTarget(self, action: nil, for: .allEvents)
guard !awakeFromNibCalled else { return }
if observingTitleText {
titleLabel?.removeObserver(self, forKeyPath: "text")
}
imageView?.removeObserver(self, forKeyPath: "image")
NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIContentSizeCategory.didChangeNotification, object: nil)
}
open override func setup() {
super.setup()
selectionStyle = .none
if !awakeFromNibCalled {
titleLabel?.addObserver(self, forKeyPath: "text", options: [.new, .old], context: nil)
observingTitleText = true
imageView?.addObserver(self, forKeyPath: "image", options: [.new, .old], context: nil)
}
textField.addTarget(self, action: #selector(_FieldCell.textFieldDidChange(_:)), for: .editingChanged)
if let titleLabel = titleLabel {
// Make sure the title takes over most of the empty space so that the text field starts editing at the back.
let priority = UILayoutPriority(rawValue: titleLabel.contentHuggingPriority(for: .horizontal).rawValue + 1)
textField.setContentHuggingPriority(priority, for: .horizontal)
}
}
open override func update() {
super.update()
detailTextLabel?.text = nil
if !awakeFromNibCalled {
if let title = row.title {
switch row.cellStyle {
case .subtitle:
textField.textAlignment = .left
textField.clearButtonMode = .whileEditing
default:
textField.textAlignment = title.isEmpty ? .left : .right
textField.clearButtonMode = title.isEmpty ? .whileEditing : .never
}
} else {
textField.textAlignment = .left
textField.clearButtonMode = .whileEditing
}
} else {
textLabel?.text = nil
titleLabel?.text = row.title
if #available(iOS 13.0, *) {
titleLabel?.textColor = row.isDisabled ? .tertiaryLabel : .label
} else {
titleLabel?.textColor = row.isDisabled ? .gray : .black
}
}
textField.delegate = self
textField.text = row.displayValueFor?(row.value)
textField.isEnabled = !row.isDisabled
if #available(iOS 13.0, *) {
textField.textColor = row.isDisabled ? .tertiaryLabel : .label
} else {
textField.textColor = row.isDisabled ? .gray : .black
}
textField.font = .preferredFont(forTextStyle: .body)
if let placeholder = (row as? FieldRowConformance)?.placeholder {
if let color = (row as? FieldRowConformance)?.placeholderColor {
textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [.foregroundColor: color])
} else {
textField.placeholder = (row as? FieldRowConformance)?.placeholder
}
}
if row.isHighlighted {
titleLabel?.textColor = tintColor
}
}
open override func cellCanBecomeFirstResponder() -> Bool {
return !row.isDisabled && textField?.canBecomeFirstResponder == true
}
open override func cellBecomeFirstResponder(withDirection: Direction) -> Bool {
return textField.becomeFirstResponder()
}
open override func cellResignFirstResponder() -> Bool {
return textField.resignFirstResponder()
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let obj = object as AnyObject?
if let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKey.kindKey],
((obj === titleLabel && keyPathValue == "text") || (obj === imageView && keyPathValue == "image")) &&
(changeType as? NSNumber)?.uintValue == NSKeyValueChange.setting.rawValue {
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
}
}
// MARK: Helpers
open func customConstraints() {
guard !awakeFromNibCalled else { return }
contentView.removeConstraints(dynamicConstraints)
dynamicConstraints = []
switch row.cellStyle {
case .subtitle:
var views: [String: AnyObject] = ["textField": textField]
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
views["titleLabel"] = titleLabel
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-[titleLabel]-3-[textField]-|",
options: .alignAllLeading, metrics: nil, views: views)
titleLabel.setContentHuggingPriority(
UILayoutPriority(textField.contentHuggingPriority(for: .vertical).rawValue + 1), for: .vertical)
dynamicConstraints.append(NSLayoutConstraint(item: titleLabel, attribute: .centerX, relatedBy: .equal, toItem: textField, attribute: .centerX, multiplier: 1, constant: 0))
} else {
dynamicConstraints.append(NSLayoutConstraint(item: textField!, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0))
}
if let imageView = imageView, let _ = imageView.image {
views["imageView"] = imageView
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[titleLabel]-|", options: [], metrics: nil, views: views)
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[textField]-|", options: [], metrics: nil, views: views)
} else {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[textField]-|", options: [], metrics: nil, views: views)
}
} else {
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[titleLabel]-|", options: [], metrics: nil, views: views)
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[textField]-|", options: [], metrics: nil, views: views)
} else {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[textField]-|", options: .alignAllLeft, metrics: nil, views: views)
}
}
default:
var views: [String: AnyObject] = ["textField": textField]
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-[textField]-|", options: .alignAllLastBaseline, metrics: nil, views: views)
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
views["titleLabel"] = titleLabel
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-[titleLabel]-|", options: .alignAllLastBaseline, metrics: nil, views: views)
dynamicConstraints.append(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: textField, attribute: .centerY, multiplier: 1, constant: 0))
}
if let imageView = imageView, let _ = imageView.image {
views["imageView"] = imageView
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[titleLabel]-[textField]-|", options: [], metrics: nil, views: views)
dynamicConstraints.append(NSLayoutConstraint(item: titleLabel,
attribute: .width,
relatedBy: (row as? FieldRowConformance)?.titlePercentage != nil ? .equal : .lessThanOrEqual,
toItem: contentView,
attribute: .width,
multiplier: calculatedTitlePercentage,
constant: 0.0))
} else {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[textField]-|", options: [], metrics: nil, views: views)
}
} else {
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[titleLabel]-[textField]-|", options: [], metrics: nil, views: views)
dynamicConstraints.append(NSLayoutConstraint(item: titleLabel,
attribute: .width,
relatedBy: (row as? FieldRowConformance)?.titlePercentage != nil ? .equal : .lessThanOrEqual,
toItem: contentView,
attribute: .width,
multiplier: calculatedTitlePercentage,
constant: 0.0))
} else {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[textField]-|", options: .alignAllLeft, metrics: nil, views: views)
}
}
}
contentView.addConstraints(dynamicConstraints)
}
open override func updateConstraints() {
customConstraints()
super.updateConstraints()
}
@objc open func textFieldDidChange(_ textField: UITextField) {
guard let textValue = textField.text else {
row.value = nil
return
}
guard let fieldRow = row as? FieldRowConformance, let formatter = fieldRow.formatter else {
row.value = textValue.isEmpty ? nil : (T.init(string: textValue) ?? row.value)
return
}
if fieldRow.useFormatterDuringInput {
let unsafePointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
defer {
unsafePointer.deallocate()
}
let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(unsafePointer)
let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil
if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) {
row.value = value.pointee as? T
guard var selStartPos = textField.selectedTextRange?.start else { return }
let oldVal = textField.text
textField.text = row.displayValueFor?(row.value)
selStartPos = (formatter as? FormatterProtocol)?.getNewPosition(forPosition: selStartPos, inTextInput: textField, oldValue: oldVal, newValue: textField.text) ?? selStartPos
textField.selectedTextRange = textField.textRange(from: selStartPos, to: selStartPos)
return
}
} else {
let unsafePointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
defer {
unsafePointer.deallocate()
}
let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(unsafePointer)
let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil
if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) {
row.value = value.pointee as? T
} else {
row.value = textValue.isEmpty ? nil : (T.init(string: textValue) ?? row.value)
}
}
}
// MARK: Helpers
private func setupTitleLabel() {
titleLabel = self.textLabel
titleLabel?.translatesAutoresizingMaskIntoConstraints = false
titleLabel?.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal)
titleLabel?.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal)
}
private func displayValue(useFormatter: Bool) -> String? {
guard let v = row.value else { return nil }
if let formatter = (row as? FormatterConformance)?.formatter, useFormatter {
return textField?.isFirstResponder == true ? formatter.editingString(for: v) : formatter.string(for: v)
}
return String(describing: v)
}
// MARK: TextFieldDelegate
open func textFieldDidBeginEditing(_ textField: UITextField) {
formViewController()?.beginEditing(of: self)
formViewController()?.textInputDidBeginEditing(textField, cell: self)
if let fieldRowConformance = row as? FormatterConformance, let _ = fieldRowConformance.formatter, fieldRowConformance.useFormatterOnDidBeginEditing ?? fieldRowConformance.useFormatterDuringInput {
textField.text = displayValue(useFormatter: true)
} else {
textField.text = displayValue(useFormatter: false)
}
}
open func textFieldDidEndEditing(_ textField: UITextField) {
formViewController()?.endEditing(of: self)
formViewController()?.textInputDidEndEditing(textField, cell: self)
textFieldDidChange(textField)
textField.text = displayValue(useFormatter: (row as? FormatterConformance)?.formatter != nil)
}
open func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldReturn(textField, cell: self) ?? true
}
open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return formViewController()?.textInput(textField, shouldChangeCharactersInRange:range, replacementString:string, cell: self) ?? true
}
open func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldBeginEditing(textField, cell: self) ?? true
}
open func textFieldShouldClear(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldClear(textField, cell: self) ?? true
}
open func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldEndEditing(textField, cell: self) ?? true
}
open override func layoutSubviews() {
super.layoutSubviews()
guard let row = (row as? FieldRowConformance) else { return }
defer {
// As titleLabel is the textLabel, iOS may re-layout without updating constraints, for example:
// swiping, showing alert or actionsheet from the same section.
// thus we need forcing update to use customConstraints()
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
}
guard let titlePercentage = row.titlePercentage else { return }
var targetTitleWidth = bounds.size.width * titlePercentage
if let imageView = imageView, let _ = imageView.image, let titleLabel = titleLabel {
var extraWidthToSubtract = titleLabel.frame.minX - imageView.frame.minX // Left-to-right interface layout
if UIView.userInterfaceLayoutDirection(for: self.semanticContentAttribute) == .rightToLeft {
extraWidthToSubtract = imageView.frame.maxX - titleLabel.frame.maxX
}
targetTitleWidth -= extraWidthToSubtract
}
calculatedTitlePercentage = targetTitleWidth / contentView.bounds.size.width
}
}
| mit | 65451c2e078d7e4a863e2825c87642e3 | 45.54878 | 204 | 0.637324 | 5.477637 | false | false | false | false |
pascalodek/Tip_calculator | Tip-Calculator/ViewController.swift | 1 | 2581 | //
// ViewController.swift
// Tip-Calculator
//
// Created by PASCAL ARINGO ODEK on 12/25/14.
// Copyright (c) 2014 Pascal Odek. All rights reserved.
//
import UIKit
class ViewController: UIKit.UIViewController, UITableViewDataSource {
@IBOutlet weak var totalTextField: UITextField!
@IBOutlet weak var taxPctslider: UISlider!
@IBOutlet weak var taxPctLabel: UILabel!
@IBOutlet weak var resultsTextView: UITextView!
let tipCalc = TipCalculatorModel(total: 33.25, taxPct: 0.06)
var possibleTips = Dictionary<Int, (tipAmt:Double, total:Double)>()
var sortedKeys:[Int] = []
@IBOutlet weak var tableView: UITableView!
func refreshUI() {
// 1
totalTextField.text = String(format: "%0.2f", tipCalc.total)
// 2
taxPctslider.value = Float(tipCalc.taxPct) * 100.0
// 3
taxPctLabel.text = "Tax Percentage (\(Int(taxPctslider.value))%)"
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
refreshUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func calculateTapped(sender : AnyObject) {
tipCalc.total = Double((totalTextField.text as NSString).doubleValue)
possibleTips = tipCalc.returnPossibleTips()
sortedKeys = sorted(Array(possibleTips.keys))
tableView.reloadData()
}
@IBAction func taxPercentageChanged(sender: AnyObject) {
tipCalc.taxPct = Double(taxPctslider.value) / 100.0
refreshUI()
}
@IBAction func viewTapped(sender: AnyObject) {
totalTextField.resignFirstResponder()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sortedKeys.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// 2
let cell = UITableViewCell(style: UITableViewCellStyle.Value2, reuseIdentifier: nil)
// 3
let tipPct = sortedKeys[indexPath.row]
// 4
let tipAmt = possibleTips[tipPct]!.tipAmt
let total = possibleTips[tipPct]!.total
// 5
cell.textLabel?.text = "\(tipPct)%:"
cell.detailTextLabel?.text = String(format:"Tip: $%0.2f, Total: $%0.2f", tipAmt, total)
return cell
}
}
| mit | 6251072a1e3050afca959551de537c52 | 27.677778 | 109 | 0.630376 | 4.684211 | false | false | false | false |
brentdax/swift | test/IRGen/same_type_constraints.swift | 2 | 3295 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -primary-file %s -disable-objc-attr-requires-foundation-module | %FileCheck %s
// RUN: %target-swift-frontend -Osize -assume-parsing-unqualified-ownership-sil -emit-ir -primary-file %s -disable-objc-attr-requires-foundation-module | %FileCheck %s --check-prefix=OSIZE
// Ensure that same-type constraints between generic arguments get reflected
// correctly in the type context descriptor.
// CHECK-LABEL: @"$s21same_type_constraints4SG11VA2A2P2Rzq_RszrlE13InnerTEqualsUVMn" =
// T U(==T) V padding
// CHECK-SAME: , i8 -128, i8 0, i8 -128, i8 0,
// <rdar://problem/21665983> IRGen crash with protocol extension involving same-type constraint to X<T>
public struct DefaultFoo<T> {
var t: T?
}
public protocol P {
associatedtype Foo
}
public extension P where Foo == DefaultFoo<Self> {
public func foo() -> DefaultFoo<Self> {
return DefaultFoo()
}
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s21same_type_constraints1PPA2A10DefaultFooVyxG0E0RtzrlE3fooAFyF"
// <rdar://26873036> IRGen crash with derived class declaring same-type constraint on constrained associatedtype.
public class C1<T: Equatable> { }
public class C2<T: Equatable, U: P>: C1<T> where T == U.Foo {}
// CHECK: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s21same_type_constraints2C1CfD"
public protocol MyHashable {}
public protocol DataType : MyHashable {}
public protocol E {
associatedtype Data: DataType
}
struct Dict<V : MyHashable, K> {}
struct Val {}
public class GenericKlazz<T: DataType, R: E> : E where R.Data == T
{
public typealias Data = T
var d: Dict<T, Val>
init() {
d = Dict()
}
}
// This used to hit an infinite loop - <rdar://problem/27018457>
public protocol CodingType {
associatedtype ValueType
}
public protocol ValueCoding {
associatedtype Coder: CodingType
}
func foo<Self>(s: Self)
where Self : CodingType,
Self.ValueType: ValueCoding,
Self.ValueType.Coder == Self {
print(Self.ValueType.self)
}
// OSIZE: define internal swiftcc i8** @"$s21same_type_constraints12GenericKlazzCyxq_GAA1EAA4Data_AA0F4TypePWT"(%swift.type* %"GenericKlazz<T, R>.Data", %swift.type* nocapture readonly %"GenericKlazz<T, R>", i8** nocapture readnone %"GenericKlazz<T, R>.E") [[ATTRS:#[0-9]+]] {
// OSIZE: [[ATTRS]] = {{{.*}}noinline
// Check that same-typing two generic parameters together lowers correctly.
protocol P1 {}
protocol P2 {}
protocol P3 {}
struct ConformsToP1: P1 {}
struct ConformsToP2: P2 {}
struct ConformsToP3: P3 {}
struct SG11<T: P1, U: P2> {}
struct ConformsToP1AndP2 : P1, P2 { }
extension SG11 where U == T {
struct InnerTEqualsU<V: P3> { }
}
extension SG11 where T == ConformsToP1 {
struct InnerTEqualsConformsToP1<V: P3> { }
}
extension SG11 where U == ConformsToP2 {
struct InnerUEqualsConformsToP2<V: P3> { }
}
func inner1() -> Any.Type {
return SG11<ConformsToP1AndP2, ConformsToP1AndP2>.InnerTEqualsU<ConformsToP3>.self
}
func inner2() -> Any.Type {
return SG11<ConformsToP1, ConformsToP2>.InnerTEqualsConformsToP1<ConformsToP3>.self
}
func inner3() -> Any.Type {
return SG11<ConformsToP1, ConformsToP2>.InnerTEqualsConformsToP1<ConformsToP3>.self
}
| apache-2.0 | 3ab9f24c22b1ed2b093cf01870bc6f41 | 29.509259 | 276 | 0.711988 | 3.272095 | false | false | false | false |
jjatie/Charts | Source/Charts/Data/ChartDataSet/CandleChartDataSet.swift | 1 | 2370 | //
// CandleChartDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import CoreGraphics
import Foundation
public class CandleChartDataSet: LineScatterCandleRadarChartDataSet, CandleChartDataSetProtocol {
public required init() {
super.init()
}
override public init(entries: [ChartDataEntry], label: String) {
super.init(entries: entries, label: label)
}
// MARK: - Data functions and accessors
override public func calcMinMax(entry e: Element) {
guard let e = e as? CandleChartDataEntry
else { return }
yRange.min = Swift.min(e.low, yRange.min)
yRange.max = Swift.max(e.high, yRange.max)
calcMinMaxX(entry: e)
}
override public func calcMinMaxY(entry e: Element) {
guard let e = e as? CandleChartDataEntry
else { return }
yRange.min = Swift.min(e.low, yRange.min)
yRange.max = Swift.max(e.high, yRange.min)
yRange.min = Swift.min(e.low, yRange.max)
yRange.max = Swift.max(e.high, yRange.max)
}
// MARK: - Styling functions and accessors
/// the space between the candle entries
///
/// **default**: 0.1 (10%)
private var _barSpace: CGFloat = 0.1
/// the space that is left out on the left and right side of each candle,
/// **default**: 0.1 (10%), max 0.45, min 0.0
public var barSpace: CGFloat {
get { _barSpace }
set {
_barSpace = newValue.clamped(to: 0 ... 0.45)
}
}
/// should the candle bars show?
/// when false, only "ticks" will show
///
/// **default**: true
public var showCandleBar = true
/// the width of the candle-shadow-line in pixels.
///
/// **default**: 1.5
public var shadowWidth: CGFloat = 1.5
/// the color of the shadow line
public var shadowColor: NSUIColor?
public var isShadowColorSameAsCandle = false
/// color for open == close
public var neutralColor: NSUIColor?
/// color for open > close
public var increasingColor: NSUIColor?
/// color for open < close
public var decreasingColor: NSUIColor?
public var isIncreasingFilled = false
public var isDecreasingFilled = true
}
| apache-2.0 | b94bbda353e7e6c8a320297317efdbde | 25.043956 | 97 | 0.629536 | 4.157895 | false | false | false | false |
AbeHaruhiko/Welco-iOS | Welco-iOS/AppDelegate.swift | 1 | 7351 | /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import UIKit
import Parse
// If you want to use any of the UI components, uncomment this line
// import ParseUI
// If you want to use Crash Reporting - uncomment this line
// import ParseCrashReporting
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//--------------------------------------
// MARK: - UIApplicationDelegate
//--------------------------------------
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Enable storing and querying data from Local Datastore.
// Remove this line if you don't want to use Local Datastore features or want to use cachePolicy.
Parse.enableLocalDatastore()
// ****************************************************************************
// Uncomment this line if you want to enable Crash Reporting
// ParseCrashReporting.enable()
//
// Uncomment and fill in with your Parse credentials:
// Parse.setApplicationId("your_application_id", clientKey: "your_client_key")
Parse.setApplicationId("Ikzt3vnq6LwIKSb4WDP8RkOcUW3wRlsQuLUlrrFN",
clientKey: "2mBGwz3A3YD8SMo1UuKXD6M9wEl9QOCUkBV1KDf6")
//
// If you are using Facebook, uncomment and add your FacebookAppID to your bundle's plist as
// described here: https://developers.facebook.com/docs/getting-started/facebook-sdk-for-ios/
// Uncomment the line inside ParseStartProject-Bridging-Header and the following line here:
// PFFacebookUtils.initializeFacebook()
// ****************************************************************************
PFUser.enableAutomaticUser()
let defaultACL = PFACL();
// If you would like all objects to be private by default, remove this line.
defaultACL.publicReadAccess = true
PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser:true)
if application.applicationState != UIApplicationState.Background {
// Track an app open here if we launch with a push, unless
// "content_available" was used to trigger a background push (introduced in iOS 7).
// In that case, we skip tracking here to avoid double counting the app-open.
let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
var noPushPayload = false;
if let options = launchOptions {
noPushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil;
}
if (preBackgroundPush || oldPushHandlerOnly || noPushPayload) {
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
}
}
//
// Swift 1.2
//
// if application.respondsToSelector("registerUserNotificationSettings:") {
// let userNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
// let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
// application.registerUserNotificationSettings(settings)
// application.registerForRemoteNotifications()
// } else {
// let types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Alert | UIRemoteNotificationType.Sound
// application.registerForRemoteNotificationTypes(types)
// }
//
// Swift 2.0
//
// if #available(iOS 8.0, *) {
// let types: UIUserNotificationType = [.Alert, .Badge, .Sound]
// let settings = UIUserNotificationSettings(forTypes: types, categories: nil)
// application.registerUserNotificationSettings(settings)
// application.registerForRemoteNotifications()
// } else {
// let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound]
// application.registerForRemoteNotificationTypes(types)
// }
return true
}
//--------------------------------------
// MARK: Push Notifications
//--------------------------------------
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackground()
PFPush.subscribeToChannelInBackground("") { (succeeded: Bool, error: NSError?) in
if succeeded {
print("ParseStarterProject successfully subscribed to push notifications on the broadcast channel.\n");
} else {
print("ParseStarterProject failed to subscribe to push notifications on the broadcast channel with error = %@.\n", error)
}
}
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
print("Push notifications are not supported in the iOS Simulator.\n")
} else {
print("application:didFailToRegisterForRemoteNotificationsWithError: %@\n", error)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
}
///////////////////////////////////////////////////////////
// Uncomment this method if you want to use Push Notifications with Background App Refresh
///////////////////////////////////////////////////////////
// func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// if application.applicationState == UIApplicationState.Inactive {
// PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
// }
// }
//--------------------------------------
// MARK: Facebook SDK Integration
//--------------------------------------
///////////////////////////////////////////////////////////
// Uncomment this method if you are using Facebook
///////////////////////////////////////////////////////////
// func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
// return FBAppCall.handleOpenURL(url, sourceApplication:sourceApplication, session:PFFacebookUtils.session())
// }
}
| mit | 1677f5245136410cd4163adfc807c6cf | 46.425806 | 193 | 0.61257 | 5.857371 | false | false | false | false |
borglab/SwiftFusion | Sources/SwiftFusion/Inference/IdentityLinearizationFactor.swift | 1 | 2312 | // Copyright 2020 The SwiftFusion 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 _Differentiation
import PenguinStructures
/// A linear approximation of a `GaussianFactor`.
///
/// Since `GaussianFactor`s are linear, they are their own linear approximations.
public struct IdentityLinearizationFactor<Base: GaussianFactor>: LinearApproximationFactor {
/// The appoximated factor.
let base: Base
/// A tuple of the variable types of variables adjacent to this factor.
public typealias Variables = Base.Variables
/// The type of the error vector.
public typealias ErrorVector = Base.ErrorVector
/// The IDs of the variables adjacent to this factor.
public var edges: Variables.Indices {
base.edges
}
/// Creates a factor that linearly approximates `f` at `x`.
///
/// - Requires: `F == Base`.
public init<F: LinearizableFactor>(linearizing f: F, at x: F.Variables)
where F.Variables.TangentVector == Variables, F.ErrorVector == ErrorVector {
self.base = f as! Base
}
/// Returns the error at `x`.
///
/// This is typically interpreted as negative log-likelihood.
public func error(at x: Variables) -> Double {
base.error(at: x)
}
/// Returns the error vector given the values of the adjacent variables.
@differentiable
public func errorVector(at x: Variables) -> ErrorVector {
base.errorVector(at: x)
}
/// The linear component of `errorVector`.
public func errorVector_linearComponent(_ x: Variables) -> ErrorVector {
base.errorVector_linearComponent(x)
}
/// The adjoint (aka "transpose" or "dual") of the linear component of `errorVector`.
public func errorVector_linearComponent_adjoint(_ y: ErrorVector) -> Variables {
base.errorVector_linearComponent_adjoint(y)
}
}
| apache-2.0 | 79dcfb4a752013ac20139b3fb1257831 | 34.030303 | 92 | 0.723183 | 4.265683 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/CodePipeline/CodePipeline_Error.swift | 1 | 10249 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for CodePipeline
public struct CodePipelineErrorType: AWSErrorType {
enum Code: String {
case actionNotFoundException = "ActionNotFoundException"
case actionTypeNotFoundException = "ActionTypeNotFoundException"
case approvalAlreadyCompletedException = "ApprovalAlreadyCompletedException"
case concurrentModificationException = "ConcurrentModificationException"
case duplicatedStopRequestException = "DuplicatedStopRequestException"
case invalidActionDeclarationException = "InvalidActionDeclarationException"
case invalidApprovalTokenException = "InvalidApprovalTokenException"
case invalidArnException = "InvalidArnException"
case invalidBlockerDeclarationException = "InvalidBlockerDeclarationException"
case invalidClientTokenException = "InvalidClientTokenException"
case invalidJobException = "InvalidJobException"
case invalidJobStateException = "InvalidJobStateException"
case invalidNextTokenException = "InvalidNextTokenException"
case invalidNonceException = "InvalidNonceException"
case invalidStageDeclarationException = "InvalidStageDeclarationException"
case invalidStructureException = "InvalidStructureException"
case invalidTagsException = "InvalidTagsException"
case invalidWebhookAuthenticationParametersException = "InvalidWebhookAuthenticationParametersException"
case invalidWebhookFilterPatternException = "InvalidWebhookFilterPatternException"
case jobNotFoundException = "JobNotFoundException"
case limitExceededException = "LimitExceededException"
case notLatestPipelineExecutionException = "NotLatestPipelineExecutionException"
case outputVariablesSizeExceededException = "OutputVariablesSizeExceededException"
case pipelineExecutionNotFoundException = "PipelineExecutionNotFoundException"
case pipelineExecutionNotStoppableException = "PipelineExecutionNotStoppableException"
case pipelineNameInUseException = "PipelineNameInUseException"
case pipelineNotFoundException = "PipelineNotFoundException"
case pipelineVersionNotFoundException = "PipelineVersionNotFoundException"
case resourceNotFoundException = "ResourceNotFoundException"
case stageNotFoundException = "StageNotFoundException"
case stageNotRetryableException = "StageNotRetryableException"
case tooManyTagsException = "TooManyTagsException"
case validationException = "ValidationException"
case webhookNotFoundException = "WebhookNotFoundException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize CodePipeline
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// The specified action cannot be found.
public static var actionNotFoundException: Self { .init(.actionNotFoundException) }
/// The specified action type cannot be found.
public static var actionTypeNotFoundException: Self { .init(.actionTypeNotFoundException) }
/// The approval action has already been approved or rejected.
public static var approvalAlreadyCompletedException: Self { .init(.approvalAlreadyCompletedException) }
/// Unable to modify the tag due to a simultaneous update request.
public static var concurrentModificationException: Self { .init(.concurrentModificationException) }
/// The pipeline execution is already in a Stopping state. If you already chose to stop and wait, you cannot make that request again. You can choose to stop and abandon now, but be aware that this option can lead to failed tasks or out of sequence tasks. If you already chose to stop and abandon, you cannot make that request again.
public static var duplicatedStopRequestException: Self { .init(.duplicatedStopRequestException) }
/// The action declaration was specified in an invalid format.
public static var invalidActionDeclarationException: Self { .init(.invalidActionDeclarationException) }
/// The approval request already received a response or has expired.
public static var invalidApprovalTokenException: Self { .init(.invalidApprovalTokenException) }
/// The specified resource ARN is invalid.
public static var invalidArnException: Self { .init(.invalidArnException) }
/// Reserved for future use.
public static var invalidBlockerDeclarationException: Self { .init(.invalidBlockerDeclarationException) }
/// The client token was specified in an invalid format
public static var invalidClientTokenException: Self { .init(.invalidClientTokenException) }
/// The job was specified in an invalid format or cannot be found.
public static var invalidJobException: Self { .init(.invalidJobException) }
/// The job state was specified in an invalid format.
public static var invalidJobStateException: Self { .init(.invalidJobStateException) }
/// The next token was specified in an invalid format. Make sure that the next token you provide is the token returned by a previous call.
public static var invalidNextTokenException: Self { .init(.invalidNextTokenException) }
/// The nonce was specified in an invalid format.
public static var invalidNonceException: Self { .init(.invalidNonceException) }
/// The stage declaration was specified in an invalid format.
public static var invalidStageDeclarationException: Self { .init(.invalidStageDeclarationException) }
/// The structure was specified in an invalid format.
public static var invalidStructureException: Self { .init(.invalidStructureException) }
/// The specified resource tags are invalid.
public static var invalidTagsException: Self { .init(.invalidTagsException) }
/// The specified authentication type is in an invalid format.
public static var invalidWebhookAuthenticationParametersException: Self { .init(.invalidWebhookAuthenticationParametersException) }
/// The specified event filter rule is in an invalid format.
public static var invalidWebhookFilterPatternException: Self { .init(.invalidWebhookFilterPatternException) }
/// The job was specified in an invalid format or cannot be found.
public static var jobNotFoundException: Self { .init(.jobNotFoundException) }
/// The number of pipelines associated with the AWS account has exceeded the limit allowed for the account.
public static var limitExceededException: Self { .init(.limitExceededException) }
/// The stage has failed in a later run of the pipeline and the pipelineExecutionId associated with the request is out of date.
public static var notLatestPipelineExecutionException: Self { .init(.notLatestPipelineExecutionException) }
/// Exceeded the total size limit for all variables in the pipeline.
public static var outputVariablesSizeExceededException: Self { .init(.outputVariablesSizeExceededException) }
/// The pipeline execution was specified in an invalid format or cannot be found, or an execution ID does not belong to the specified pipeline.
public static var pipelineExecutionNotFoundException: Self { .init(.pipelineExecutionNotFoundException) }
/// Unable to stop the pipeline execution. The execution might already be in a Stopped state, or it might no longer be in progress.
public static var pipelineExecutionNotStoppableException: Self { .init(.pipelineExecutionNotStoppableException) }
/// The specified pipeline name is already in use.
public static var pipelineNameInUseException: Self { .init(.pipelineNameInUseException) }
/// The pipeline was specified in an invalid format or cannot be found.
public static var pipelineNotFoundException: Self { .init(.pipelineNotFoundException) }
/// The pipeline version was specified in an invalid format or cannot be found.
public static var pipelineVersionNotFoundException: Self { .init(.pipelineVersionNotFoundException) }
/// The resource was specified in an invalid format.
public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) }
/// The stage was specified in an invalid format or cannot be found.
public static var stageNotFoundException: Self { .init(.stageNotFoundException) }
/// Unable to retry. The pipeline structure or stage state might have changed while actions awaited retry, or the stage contains no failed actions.
public static var stageNotRetryableException: Self { .init(.stageNotRetryableException) }
/// The tags limit for a resource has been exceeded.
public static var tooManyTagsException: Self { .init(.tooManyTagsException) }
/// The validation was specified in an invalid format.
public static var validationException: Self { .init(.validationException) }
/// The specified webhook was entered in an invalid format or cannot be found.
public static var webhookNotFoundException: Self { .init(.webhookNotFoundException) }
}
extension CodePipelineErrorType: Equatable {
public static func == (lhs: CodePipelineErrorType, rhs: CodePipelineErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension CodePipelineErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| apache-2.0 | 6edfa638b31d6f78d10ee44e5af7d2fe | 64.698718 | 336 | 0.754317 | 5.428496 | false | false | false | false |
AnthonyMDev/Nimble | Sources/Nimble/Matchers/BeIdenticalTo.swift | 2 | 1459 | import Foundation
/// A Nimble matcher that succeeds when the actual value is the same instance
/// as the expected instance.
public func beIdenticalTo(_ expected: Any?) -> Predicate<Any> {
return Predicate.define { actualExpression in
let actual = try actualExpression.evaluate() as AnyObject?
let bool = actual === (expected as AnyObject?) && actual !== nil
return PredicateResult(
bool: bool,
message: .expectedCustomValueTo(
"be identical to \(identityAsString(expected))",
"\(identityAsString(actual))"
)
)
}
}
extension Expectation where T == Any {
public static func === (lhs: Expectation, rhs: Any?) {
lhs.to(beIdenticalTo(rhs))
}
public static func !== (lhs: Expectation, rhs: Any?) {
lhs.toNot(beIdenticalTo(rhs))
}
}
/// A Nimble matcher that succeeds when the actual value is the same instance
/// as the expected instance.
///
/// Alias for "beIdenticalTo".
public func be(_ expected: Any?) -> Predicate<Any> {
return beIdenticalTo(expected)
}
#if canImport(Darwin)
extension NMBObjCMatcher {
@objc public class func beIdenticalToMatcher(_ expected: NSObject?) -> NMBMatcher {
return NMBPredicate { actualExpression in
let aExpr = actualExpression.cast { $0 as Any? }
return try beIdenticalTo(expected).satisfies(aExpr).toObjectiveC()
}
}
}
#endif
| apache-2.0 | 77c6ad98f1029c4796a42271b7d3d017 | 30.042553 | 87 | 0.640164 | 4.737013 | false | false | false | false |
poetmountain/MotionMachine | Examples/MotionExamples/Classes/DynamicViewController.swift | 1 | 6713 | //
// DynamicViewController.swift
// MotionExamples
//
// Created by Brett Walker on 6/3/16.
// Copyright © 2016 Poet & Mountain, LLC. All rights reserved.
//
import UIKit
public class DynamicViewController: UIViewController, ButtonsViewDelegate {
var createdUI: Bool = false
var buttonsView: ButtonsView!
var tapRecognizer: UITapGestureRecognizer!
var circle: UIView!
var motions: [MotionGroup] = []
var constraints: [String : NSLayoutConstraint] = [:]
convenience init() {
self.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if (!createdUI) {
setupUI()
tapRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(viewTappedHandler))
view.addGestureRecognizer(tapRecognizer)
createdUI = true
}
}
override public func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
for motion in motions {
motion.stop()
}
motions.removeAll()
}
deinit {
view.removeGestureRecognizer(tapRecognizer)
}
// MARK: - Private methods
private func setupUI() {
view.backgroundColor = UIColor.white
var margins : UILayoutGuide
let top_offset : CGFloat = 20.0
if #available(iOS 11.0, *) {
margins = view.safeAreaLayoutGuide
} else {
margins = topLayoutGuide as! UILayoutGuide
}
let label = UILabel.init(frame: CGRect.zero)
label.font = UIFont.systemFont(ofSize: 12.0)
label.isUserInteractionEnabled = false
label.text = "Tap to move the circle to that point.\nThe path will blend as you continue to tap in other locations."
label.numberOfLines = 4
self.view.addSubview(label)
let w: CGFloat = 40.0
circle = UIView.init()
circle.backgroundColor = UIColor.init(red: 76.0/255.0, green:164.0/255.0, blue:68.0/255.0, alpha:1.0)
circle.layer.masksToBounds = true
circle.layer.cornerRadius = w * 0.5
self.view.addSubview(circle)
var top_anchor: NSLayoutYAxisAnchor
if #available(iOS 11.0, *) {
top_anchor = margins.topAnchor
} else {
top_anchor = margins.bottomAnchor
}
circle.translatesAutoresizingMaskIntoConstraints = false
let circle_x = circle.centerXAnchor.constraint(equalTo: margins.leadingAnchor, constant: 48.0)
circle_x.isActive = true
let circle_y = circle.topAnchor.constraint(equalTo: top_anchor, constant: top_offset)
circle_y.isActive = true
circle.heightAnchor.constraint(equalToConstant: 40.0).isActive = true
circle.widthAnchor.constraint(equalToConstant: 40.0).isActive = true
constraints["x"] = circle_x
constraints["y"] = circle_y
label.translatesAutoresizingMaskIntoConstraints = false
label.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: 80.0).isActive = true
label.firstBaselineAnchor.constraint(equalTo: top_anchor, constant: top_offset).isActive = true
label.widthAnchor.constraint(equalToConstant: 220.0).isActive = true
label.heightAnchor.constraint(equalToConstant: 60.0).isActive = true
buttonsView = ButtonsView.init(frame: CGRect.zero)
view.addSubview(buttonsView)
buttonsView.startButton.isHidden = true
buttonsView.stopButton.isHidden = true
buttonsView.delegate = self
buttonsView.translatesAutoresizingMaskIntoConstraints = false
buttonsView.widthAnchor.constraint(equalTo: margins.widthAnchor, constant: 0.0).isActive = true
buttonsView.heightAnchor.constraint(equalTo: margins.heightAnchor, constant: 0.0).isActive = true
}
@objc func viewTappedHandler(_ gesture: UITapGestureRecognizer) {
if (gesture.state != UIGestureRecognizer.State.ended) {
return;
}
let pt = gesture.location(in: self.view)
print("gesture pt \(pt)")
var y_offset : CGFloat = 0.0
if #available(iOS 11.0, *) {
y_offset = CGFloat(view.safeAreaInsets.top) + 20.0
} else {
y_offset = CGFloat(topLayoutGuide.length) + 20.0
}
// setup new motion
let x = constraints["x"]!
let y = constraints["y"]!
let motion_x = Motion(target: x,
properties: [PropertyData(path: "constant", start: Double(x.constant), end: Double(pt.x))],
duration: 1.5,
easing: EasingQuadratic.easeInOut())
motion_x.additive = true
let motion_y = Motion(target: y,
properties: [PropertyData(path: "constant", start: Double(y.constant), end: Double(pt.y-y_offset))],
duration: 1.5,
easing: EasingQuadratic.easeInOut())
motion_y.additive = true
let group = MotionGroup(motions: [motion_x, motion_y])
group.updated { [weak self] (group) in
guard let strong_self = self else { return }
//print("constraints \(strong_self.constraints)")
}
group.completed { [weak self] (group) in
guard let strong_self = self else { return }
for x in 0..<strong_self.motions.count {
let motion = strong_self.motions[x]
if (group === motion) {
strong_self.motions.remove(at: x)
break
}
}
}
motions.append(group)
group.start()
}
// MARK: - ButtonsViewDelegate methods
func didStart() {
}
func didStop() {
}
func didPause() {
for motion in motions {
motion.pause()
}
}
func didResume() {
for motion in motions {
motion.resume()
}
}
}
| mit | 9e75fe682025ebbc1b736860aefc2446 | 29.788991 | 130 | 0.569428 | 4.906433 | false | false | false | false |
DivineDominion/mac-licensing-fastspring-cocoafob | No-Trial-Verify-at-Start/MyNewApp/ExistingLicenseViewController.swift | 1 | 1107 | // Copyright (c) 2015-2019 Christian Tietze
//
// See the file LICENSE for copying permission.
import Cocoa
public protocol HandlesRegistering: AnyObject {
func register(name: String, licenseCode: String)
}
public class ExistingLicenseViewController: NSViewController {
@IBOutlet public weak var licenseeTextField: NSTextField!
@IBOutlet public weak var licenseCodeTextField: NSTextField!
@IBOutlet public weak var registerButton: NSButton!
public var eventHandler: HandlesRegistering?
@IBAction public func register(_ sender: AnyObject) {
let name = licenseeTextField.stringValue
let licenseCode = licenseCodeTextField.stringValue
eventHandler?.register(name: name, licenseCode: licenseCode)
}
public func displayEmptyForm() {
licenseeTextField.stringValue = ""
licenseCodeTextField.stringValue = ""
}
public func display(license: License) {
licenseeTextField.stringValue = license.name
licenseCodeTextField.stringValue = license.licenseCode
}
}
| mit | a46dd7738125e783aa22f11d9d5612db | 28.131579 | 68 | 0.70009 | 5.426471 | false | false | false | false |
IngmarStein/swift | stdlib/public/Platform/Platform.swift | 4 | 13145 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
//===----------------------------------------------------------------------===//
// MacTypes.h
//===----------------------------------------------------------------------===//
public var noErr: OSStatus { return 0 }
/// The `Boolean` type declared in MacTypes.h and used throughout Core
/// Foundation.
///
/// The C type is a typedef for `unsigned char`.
@_fixed_layout
public struct DarwinBoolean : ExpressibleByBooleanLiteral {
var _value: UInt8
public init(_ value: Bool) {
self._value = value ? 1 : 0
}
/// The value of `self`, expressed as a `Bool`.
public var boolValue: Bool {
return _value != 0
}
/// Create an instance initialized to `value`.
@_transparent
public init(booleanLiteral value: Bool) {
self.init(value)
}
}
extension DarwinBoolean : CustomReflectable {
/// Returns a mirror that reflects `self`.
public var customMirror: Mirror {
return Mirror(reflecting: boolValue)
}
}
extension DarwinBoolean : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return self.boolValue.description
}
}
extension DarwinBoolean : Equatable {}
public func ==(lhs: DarwinBoolean, rhs: DarwinBoolean) -> Bool {
return lhs.boolValue == rhs.boolValue
}
public // COMPILER_INTRINSIC
func _convertBoolToDarwinBoolean(_ x: Bool) -> DarwinBoolean {
return DarwinBoolean(x)
}
public // COMPILER_INTRINSIC
func _convertDarwinBooleanToBool(_ x: DarwinBoolean) -> Bool {
return x.boolValue
}
#endif
//===----------------------------------------------------------------------===//
// sys/errno.h
//===----------------------------------------------------------------------===//
@_silgen_name("_swift_Platform_getErrno")
func _swift_Platform_getErrno() -> Int32
@_silgen_name("_swift_Platform_setErrno")
func _swift_Platform_setErrno(_: Int32)
public var errno : Int32 {
get {
return _swift_Platform_getErrno()
}
set(val) {
return _swift_Platform_setErrno(val)
}
}
//===----------------------------------------------------------------------===//
// stdio.h
//===----------------------------------------------------------------------===//
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) || os(FreeBSD) || os(PS4)
public var stdin : UnsafeMutablePointer<FILE> {
get {
return __stdinp
}
set {
__stdinp = newValue
}
}
public var stdout : UnsafeMutablePointer<FILE> {
get {
return __stdoutp
}
set {
__stdoutp = newValue
}
}
public var stderr : UnsafeMutablePointer<FILE> {
get {
return __stderrp
}
set {
__stderrp = newValue
}
}
public func dprintf(_ fd: Int, _ format: UnsafePointer<Int8>, _ args: CVarArg...) -> Int32 {
return withVaList(args) { va_args in
vdprintf(Int32(fd), format, va_args)
}
}
public func snprintf(ptr: UnsafeMutablePointer<Int8>, _ len: Int, _ format: UnsafePointer<Int8>, _ args: CVarArg...) -> Int32 {
return withVaList(args) { va_args in
return vsnprintf(ptr, len, format, va_args)
}
}
#endif
//===----------------------------------------------------------------------===//
// fcntl.h
//===----------------------------------------------------------------------===//
#if !os(Windows) || CYGWIN
@_silgen_name("_swift_Platform_open")
func _swift_Platform_open(
_ path: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: mode_t
) -> Int32
#else
@_silgen_name("_swift_Platform_open")
func _swift_Platform_open(
_ path: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: Int32
) -> Int32
#endif
#if !os(Windows) || CYGWIN
@_silgen_name("_swift_Platform_openat")
func _swift_Platform_openat(
_ fd: Int32,
_ path: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: mode_t
) -> Int32
#endif
public func open(
_ path: UnsafePointer<CChar>,
_ oflag: Int32
) -> Int32 {
return _swift_Platform_open(path, oflag, 0)
}
#if !os(Windows) || CYGWIN
public func open(
_ path: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: mode_t
) -> Int32 {
return _swift_Platform_open(path, oflag, mode)
}
public func openat(
_ fd: Int32,
_ path: UnsafePointer<CChar>,
_ oflag: Int32
) -> Int32 {
return _swift_Platform_openat(fd, path, oflag, 0)
}
public func openat(
_ fd: Int32,
_ path: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: mode_t
) -> Int32 {
return _swift_Platform_openat(fd, path, oflag, mode)
}
#else
public func open(
_ path: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: Int32
) -> Int32 {
return _swift_Platform_open(path, oflag, mode)
}
#endif
#if !os(Windows) || CYGWIN
@_silgen_name("_swift_Platform_fcntl")
internal func _swift_Platform_fcntl(
_ fd: Int32,
_ cmd: Int32,
_ value: Int32
) -> Int32
@_silgen_name("_swift_Platform_fcntlPtr")
internal func _swift_Platform_fcntlPtr(
_ fd: Int32,
_ cmd: Int32,
_ ptr: UnsafeMutableRawPointer
) -> Int32
public func fcntl(
_ fd: Int32,
_ cmd: Int32
) -> Int32 {
return _swift_Platform_fcntl(fd, cmd, 0)
}
public func fcntl(
_ fd: Int32,
_ cmd: Int32,
_ value: Int32
) -> Int32 {
return _swift_Platform_fcntl(fd, cmd, value)
}
public func fcntl(
_ fd: Int32,
_ cmd: Int32,
_ ptr: UnsafeMutableRawPointer
) -> Int32 {
return _swift_Platform_fcntlPtr(fd, cmd, ptr)
}
#endif
#if !os(Windows) || CYGWIN
public var S_IFMT: mode_t { return mode_t(0o170000) }
public var S_IFIFO: mode_t { return mode_t(0o010000) }
public var S_IFCHR: mode_t { return mode_t(0o020000) }
public var S_IFDIR: mode_t { return mode_t(0o040000) }
public var S_IFBLK: mode_t { return mode_t(0o060000) }
public var S_IFREG: mode_t { return mode_t(0o100000) }
public var S_IFLNK: mode_t { return mode_t(0o120000) }
public var S_IFSOCK: mode_t { return mode_t(0o140000) }
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
public var S_IFWHT: mode_t { return mode_t(0o160000) }
#endif
public var S_IRWXU: mode_t { return mode_t(0o000700) }
public var S_IRUSR: mode_t { return mode_t(0o000400) }
public var S_IWUSR: mode_t { return mode_t(0o000200) }
public var S_IXUSR: mode_t { return mode_t(0o000100) }
public var S_IRWXG: mode_t { return mode_t(0o000070) }
public var S_IRGRP: mode_t { return mode_t(0o000040) }
public var S_IWGRP: mode_t { return mode_t(0o000020) }
public var S_IXGRP: mode_t { return mode_t(0o000010) }
public var S_IRWXO: mode_t { return mode_t(0o000007) }
public var S_IROTH: mode_t { return mode_t(0o000004) }
public var S_IWOTH: mode_t { return mode_t(0o000002) }
public var S_IXOTH: mode_t { return mode_t(0o000001) }
public var S_ISUID: mode_t { return mode_t(0o004000) }
public var S_ISGID: mode_t { return mode_t(0o002000) }
public var S_ISVTX: mode_t { return mode_t(0o001000) }
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
public var S_ISTXT: mode_t { return S_ISVTX }
public var S_IREAD: mode_t { return S_IRUSR }
public var S_IWRITE: mode_t { return S_IWUSR }
public var S_IEXEC: mode_t { return S_IXUSR }
#endif
#else
public var S_IFMT: Int32 { return Int32(0xf000) }
public var S_IFREG: Int32 { return Int32(0x8000) }
public var S_IFDIR: Int32 { return Int32(0x4000) }
public var S_IFCHR: Int32 { return Int32(0x2000) }
public var S_IFIFO: Int32 { return Int32(0x1000) }
public var S_IREAD: Int32 { return Int32(0x0100) }
public var S_IWRITE: Int32 { return Int32(0x0080) }
public var S_IEXEC: Int32 { return Int32(0x0040) }
#endif
//===----------------------------------------------------------------------===//
// ioctl.h
//===----------------------------------------------------------------------===//
#if !os(Windows) || CYGWIN
@_silgen_name("_swift_Platform_ioctl")
internal func _swift_Platform_ioctl(
_ fd: CInt,
_ request: UInt,
_ value: CInt
) -> CInt
@_silgen_name("_swift_Platform_ioctlPtr")
internal func _swift_Platform_ioctlPtr(
_ fd: CInt,
_ request: UInt,
_ ptr: UnsafeMutableRawPointer
) -> CInt
public func ioctl(
_ fd: CInt,
_ request: UInt,
_ value: CInt
) -> CInt {
return _swift_Platform_ioctl(fd, request, value)
}
public func ioctl(
_ fd: CInt,
_ request: UInt,
_ ptr: UnsafeMutableRawPointer
) -> CInt {
return _swift_Platform_ioctlPtr(fd, request, ptr)
}
public func ioctl(
_ fd: CInt,
_ request: UInt
) -> CInt {
return _swift_Platform_ioctl(fd, request, 0)
}
#endif
//===----------------------------------------------------------------------===//
// unistd.h
//===----------------------------------------------------------------------===//
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
@available(*, unavailable, message: "Please use threads or posix_spawn*()")
public func fork() -> Int32 {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "Please use threads or posix_spawn*()")
public func vfork() -> Int32 {
fatalError("unavailable function can't be called")
}
#endif
//===----------------------------------------------------------------------===//
// signal.h
//===----------------------------------------------------------------------===//
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
public var SIG_DFL: sig_t? { return nil }
public var SIG_IGN: sig_t { return unsafeBitCast(1, to: sig_t.self) }
public var SIG_ERR: sig_t { return unsafeBitCast(-1, to: sig_t.self) }
public var SIG_HOLD: sig_t { return unsafeBitCast(5, to: sig_t.self) }
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
public typealias sighandler_t = __sighandler_t
public var SIG_DFL: sighandler_t? { return nil }
public var SIG_IGN: sighandler_t {
return unsafeBitCast(1, to: sighandler_t.self)
}
public var SIG_ERR: sighandler_t {
return unsafeBitCast(-1, to: sighandler_t.self)
}
public var SIG_HOLD: sighandler_t {
return unsafeBitCast(2, to: sighandler_t.self)
}
#elseif os(Windows)
#if CYGWIN
public typealias sighandler_t = __sighandler_t
public var SIG_DFL: sighandler_t? { return nil }
public var SIG_IGN: sighandler_t {
return unsafeBitCast(1, to: sighandler_t.self)
}
public var SIG_ERR: sighandler_t {
return unsafeBitCast(-1, to: sighandler_t.self)
}
public var SIG_HOLD: sighandler_t {
return unsafeBitCast(2, to: sighandler_t.self)
}
#else
public var SIG_DFL: _crt_signal_t? { return nil }
public var SIG_IGN: _crt_signal_t {
return unsafeBitCast(1, to: _crt_signal_t.self)
}
public var SIG_ERR: _crt_signal_t {
return unsafeBitCast(-1, to: _crt_signal_t.self)
}
#endif
#else
internal var _ignore = _UnsupportedPlatformError()
#endif
//===----------------------------------------------------------------------===//
// semaphore.h
//===----------------------------------------------------------------------===//
#if !os(Windows) || CYGWIN
/// The value returned by `sem_open()` in the case of failure.
public var SEM_FAILED: UnsafeMutablePointer<sem_t>? {
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
// The value is ABI. Value verified to be correct for OS X, iOS, watchOS, tvOS.
return UnsafeMutablePointer<sem_t>(bitPattern: -1)
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
// The value is ABI. Value verified to be correct on Glibc.
return UnsafeMutablePointer<sem_t>(bitPattern: 0)
#elseif os(Windows)
#if CYGWIN
// The value is ABI. Value verified to be correct on Glibc.
return UnsafeMutablePointer<sem_t>(bitPattern: 0)
#else
_UnsupportedPlatformError()
#endif
#else
_UnsupportedPlatformError()
#endif
}
@_silgen_name("_swift_Platform_sem_open2")
internal func _swift_Platform_sem_open2(
_ name: UnsafePointer<CChar>,
_ oflag: Int32
) -> UnsafeMutablePointer<sem_t>?
@_silgen_name("_swift_Platform_sem_open4")
internal func _swift_Platform_sem_open4(
_ name: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: mode_t,
_ value: CUnsignedInt
) -> UnsafeMutablePointer<sem_t>?
public func sem_open(
_ name: UnsafePointer<CChar>,
_ oflag: Int32
) -> UnsafeMutablePointer<sem_t>? {
return _swift_Platform_sem_open2(name, oflag)
}
public func sem_open(
_ name: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: mode_t,
_ value: CUnsignedInt
) -> UnsafeMutablePointer<sem_t>? {
return _swift_Platform_sem_open4(name, oflag, mode, value)
}
#endif
//===----------------------------------------------------------------------===//
// Misc.
//===----------------------------------------------------------------------===//
// FreeBSD defines extern char **environ differently than Linux.
#if os(FreeBSD) || os(PS4)
@_silgen_name("_swift_FreeBSD_getEnv")
func _swift_FreeBSD_getEnv(
) -> UnsafeMutablePointer<UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>>
public var environ: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> {
return _swift_FreeBSD_getEnv().pointee
}
#endif
| apache-2.0 | 43de6a2029fd48308d83882076cf1d3a | 26.385417 | 127 | 0.597413 | 3.416948 | false | false | false | false |
castillejoale/Bluefruit_LE_Connect_v2_Minimized_UART | Pods/CocoaMQTT/Source/CocoaMQTT.swift | 1 | 16148 | //
// CocoaMQTT.swift
// CocoaMQTT
//
// Created by Feng Lee<[email protected]> on 14/8/3.
// Copyright (c) 2015 emqtt.io. All rights reserved.
//
import Foundation
import CocoaAsyncSocket
import MSWeakTimer
/**
* MQTT Delegate
*/
public protocol CocoaMQTTDelegate : class {
/**
* MQTT connected with server
*/
func mqtt(mqtt: CocoaMQTT, didConnect host: String, port: Int)
func mqtt(mqtt: CocoaMQTT, didConnectAck ack: CocoaMQTTConnAck)
func mqtt(mqtt: CocoaMQTT, didPublishMessage message: CocoaMQTTMessage, id: UInt16)
func mqtt(mqtt: CocoaMQTT, didPublishAck id: UInt16)
func mqtt(mqtt: CocoaMQTT, didReceiveMessage message: CocoaMQTTMessage, id: UInt16 )
func mqtt(mqtt: CocoaMQTT, didSubscribeTopic topic: String)
func mqtt(mqtt: CocoaMQTT, didUnsubscribeTopic topic: String)
func mqttDidPing(mqtt: CocoaMQTT)
func mqttDidReceivePong(mqtt: CocoaMQTT)
func mqttDidDisconnect(mqtt: CocoaMQTT, withError err: NSError?)
}
/**
* Blueprint of the MQTT client
*/
public protocol CocoaMQTTClient {
var host: String { get set }
var port: UInt16 { get set }
var clientId: String { get }
var username: String? {get set}
var password: String? {get set}
var secureMQTT: Bool {get set}
var cleanSess: Bool {get set}
var keepAlive: UInt16 {get set}
var willMessage: CocoaMQTTWill? {get set}
func connect() -> Bool
func publish(topic: String, withString string: String, qos: CocoaMQTTQOS, retained: Bool, dup: Bool) -> UInt16
func publish(message: CocoaMQTTMessage) -> UInt16
func subscribe(topic: String, qos: CocoaMQTTQOS) -> UInt16
func unsubscribe(topic: String) -> UInt16
func ping()
func disconnect()
}
/**
* QOS
*/
public enum CocoaMQTTQOS: UInt8 {
case QOS0 = 0
case QOS1
case QOS2
}
/**
* Connection State
*/
public enum CocoaMQTTConnState: UInt8 {
case INIT = 0
case CONNECTING
case CONNECTED
case DISCONNECTED
}
/**
* Conn Ack
*/
public enum CocoaMQTTConnAck: UInt8 {
case ACCEPT = 0
case PROTO_VER
case INVALID_ID
case SERVER
case CREDENTIALS
case AUTH
}
/**
* asyncsocket read tag
*/
enum CocoaMQTTReadTag: Int {
case TAG_HEADER = 0
case TAG_LENGTH
case TAG_PAYLOAD
}
/**
* Main CocoaMQTT Class
*
* Notice: GCDAsyncSocket need delegate to extend NSObject
*/
public class CocoaMQTT: NSObject, CocoaMQTTClient, GCDAsyncSocketDelegate, CocoaMQTTReaderDelegate {
//client variables
public var host = "localhost"
public var port: UInt16 = 1883
public var clientId: String
public var username: String?
public var password: String?
public var secureMQTT: Bool = false
public var backgroundOnSocket: Bool = false
public var cleanSess: Bool = true
//keep alive
public var keepAlive: UInt16 = 60
var aliveTimer: MSWeakTimer?
//will message
public var willMessage: CocoaMQTTWill?
//delegate weak??
public weak var delegate: CocoaMQTTDelegate?
//socket and connection
public var connState = CocoaMQTTConnState.INIT
var socket: GCDAsyncSocket?
var reader: CocoaMQTTReader?
//global message id
var gmid: UInt16 = 1
//subscribed topics
var subscriptions = Dictionary<UInt16, String>()
//published messages
public var messages = Dictionary<UInt16, CocoaMQTTMessage>()
public init(clientId: String, host: String = "localhost", port: UInt16 = 1883) {
self.clientId = clientId
self.host = host
self.port = port
}
//API Functions
public func connect() -> Bool {
socket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
reader = CocoaMQTTReader(socket: socket!, delegate: self)
do {
try socket!.connectToHost(self.host, onPort: self.port)
connState = CocoaMQTTConnState.CONNECTING
return true
} catch let error as NSError {
#if DEBUG
NSLog("CocoaMQTT: socket connect error: \(error.description)")
#endif
return false
}
}
public func publish(topic: String, withString string: String, qos: CocoaMQTTQOS = .QOS1, retained: Bool = false, dup: Bool = false) -> UInt16 {
let message = CocoaMQTTMessage(topic: topic, string: string, qos: qos, retained: retained, dup: dup)
return publish(message)
}
public func publish(message: CocoaMQTTMessage) -> UInt16 {
let msgId: UInt16 = _nextMessageId()
let frame = CocoaMQTTFramePublish(msgid: msgId, topic: message.topic, payload: message.payload)
frame.qos = message.qos.rawValue
frame.retained = message.retained
frame.dup = message.dup
send(frame, tag: Int(msgId))
if message.qos != CocoaMQTTQOS.QOS0 {
messages[msgId] = message //cache
}
delegate?.mqtt(self, didPublishMessage: message, id: msgId)
return msgId
}
public func subscribe(topic: String, qos: CocoaMQTTQOS = .QOS1) -> UInt16 {
let msgId = _nextMessageId()
let frame = CocoaMQTTFrameSubscribe(msgid: msgId, topic: topic, reqos: qos.rawValue)
send(frame, tag: Int(msgId))
subscriptions[msgId] = topic //cache?
return msgId
}
public func unsubscribe(topic: String) -> UInt16 {
let msgId = _nextMessageId()
let frame = CocoaMQTTFrameUnsubscribe(msgid: msgId, topic: topic)
subscriptions[msgId] = topic //cache
send(frame, tag: Int(msgId))
return msgId
}
public func ping() {
send(CocoaMQTTFrame(type: CocoaMQTTFrameType.PINGREQ), tag: -0xC0)
self.delegate?.mqttDidPing(self)
}
public func disconnect() {
send(CocoaMQTTFrame(type: CocoaMQTTFrameType.DISCONNECT), tag: -0xE0)
socket!.disconnect()
}
func send(frame: CocoaMQTTFrame, tag: Int = 0) {
let data = frame.data()
socket!.writeData(NSData(bytes: data, length: data.count), withTimeout: -1, tag: tag)
}
func sendConnectFrame() {
let frame = CocoaMQTTFrameConnect(client: self)
send(frame)
reader!.start()
delegate?.mqtt(self, didConnect: host, port: Int(port))
}
//AsyncSocket Delegate
public func socket(sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
#if DEBUG
NSLog("CocoaMQTT: connected to \(host) : \(port)")
#endif
#if TARGET_OS_IPHONE
if backgroundOnSocket {
sock.performBlock { sock.enableBackgroundingOnSocket() }
}
#endif
if secureMQTT {
#if DEBUG
sock.startTLS([GCDAsyncSocketManuallyEvaluateTrust: true])
#else
sock.startTLS(nil)
#endif
} else {
sendConnectFrame()
}
}
public func socket(sock: GCDAsyncSocket, didReceiveTrust trust: SecTrust, completionHandler: ((Bool) -> Void)) {
#if DEBUG
NSLog("CocoaMQTT: didReceiveTrust")
#endif
completionHandler(true)
}
public func socketDidSecure(sock: GCDAsyncSocket) {
#if DEBUG
NSLog("CocoaMQTT: socketDidSecure")
#endif
sendConnectFrame()
}
public func socket(sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) {
#if DEBUG
NSLog("CocoaMQTT: Socket write message with tag: \(tag)")
#endif
}
public func socket(sock: GCDAsyncSocket, didReadData data: NSData, withTag tag: Int) {
let etag: CocoaMQTTReadTag = CocoaMQTTReadTag(rawValue: tag)!
var bytes = [UInt8]([0])
switch etag {
case CocoaMQTTReadTag.TAG_HEADER:
data.getBytes(&bytes, length: 1)
reader!.headerReady(bytes[0])
case CocoaMQTTReadTag.TAG_LENGTH:
data.getBytes(&bytes, length: 1)
reader!.lengthReady(bytes[0])
case CocoaMQTTReadTag.TAG_PAYLOAD:
reader!.payloadReady(data)
}
}
public func socketDidDisconnect(sock: GCDAsyncSocket, withError err: NSError?) {
connState = CocoaMQTTConnState.DISCONNECTED
delegate?.mqttDidDisconnect(self, withError: err)
}
//CocoaMQTTReader Delegate
public func didReceiveConnAck(reader: CocoaMQTTReader, connack: UInt8) {
connState = CocoaMQTTConnState.CONNECTED
#if DEBUG
NSLog("CocoaMQTT: CONNACK Received: \(connack)")
#endif
let ack = CocoaMQTTConnAck(rawValue: connack)!
delegate?.mqtt(self, didConnectAck: ack)
//keep alive
if ack == CocoaMQTTConnAck.ACCEPT && keepAlive > 0 {
aliveTimer = MSWeakTimer.scheduledTimerWithTimeInterval(
NSTimeInterval(keepAlive),
target: self,
selector: #selector(CocoaMQTT._aliveTimerFired),
userInfo: nil,
repeats: true,
dispatchQueue: dispatch_get_main_queue())
}
}
func _aliveTimerFired() {
if connState == CocoaMQTTConnState.CONNECTED {
ping()
} else {
aliveTimer?.invalidate()
}
}
func didReceivePublish(reader: CocoaMQTTReader, message: CocoaMQTTMessage, id: UInt16) {
#if DEBUG
NSLog("CocoaMQTT: PUBLISH Received from \(message.topic)")
#endif
delegate?.mqtt(self, didReceiveMessage: message, id: id)
if message.qos == CocoaMQTTQOS.QOS1 {
_puback(CocoaMQTTFrameType.PUBACK, msgid: id)
} else if message.qos == CocoaMQTTQOS.QOS2 {
_puback(CocoaMQTTFrameType.PUBREC, msgid: id)
}
}
func _puback(type: CocoaMQTTFrameType, msgid: UInt16) {
var descr: String?
switch type {
case .PUBACK: descr = "PUBACK"
case .PUBREC: descr = "PUBREC"
case .PUBREL: descr = "PUBREL"
case .PUBCOMP: descr = "PUBCOMP"
default: break
}
#if DEBUG
if descr != nil {
NSLog("CocoaMQTT: Send \(descr!), msgid: \(msgid)")
}
#endif
send(CocoaMQTTFramePubAck(type: type, msgid: msgid))
}
func didReceivePubAck(reader: CocoaMQTTReader, msgid: UInt16) {
#if DEBUG
NSLog("CocoaMQTT: PUBACK Received: \(msgid)")
#endif
messages.removeValueForKey(msgid)
delegate?.mqtt(self, didPublishAck: msgid)
}
func didReceivePubRec(reader: CocoaMQTTReader, msgid: UInt16) {
#if DEBUG
NSLog("CocoaMQTT: PUBREC Received: \(msgid)")
#endif
_puback(CocoaMQTTFrameType.PUBREL, msgid: msgid)
}
func didReceivePubRel(reader: CocoaMQTTReader, msgid: UInt16) {
#if DEBUG
NSLog("CocoaMQTT: PUBREL Received: \(msgid)")
#endif
_puback(CocoaMQTTFrameType.PUBCOMP, msgid: msgid)
}
func didReceivePubComp(reader: CocoaMQTTReader, msgid: UInt16) {
#if DEBUG
NSLog("CocoaMQTT: PUBCOMP Received: \(msgid)")
#endif
messages.removeValueForKey(msgid)
}
func didReceiveSubAck(reader: CocoaMQTTReader, msgid: UInt16) {
#if DEBUG
NSLog("CocoaMQTT: SUBACK Received: \(msgid)")
#endif
if let topic = subscriptions.removeValueForKey(msgid) {
delegate?.mqtt(self, didSubscribeTopic: topic)
}
}
func didReceiveUnsubAck(reader: CocoaMQTTReader, msgid: UInt16) {
#if DEBUG
NSLog("CocoaMQTT: UNSUBACK Received: \(msgid)")
#endif
if let topic = subscriptions.removeValueForKey(msgid) {
delegate?.mqtt(self, didUnsubscribeTopic: topic)
}
}
func didReceivePong(reader: CocoaMQTTReader) {
#if DEBUG
NSLog("CocoaMQTT: PONG Received")
#endif
delegate?.mqttDidReceivePong(self)
}
func _nextMessageId() -> UInt16 {
if gmid == UInt16.max {
gmid = 0
}
gmid += 1
return gmid
}
}
/**
* MQTT Reader Delegate
*/
protocol CocoaMQTTReaderDelegate {
func didReceiveConnAck(reader: CocoaMQTTReader, connack: UInt8)
func didReceivePublish(reader: CocoaMQTTReader, message: CocoaMQTTMessage, id: UInt16)
func didReceivePubAck(reader: CocoaMQTTReader, msgid: UInt16)
func didReceivePubRec(reader: CocoaMQTTReader, msgid: UInt16)
func didReceivePubRel(reader: CocoaMQTTReader, msgid: UInt16)
func didReceivePubComp(reader: CocoaMQTTReader, msgid: UInt16)
func didReceiveSubAck(reader: CocoaMQTTReader, msgid: UInt16)
func didReceiveUnsubAck(reader: CocoaMQTTReader, msgid: UInt16)
func didReceivePong(reader: CocoaMQTTReader)
}
public class CocoaMQTTReader {
var socket: GCDAsyncSocket
var header: UInt8 = 0
var data: [UInt8] = []
var length: UInt = 0
var multiply: Int = 1
var delegate: CocoaMQTTReaderDelegate
var timeout: Int = 30000
init(socket: GCDAsyncSocket, delegate: CocoaMQTTReaderDelegate) {
self.socket = socket
self.delegate = delegate
}
func start() { readHeader() }
func readHeader() {
_reset(); socket.readDataToLength(1, withTimeout: -1, tag: CocoaMQTTReadTag.TAG_HEADER.rawValue)
}
func headerReady(header: UInt8) {
#if DEBUG
NSLog("CocoaMQTTReader: header ready: \(header) ")
#endif
self.header = header
readLength()
}
func readLength() {
socket.readDataToLength(1, withTimeout: NSTimeInterval(timeout), tag: CocoaMQTTReadTag.TAG_LENGTH.rawValue)
}
func lengthReady(byte: UInt8) {
length += (UInt)((Int)(byte & 127) * multiply)
if byte & 0x80 == 0 { //done
if length == 0 {
frameReady()
} else {
readPayload()
}
} else { //more
multiply *= 128
readLength()
}
}
func readPayload() {
socket.readDataToLength(length, withTimeout: NSTimeInterval(timeout), tag: CocoaMQTTReadTag.TAG_PAYLOAD.rawValue)
}
func payloadReady(data: NSData) {
self.data = [UInt8](count: data.length, repeatedValue: 0)
data.getBytes(&(self.data), length: data.length)
frameReady()
}
func frameReady() {
//handle frame
let frameType = CocoaMQTTFrameType(rawValue: UInt8(header & 0xF0))!
switch frameType {
case .CONNACK:
delegate.didReceiveConnAck(self, connack: data[1])
case .PUBLISH:
let (msgId, message) = unpackPublish()
delegate.didReceivePublish(self, message: message, id: msgId)
case .PUBACK:
delegate.didReceivePubAck(self, msgid: _msgid(data))
case .PUBREC:
delegate.didReceivePubRec(self, msgid: _msgid(data))
case .PUBREL:
delegate.didReceivePubRel(self, msgid: _msgid(data))
case .PUBCOMP:
delegate.didReceivePubComp(self, msgid: _msgid(data))
case .SUBACK:
delegate.didReceiveSubAck(self, msgid: _msgid(data))
case .UNSUBACK:
delegate.didReceiveUnsubAck(self, msgid: _msgid(data))
case .PINGRESP:
delegate.didReceivePong(self)
default:
break
}
readHeader()
}
func unpackPublish() -> (UInt16, CocoaMQTTMessage) {
let frame = CocoaMQTTFramePublish(header: header, data: data)
frame.unpack()
let msgId = frame.msgid!
let qos = CocoaMQTTQOS(rawValue: frame.qos)!
let message = CocoaMQTTMessage(topic: frame.topic!, payload: frame.payload, qos: qos, retained: frame.retained, dup: frame.dup)
return (msgId, message)
}
func _msgid(bytes: [UInt8]) -> UInt16 {
if bytes.count < 2 { return 0 }
return UInt16(bytes[0]) << 8 + UInt16(bytes[1])
}
func _reset() {
length = 0; multiply = 1; header = 0; data = []
}
}
| mit | e7d4845b4d5a077b31eeee18cb41856f | 25.559211 | 147 | 0.616671 | 4.228332 | false | false | false | false |
soapyigu/LeetCode_Swift | Math/ExcelSheetColumnNumber.swift | 1 | 629 | /**
* Question Link: https://leetcode.com/problems/excel-sheet-column-number/
* Primary idea: Classic Math problem, res = res * 26 + current
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class ExcelSheetColumnNumber {
func titleToNumber(s: String) -> Int {
var res = 0
let scalarsOfA = "A".unicodeScalars
for char in s.characters {
let scalars = String(char).unicodeScalars
let current = Int(scalars[scalars.startIndex].value - scalarsOfA[scalarsOfA.startIndex].value) + 1
res = res * 26 + current
}
return res
}
} | mit | b4526b626050e6eb781bfa0d4dc7abc0 | 29 | 110 | 0.604134 | 4.084416 | false | false | false | false |
miracl/amcl | version3/swift/dbig.swift | 1 | 7142 |
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
//
// dbig.swift
//
// Created by Michael Scott on 13/06/2015.
// Copyright (c) 2015 Michael Scott. All rights reserved.
//
public struct DBIG{
var w=[Chunk](repeating: 0,count: CONFIG_BIG.DNLEN)
public init() {
for i in 0 ..< CONFIG_BIG.DNLEN {w[i]=0}
}
public init(_ x: Int)
{
w[0]=Chunk(x);
for i in 1 ..< CONFIG_BIG.DNLEN {w[i]=0}
}
public init(_ x: BIG)
{
for i in 0 ..< CONFIG_BIG.NLEN {w[i]=x.w[i]}
w[CONFIG_BIG.NLEN-1]=x.w[CONFIG_BIG.NLEN-1]&CONFIG_BIG.BMASK
w[CONFIG_BIG.NLEN]=x.w[CONFIG_BIG.NLEN-1]>>Chunk(CONFIG_BIG.BASEBITS)
for i in CONFIG_BIG.NLEN+1 ..< CONFIG_BIG.DNLEN {w[i]=0}
}
public init(_ x: DBIG)
{
for i in 0 ..< CONFIG_BIG.DNLEN {w[i]=x.w[i]}
}
public init(_ x: [Chunk])
{
for i in 0 ..< CONFIG_BIG.DNLEN {w[i]=x[i]}
}
mutating func cmove(_ g: DBIG,_ d: Int)
{
let b = Chunk(-d)
for i in 0 ..< CONFIG_BIG.DNLEN
{
w[i]^=(w[i]^g.w[i])&b;
}
}
/* Copy from another DBIG */
mutating func copy(_ x: DBIG)
{
for i in 0 ..< CONFIG_BIG.DNLEN {w[i] = x.w[i]}
}
mutating func ucopy(_ x: BIG)
{
for i in 0 ..< CONFIG_BIG.NLEN {w[i] = 0}
for i in CONFIG_BIG.NLEN ..< CONFIG_BIG.DNLEN {w[i] = x.w[i-CONFIG_BIG.NLEN]}
}
/* this+=x */
mutating func add(_ x: DBIG)
{
for i in 0 ..< CONFIG_BIG.DNLEN
{
w[i]+=x.w[i]
}
}
/* this-=x */
mutating func sub(_ x: DBIG)
{
for i in 0 ..< CONFIG_BIG.DNLEN
{
w[i]-=x.w[i]
}
}
/* this-=x */
mutating func rsub(_ x: DBIG)
{
for i in 0 ..< CONFIG_BIG.DNLEN
{
w[i]=x.w[i]-w[i]
}
}
/* general shift left */
mutating func shl(_ k: UInt)
{
let n=k%CONFIG_BIG.BASEBITS
let m=Int(k/CONFIG_BIG.BASEBITS)
w[CONFIG_BIG.DNLEN-1]=((w[CONFIG_BIG.DNLEN-1-m]<<Chunk(n)))|(w[CONFIG_BIG.DNLEN-m-2]>>Chunk(CONFIG_BIG.BASEBITS-n))
for i in (m+1...CONFIG_BIG.DNLEN-2).reversed()
{
w[i]=((w[i-m]<<Chunk(n))&CONFIG_BIG.BMASK)|(w[i-m-1]>>Chunk(CONFIG_BIG.BASEBITS-n))
}
w[m]=(w[0]<<Chunk(n))&CONFIG_BIG.BMASK
for i in 0 ..< m {w[i]=0}
}
/* general shift right */
mutating func shr(_ k: UInt)
{
let n=k%CONFIG_BIG.BASEBITS
let m=Int(k/CONFIG_BIG.BASEBITS)
for i in 0 ..< CONFIG_BIG.DNLEN-m-1
{
w[i]=(w[m+i]>>Chunk(n))|((w[m+i+1]<<Chunk(CONFIG_BIG.BASEBITS-n))&CONFIG_BIG.BMASK)
}
w[CONFIG_BIG.DNLEN - m - 1]=w[CONFIG_BIG.DNLEN-1]>>Chunk(n)
for i in CONFIG_BIG.DNLEN - m ..< CONFIG_BIG.DNLEN {w[i]=0}
}
/* Compare a and b, return 0 if a==b, -1 if a<b, +1 if a>b. Inputs must be normalised */
static func comp(_ a: DBIG,_ b: DBIG) -> Int
{
for i in (0...CONFIG_BIG.DNLEN-1).reversed()
{
if (a.w[i]==b.w[i]) {continue}
if (a.w[i]>b.w[i]) {return 1}
else {return -1}
}
return 0;
}
/* set x = x mod 2^m */
mutating func mod2m(_ m: UInt)
{
let wd=Int(m/CONFIG_BIG.BASEBITS)
let bt=m%CONFIG_BIG.BASEBITS
let msk=Chunk(1<<bt)-1;
w[wd]&=msk;
for i in wd+1 ..< CONFIG_BIG.DNLEN {w[i]=0}
}
/* normalise BIG - force all digits < 2^BASEBITS */
mutating func norm()
{
var carry:Chunk=0
for i in 0 ..< CONFIG_BIG.DNLEN-1
{
let d=w[i]+carry
w[i]=d&CONFIG_BIG.BMASK
carry=d>>Chunk(CONFIG_BIG.BASEBITS)
}
w[CONFIG_BIG.DNLEN-1]+=carry
}
/* reduces this DBIG mod a BIG, and returns the BIG */
mutating func mod(_ c: BIG) -> BIG
{
var k:Int=0
norm()
var m=DBIG(c)
var r=DBIG(0)
if DBIG.comp(self,m)<0 {return BIG(self)}
repeat
{
m.shl(1)
k += 1
}
while (DBIG.comp(self,m)>=0);
while (k>0)
{
m.shr(1)
r.copy(self)
r.sub(m)
r.norm()
cmove(r,Int(1-((r.w[CONFIG_BIG.DNLEN-1]>>Chunk(CONFIG_BIG.CHUNK-1))&1)))
k -= 1
}
return BIG(self)
}
/* return this/c */
mutating func div(_ c:BIG) -> BIG
{
var k:Int=0
var m=DBIG(c)
var a=BIG(0)
var e=BIG(1)
var r=BIG(0)
var dr=DBIG(0)
norm()
while (DBIG.comp(self,m)>=0)
{
e.fshl(1)
m.shl(1)
k += 1
}
while (k>0)
{
m.shr(1)
e.shr(1)
dr.copy(self)
dr.sub(m)
dr.norm()
let d=Int(1-((dr.w[CONFIG_BIG.DNLEN-1]>>Chunk(CONFIG_BIG.CHUNK-1))&1))
cmove(dr,d)
r.copy(a)
r.add(e)
r.norm()
a.cmove(r,d)
k -= 1
}
return a
}
/* split DBIG at position n, return higher half, keep lower half */
mutating func split(_ n: UInt) -> BIG
{
var t=BIG(0)
let m=n%CONFIG_BIG.BASEBITS
var carry=w[CONFIG_BIG.DNLEN-1]<<Chunk(CONFIG_BIG.BASEBITS-m)
for i in (CONFIG_BIG.NLEN-1...CONFIG_BIG.DNLEN-2).reversed()
{
let nw=(w[i]>>Chunk(m))|carry;
carry=(w[i]<<Chunk(CONFIG_BIG.BASEBITS-m))&CONFIG_BIG.BMASK;
t.set(i-CONFIG_BIG.NLEN+1,nw);
}
w[CONFIG_BIG.NLEN-1]&=((1<<Chunk(m))-1);
return t;
}
/* return number of bits */
func nbits() -> Int
{
var k=(CONFIG_BIG.DNLEN-1)
var t=BIG(self)
t.norm()
while k>=0 && t.w[k]==0 {k -= 1}
if k<0 {return 0}
var bts=Int(CONFIG_BIG.BASEBITS)*k
var c=t.w[k];
while c != 0 {c/=2; bts+=1}
return bts
}
/* Convert to Hex String */
public func toString() -> String
{
_ = DBIG()
var s:String=""
var len=nbits()
if len%4 == 0 {len/=4}
else {len/=4; len += 1}
for i in (0...len-1).reversed()
{
var b = DBIG(self)
b.shr(UInt(i*4))
let n=String(b.w[0]&15,radix:16,uppercase:false)
s+=n
}
return s
}
}
| apache-2.0 | 64fd124c828eaadbf18b6d19c0e8a635 | 24.783394 | 123 | 0.49706 | 2.95735 | false | true | false | false |
artyom-stv/TextInputKit | TextInputKit/TextInputKit/Code/SpecializedTextInput/BankCardNumber/BankCardNumberUtils.swift | 1 | 8762 | //
// BankCardNumberUtils.swift
// TextInputKit
//
// Created by Artem Starosvetskiy on 30/11/2016.
// Copyright © 2016 Artem Starosvetskiy. All rights reserved.
//
import Foundation
struct BankCardNumberUtils {
private init() {}
}
extension BankCardNumberUtils {
static func cardNumberDigitsStringView(
from stringView: String.UnicodeScalarView
) -> String.UnicodeScalarView? {
return StringUtils.stringView(
from: stringView,
preservingCharacters: CharacterSet.decimalDigits,
ignoringCharacters: cardNumberWhitespaces)
}
static func cardNumberDigitsStringViewAndRange(
from stringView: String.UnicodeScalarView,
range: Range<String.UnicodeScalarIndex>
) -> (String.UnicodeScalarView, Range<String.UnicodeScalarIndex>)? {
return StringUtils.stringViewAndRange(
from: stringView,
range: range,
preservingCharacters: CharacterSet.decimalDigits,
ignoringCharacters: cardNumberWhitespaces)
}
private static let cardNumberWhitespaces = CharacterSet(charactersIn: " ")
}
extension BankCardNumberUtils {
static func cardNumberStringView(
fromDigits digitsStringView: String.UnicodeScalarView,
withLength digitsStringViewLength: Int,
sortedSpacesPositions: [Int]) -> String.UnicodeScalarView {
// TODO: Optimize the implementation.
assert(String(digitsStringView).rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil)
assert(digitsStringView.count == digitsStringViewLength)
assert(sortedSpacesPositions.sorted() == sortedSpacesPositions)
var cardNumberStringView = "".unicodeScalars
cardNumberStringView.reserveCapacity(digitsStringViewLength + sortedSpacesPositions.count)
var spacesPositionsIterator = sortedSpacesPositions.makeIterator()
var nextSpacePosition: Int? = spacesPositionsIterator.next()
for (position, character) in digitsStringView.enumerated() {
if let spacePosition: Int = nextSpacePosition, spacePosition == position {
cardNumberStringView.append(UnicodeScalar(" "))
nextSpacePosition = spacesPositionsIterator.next()
}
cardNumberStringView.append(character)
}
return cardNumberStringView
}
static func cardNumberStringViewAndIndex(
fromDigits digitsStringView: String.UnicodeScalarView,
withLength digitsStringViewLength: Int,
index digitsStringViewIndex: String.UnicodeScalarIndex,
sortedSpacesPositions: [Int]) -> (String.UnicodeScalarView, String.UnicodeScalarIndex) {
assert(String(digitsStringView).rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil)
assert(digitsStringView.count == digitsStringViewLength)
assert(digitsStringViewIndex >= digitsStringView.startIndex && digitsStringViewIndex <= digitsStringView.endIndex)
assert(sortedSpacesPositions.sorted() == sortedSpacesPositions)
var cardNumberStringView = "".unicodeScalars
cardNumberStringView.reserveCapacity(digitsStringViewLength + sortedSpacesPositions.count)
var resultingIndex = cardNumberStringView.startIndex
var spacesPositionsIterator = sortedSpacesPositions.makeIterator()
var nextSpacePosition = spacesPositionsIterator.next()
for (index, positionAndCharacter) in zip(digitsStringView.indices, digitsStringView.enumerated()) {
let (position, character) = positionAndCharacter
if index == digitsStringViewIndex {
resultingIndex = cardNumberStringView.endIndex
}
if let spacePosition = nextSpacePosition, spacePosition == position {
cardNumberStringView.append(UnicodeScalar(" "))
nextSpacePosition = spacesPositionsIterator.next()
}
cardNumberStringView.append(character)
}
if digitsStringViewIndex == digitsStringView.endIndex {
resultingIndex = cardNumberStringView.endIndex
}
return (cardNumberStringView, resultingIndex)
}
}
extension BankCardNumberUtils {
struct IinRangeInfo {
let range: CountableClosedRange<Int>
let cardBrand: BankCardBrand
let maxCardNumberLength: Int
fileprivate init(_ range: CountableClosedRange<Int>, _ cardBrand: BankCardBrand, _ maxCardNumberLength: Int) {
self.range = range
self.cardBrand = cardBrand
self.maxCardNumberLength = maxCardNumberLength
}
}
/// Determines a range of IINs which may correspond to a partial or full bank card number.
///
/// - SeeAlso:
/// [Issuer identification number (IIN)](https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_.28IIN.29)
///
/// - Parameters:
/// - digitsString: A string of digits representing a bank card number.
/// - digitsStringLength: The length of `digitsString`. Passed here for an optimization purpose
/// (not to recalculate the length several times).
/// - Returns:
/// The IINs range which may correspond to a partial or full bank card number represented by a string of digits.
/// In a special case, when `digitsStringLength` is greater or equal to 6, the returned range contains only one IIN.
static func iinRange(
fromDigitsString digitsString: String,
withLength digitsStringLength: Int) -> Range<Int> {
assert(digitsString.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil)
assert(digitsString.count == digitsStringLength)
let iinRangeStart: Int = {
let iinString = digitsStringLength == iinLength
? digitsString
: digitsString.padding(toLength: iinLength, withPad: "0", startingAt: 0)
return Int(iinString)!
}()
let iinRangeLength: Int = {
var iinRangeLength = 1
if digitsStringLength < iinLength {
for _ in CountableRange(uncheckedBounds: (lower: 0, upper: iinLength - digitsStringLength)) {
iinRangeLength = iinRangeLength &* 10
}
}
return iinRangeLength
}()
return iinRangeStart ..< (iinRangeStart + iinRangeLength)
}
static func info(forIinRange iinRange: Range<Int>) -> IinRangeInfo? {
let iinRange = ClosedRange(iinRange)
guard let index = iinRangesInfo.firstIndex(where: { $0.range.contains(iinRange) }) else {
return nil
}
return iinRangesInfo[index]
}
private static let iinLength = 6
private static let iinRangesInfo: [IinRangeInfo] = [
// TODO: Fill the missing ranges (if they are allocated).
.init(100000...199999, .uatp, 15),
// .init(200000...222099, ., 16),
.init(222100...272099, .masterCard, 16),
// .init(272100...299999, ., 16),
.init(300000...305999, .dinersClub, 14),
// .init(306000...308999, ., 16),
.init(309000...309999, .dinersClub, 14),
// .init(310000...339999, ., 16),
.init(340000...349999, .amex, 15),
// .init(350000...352799, ., 16),
.init(352800...358999, .jcb, 16),
// .init(359000...359999, ., 16),
.init(360000...369999, .dinersClub, 14),
.init(370000...379999, .amex, 15),
.init(380000...399999, .dinersClub, 14),
.init(400000...499999, .visa, 16),
.init(500000...509999, .maestro, 16),
.init(510000...559999, .masterCard, 16),
.init(560000...599999, .maestro, 16),
// .init(600000...601099, ., 16),
.init(601100...601199, .discover, 16),
// .init(601200...609999, ., 16),
.init(610000...619999, .maestro, 16),
.init(620000...629999, .unionPay, 16), // 19?
.init(630000...639999, .maestro, 16),
// .init(640000...643999, ., 16),
.init(644000...659999, .discover, 16),
.init(660000...699999, .maestro, 16),
// .init(700000...799999, ., 16),
// .init(800000...879999, ., 16),
.init(880000...889999, .unionPay, 16),
// .init(890000...899999, ., 16),
// .init(900000...999999, ., 16),
]
}
extension BankCardNumberUtils {
static func sortedSpacesPositions(for cardBrand: BankCardBrand?) -> [Int] {
switch cardBrand {
case .some(.uatp):
return [4, 9]
case .some(.amex):
return [4, 10]
default:
return [4, 8, 12]
}
}
}
| mit | 4b1c409c1e159be3d64210c287f0dd51 | 35.810924 | 136 | 0.637256 | 4.615911 | false | false | false | false |
Gregsen/okapi | MXStatusMenu/StatusView.swift | 1 | 4566 | import Cocoa
import Darwin
/// The StatusView reflects the current cpu/network load
class StatusView: NSView {
/// The reference to the StatusController
unowned let statusController: StatusController
/// The fill color of the cpu load bars
lazy var cpuColor = NSColor(calibratedWhite: 0.22, alpha: 1.0)
/// The fill color of the network download bars
lazy var networkInputColor = NSColor(calibratedRed: 0.15, green: 0.15, blue: 0.9, alpha: 1.0)
/// The fill color of the network upload bars
lazy var networkOutputColor = NSColor(calibratedRed: 1.0, green: 0.5, blue: 0.0, alpha: 1.0)
/// The stroke color of the load bars
lazy var strokeColor = NSColor(calibratedWhite: 0.5, alpha: 0.3)
var counter: Double = 0
// Points on the graph
var pointsY = [Double]()
/// The background gradient of the load bars
lazy var backgroundGradient = NSGradient(colors: [
NSColor(calibratedWhite: 0.5, alpha: 0.25),
NSColor(calibratedWhite: 0.5, alpha: 0),
NSColor(calibratedWhite: 0.5, alpha: 0.25)])
/// Initialize the StatusView with a reference to the StatusController
init(frame frameRect: NSRect, statusController: StatusController) {
self.statusController = statusController
super.init(frame: frameRect)
}
/// Required initializer for NSView subclasses
convenience required init?(coder: NSCoder) {
self.init(frame: NSMakeRect(0, 0, 0, 0), statusController: StatusController())
}
/// Get the necessary width of the NSStatusItem for a given number of cpu threads
class func widthOfCPUCount(cpuCount: Int) -> CGFloat {
let cpuCount = CGFloat(cpuCount)
return LeftMargin + (2 + cpuCount) * BarWidth + (1 + cpuCount) * GapBetweenBars + RightMargin
}
/// Draw the load bar
func drawBarInFrame(frame: NSRect, fillColor: NSColor, percentage: Double) {
backgroundGradient!.drawInRect(frame, angle: 0)
strokeColor.setStroke()
NSBezierPath.strokeRect(frame)
let loadHeight = CGFloat(floor((Double(frame.size.height) + 1) * percentage))
let loadFrame = NSMakeRect(frame.origin.x - 0.5, frame.origin.y - 0.5, frame.size.width + 1, loadHeight)
fillColor.setFill()
NSBezierPath.fillRect(loadFrame)
}
func drawChartInFrame( percentage: Double) {
// Init path and and starting point
let path = NSBezierPath()
if pointsY.count == 0{
path.moveToPoint(NSPoint(x:0, y:0))
} else {
path.moveToPoint(NSPoint(x:0, y:pointsY[0]))
}
// Fill points should hold 50 values. Fill the list with each call until there are 50 values.
// For every subsequent call to this method, remove first item, add new one to the end.
// the size (count) directly influences the width in the menuBar
if pointsY.count < 51{
pointsY.append(percentage * 10)
} else if pointsY.count >= 50 {
pointsY.removeAtIndex(1)
pointsY.append(percentage * 10)
}
NSLog("percentage in draw function: \(percentage)")
// Draw the line (love isn't always on time)
for i:Int in 0...pointsY.count {
path.lineToPoint(NSPoint(x:Double(i), y:pointsY[i]))
}
path.lineToPoint(NSPoint(x:pointsY.count, y:0))
path.flatness = 0.01
path.lineWidth = 1.0
path.fill()
path.stroke()
path.closePath()
}
/// Draw the contents of the StatusView
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
var frame = NSMakeRect(LeftMargin, 3.5, BarWidth, 20)
var loadAverage: Double = 0
// drawChartInFrame(longFrame, fillColor: networkOutputColor, percentage: 0.5)
frame.origin.x += ((BarWidth + GapBetweenBars)*2)
// draw the network bars
drawBarInFrame(frame, fillColor: networkInputColor, percentage: statusController.networkLoad.input)
frame.origin.x += (BarWidth + GapBetweenBars)
drawBarInFrame(frame, fillColor: networkOutputColor, percentage: statusController.networkLoad.output)
frame.origin.x += (BarWidth + GapBetweenBars)
// draw the cpu bars
for load in statusController.cpuLoad {
drawBarInFrame(frame, fillColor: cpuColor, percentage: load)
loadAverage += load
frame.origin.x += (BarWidth + GapBetweenBars)
NSLog("load: \(load)")
NSLog("loadAverage in load loop: \(loadAverage)")
}
NSLog("fin")
loadAverage = loadAverage / Double(statusController.cpuLoad.count)
drawChartInFrame(loadAverage*10)
}
}
| mit | 28ddac832d3c5d283944a882bc12c87d | 35.822581 | 106 | 0.67039 | 3.856419 | false | false | false | false |
mleiv/MEGameTracker | MEGameTracker/Views/Common/Data Rows/Base/Text Data Row/TextDataRowType.swift | 1 | 1473 | //
// TextDataRowType.swift
// MEGameTracker
//
// Created by Emily Ivie on 9/2/16.
// Copyright © 2016 Emily Ivie. All rights reserved.
//
import UIKit
public protocol TextDataRowType {
var row: TextDataRow? { get set }
var text: String? { get }
var linkOriginController: UIViewController? { get }
var isHideOnEmpty: Bool { get }
mutating func setupView()
mutating func setupView<T: TextDataRow>(type: T.Type)
mutating func setup(view: UIView?)
func startListeners()
}
extension TextDataRowType {
public var text: String? { return nil }
public var linkOriginController: UIViewController? { return nil }
public var isHideOnEmpty: Bool { return true }
public mutating func setupView<T: TextDataRow>(type: T.Type) {
guard let row = row,
let view = row.attachOrAttachedNib() as? T,
!view.isSettingUp else { return }
view.isSettingUp = true
view.textView?.text = text
view.textView?.linkOriginController = linkOriginController
setup(view: view)
view.setupTableHeader()
hideEmptyView(view: row)
view.textView?.layoutSubviews()
if !UIWindow.isInterfaceBuilder && !view.didSetup {
startListeners()
}
view.isSettingUp = false
row.didSetup = true
}
public mutating func setup(view: UIView?) {}
public mutating func open(sender: UIButton) {}
public func hideEmptyView(view: UIView?) {
view?.isHidden = isHideOnEmpty && !UIWindow.isInterfaceBuilder && (text ?? "").isEmpty
}
public func startListeners() {}
}
| mit | 0a3e7da2c6003e1e6db201a3c31e2216 | 23.533333 | 88 | 0.717391 | 3.634568 | false | false | false | false |
AnarchyTools/atpkg | src/ExternalDependency.swift | 1 | 3679 | // Copyright (c) 2016 Anarchy Tools Contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import atfoundation
final public class ExternalDependency {
public enum VersioningMethod {
case Version([String])
case Commit(String)
case Branch(String)
case Tag(String)
}
public enum DependencyType {
case Git
case Manifest
}
///- note: This may be an HTTP-style URL or a SSH-style URL
public var url: String
public var version: VersioningMethod
public var channels: [String]?
public var dependencyType: DependencyType
///atpm sets this value when it parses the name from the manifest.
///This value is then returned from `name` on request.
///Therefore, we "learn" the value of a remote package name after parsing its manifest.
///- warning: This API is particular to atpm, it is probably not useful unless you are working on that project
public var _parsedNameFromManifest: String? = nil
///Custom info available for use by the application.
///In practice, this is used to hold lock information for atpm
public var _applicationInfo: Any? = nil
///If non-nil, the dependency should only be loaded if the user specifies one of the strings in the array
public var ifIncluding: [String]? = nil
///The reference to the containing package
public var package: Package
///The name of the dependency.
///Note that if the dependency points to a manifest, the name is not known.
public var name: String? {
if self.dependencyType == .Manifest {
if let p = _parsedNameFromManifest { return p }
return nil
}
if let lastComponent = url.split(string: "/").last {
if lastComponent.hasSuffix(".git") {
return lastComponent.subString(toIndex: lastComponent.index(lastComponent.endIndex, offsetBy: -4))
}
return lastComponent
} else {
return nil
}
}
private init?(url: String, versionMethod: VersioningMethod, channels: [String]?, package: Package) {
self.package = package
self.url = url
self.version = versionMethod
self.channels = channels
if url.hasSuffix(".atpkg") {
self.dependencyType = .Manifest
}
else { self.dependencyType = .Git }
}
convenience init?(url: String, version: [String], channels: [String]?, package: Package) {
self.init(url: url, versionMethod: .Version(version), channels: channels, package: package)
}
convenience init?(url: String, commit: String, channels: [String]?, package: Package) {
self.init(url: url, versionMethod: .Commit(commit), channels: channels, package: package)
}
convenience init?(url: String, branch: String, channels: [String]?, package: Package) {
self.init(url: url, versionMethod: .Branch(branch), channels: channels, package: package)
}
convenience init?(url: String, tag: String, channels: [String]?, package: Package) {
self.init(url: url, versionMethod: .Tag(tag), channels: channels, package: package)
}
} | apache-2.0 | 87e8ba0ba74dac016b6dbce8acba55c5 | 38.148936 | 114 | 0.666214 | 4.464806 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/ReadingListDetailUnderBarViewController.swift | 1 | 9938 | protocol ReadingListDetailUnderBarViewControllerDelegate: AnyObject {
func readingListDetailUnderBarViewController(_ underBarViewController: ReadingListDetailUnderBarViewController, didEdit name: String?, description: String?)
func readingListDetailUnderBarViewController(_ underBarViewController: ReadingListDetailUnderBarViewController, didBeginEditing textField: UITextField)
func readingListDetailUnderBarViewController(_ underBarViewController: ReadingListDetailUnderBarViewController, titleTextFieldTextDidChange textField: UITextField)
func readingListDetailUnderBarViewController(_ underBarViewController: ReadingListDetailUnderBarViewController, titleTextFieldWillClear textField: UITextField)
}
class ReadingListDetailUnderBarViewController: UIViewController {
@IBOutlet private weak var articleCountLabel: UILabel!
@IBOutlet private weak var titleTextField: ThemeableTextField!
@IBOutlet private weak var descriptionTextField: ThemeableTextField!
@IBOutlet private weak var alertStackView: UIStackView?
@IBOutlet private weak var alertTitleLabel: UILabel?
@IBOutlet private weak var alertMessageLabel: UILabel?
private var readingListTitle: String?
private var readingListDescription: String?
private var listLimit: Int = 0
private var entryLimit: Int = 0
public weak var delegate: ReadingListDetailUnderBarViewControllerDelegate?
private var theme: Theme = Theme.standard
private var firstResponder: UITextField? = nil
override func viewDidLoad() {
super.viewDidLoad()
titleTextField.isUnderlined = false
titleTextField.returnKeyType = .done
titleTextField.enablesReturnKeyAutomatically = true
descriptionTextField.isUnderlined = false
descriptionTextField.returnKeyType = .done
descriptionTextField.enablesReturnKeyAutomatically = true
titleTextField.delegate = self
descriptionTextField.delegate = self
alertTitleLabel?.numberOfLines = 0
alertMessageLabel?.numberOfLines = 0
updateFonts()
apply(theme: theme)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateFonts()
}
private func updateFonts() {
articleCountLabel.font = UIFont.wmf_font(.semiboldFootnote, compatibleWithTraitCollection: traitCollection)
titleTextField.font = UIFont.wmf_font(.boldTitle1, compatibleWithTraitCollection: traitCollection)
descriptionTextField.font = UIFont.wmf_font(.footnote, compatibleWithTraitCollection: traitCollection)
alertTitleLabel?.font = UIFont.wmf_font(.semiboldCaption2, compatibleWithTraitCollection: traitCollection)
alertMessageLabel?.font = UIFont.wmf_font(.caption2, compatibleWithTraitCollection: traitCollection)
}
// Int64 instead of Int to so that we don't have to cast countOfEntries: Int64 property of ReadingList object to Int.
var articleCount: Int64 = 0 {
didSet {
guard viewIfLoaded != nil else {
return
}
articleCountLabel.text = String.localizedStringWithFormat(CommonStrings.articleCountFormat, articleCount).uppercased()
}
}
public func updateArticleCount(_ count: Int64) {
articleCount = count
}
private var alertType: ReadingListAlertType? {
didSet {
guard let alertType = alertType else {
return
}
switch alertType {
case .listLimitExceeded(let limit):
let alertTitleFormat = WMFLocalizedString("reading-list-list-limit-exceeded-title", value: "You have exceeded the limit of {{PLURAL:%1$d|%1$d reading list|%1$d reading lists}} per account.", comment: "Informs the user that they have reached the allowed limit of reading lists per account. %1$d will be replaced with the maximum number of allowed lists")
let alertMessageFormat = WMFLocalizedString("reading-list-list-limit-exceeded-message", value: "This reading list and the articles saved to it will not be synced, please decrease your number of lists to %1$d to resume syncing of this list.", comment: "Informs the user that the reading list and its articles will not be synced until the number of lists is decreased. %1$d will be replaced with the maximimum number of allowed lists.")
alertTitleLabel?.text = String.localizedStringWithFormat(alertTitleFormat, limit)
alertMessageLabel?.text = String.localizedStringWithFormat(alertMessageFormat, limit)
case .entryLimitExceeded(let limit):
let alertTitleFormat = WMFLocalizedString("reading-list-entry-limit-exceeded-title", value: "You have exceeded the limit of {{PLURAL:%1$d|%1$d article|%1$d articles}} per account.", comment: "Informs the user that they have reached the allowed limit of articles per account. %1$d will be replaced with the maximum number of allowed articles")
let alertMessageFormat = WMFLocalizedString("reading-list-entry-limit-exceeded-message", value: "Please decrease your number of articles in this list to %1$d to resume syncing of all articles in this list.", comment: "Informs the user that the reading list and its articles will not be synced until the number of articles in the list is decreased. %1$d will be replaced with the maximum number of allowed articles in a list")
alertTitleLabel?.text = String.localizedStringWithFormat(alertTitleFormat, limit)
alertMessageLabel?.text = String.localizedStringWithFormat(alertMessageFormat, limit)
default:
break
}
}
}
public func setup(for readingList: ReadingList, listLimit: Int, entryLimit: Int) {
self.listLimit = listLimit
self.entryLimit = entryLimit
let readingListName = readingList.name
let readingListDescription = readingList.isDefault ? CommonStrings.readingListsDefaultListDescription : readingList.readingListDescription
let isDefault = readingList.isDefault
titleTextField.text = readingListName
readingListTitle = readingListName
descriptionTextField.text = readingListDescription
self.readingListDescription = readingListDescription
titleTextField.isEnabled = !isDefault
descriptionTextField.isEnabled = !isDefault
updateArticleCount(readingList.countOfEntries)
setAlertType(for: readingList.APIError, listLimit: listLimit, entryLimit: entryLimit)
}
private func setAlertType(for error: APIReadingListError?, listLimit: Int, entryLimit: Int) {
guard let error = error else {
isAlertViewHidden = true
return
}
switch error {
case .listLimit:
alertType = .listLimitExceeded(limit: listLimit)
isAlertViewHidden = false
case .entryLimit:
alertType = .entryLimitExceeded(limit: entryLimit)
isAlertViewHidden = false
default:
isAlertViewHidden = true
}
}
private var isAlertViewHidden: Bool = true {
didSet {
alertStackView?.spacing = isAlertViewHidden ? 0 : 7
alertStackView?.isHidden = isAlertViewHidden
}
}
public func reconfigureAlert(for readingList: ReadingList) {
setAlertType(for: readingList.APIError, listLimit: listLimit, entryLimit: entryLimit)
}
public func dismissKeyboardIfNecessary() {
firstResponder?.resignFirstResponder()
}
public func beginEditing() {
firstResponder = titleTextField
titleTextField.becomeFirstResponder()
}
public func cancelEditing() {
titleTextField.text = readingListTitle
descriptionTextField.text = readingListDescription
dismissKeyboardIfNecessary()
}
public func finishEditing() {
delegate?.readingListDetailUnderBarViewController(self, didEdit: titleTextField.text, description: descriptionTextField.text)
dismissKeyboardIfNecessary()
}
@IBAction func titleTextFieldTextDidChange(_ sender: UITextField) {
delegate?.readingListDetailUnderBarViewController(self, titleTextFieldTextDidChange: sender)
}
}
extension ReadingListDetailUnderBarViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
finishEditing()
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
firstResponder = textField
delegate?.readingListDetailUnderBarViewController(self, didBeginEditing: textField)
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
if textField == titleTextField {
delegate?.readingListDetailUnderBarViewController(self, titleTextFieldWillClear: textField)
}
return true
}
}
extension ReadingListDetailUnderBarViewController: Themeable {
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.paperBackground
articleCountLabel.textColor = theme.colors.secondaryText
articleCountLabel.backgroundColor = view.backgroundColor
titleTextField.apply(theme: theme)
alertTitleLabel?.backgroundColor = view.backgroundColor
alertMessageLabel?.backgroundColor = view.backgroundColor
descriptionTextField.apply(theme: theme)
descriptionTextField.textColor = theme.colors.secondaryText
alertTitleLabel?.textColor = theme.colors.error
alertMessageLabel?.textColor = theme.colors.primaryText
}
}
| mit | 89f109d40aa7eabdf3635038f59c5a0c | 47.009662 | 450 | 0.712014 | 5.747831 | false | false | false | false |
gaowanli/PinGo | PinGo/PinGo/Other/Tool/String+Extension.swift | 1 | 1559 | //
// String+Extension.swift
// PinGo
//
// Created by GaoWanli on 16/1/31.
// Copyright © 2016年 GWL. All rights reserved.
//
import UIKit
extension String {
static func size(withText text: String, withFont font: UIFont, andMaxSize maxSize: CGSize) -> CGSize {
return text.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: [ NSFontAttributeName: font ], context: nil).size
}
/**
根据日期字符串计算年龄
- parameter style: 日期字符串格式
- returns: 年龄
*/
func age(withStyle style: dateFormatStyle) -> Int {
if let date = Date.formatterWithStyle(withStyle: style).date(from: self) {
let interval = date.timeIntervalSinceNow
return abs(Int(trunc(interval / (60 * 60 * 24)) / 365))
}
return 0
}
/**
根据时间戳转换显示字符串
- parameter style: 要转换成的格式
- returns: 格式化后的字符串
*/
func dateString(toStyle style: dateFormatStyle) -> String? {
if let date = Date.dateWithTimeStamp(self) {
let components = date.componentsDeltaWithNow()
if components.day! <= 5 {
if (components.day! < 1) {
return "\(components.hour)小时前"
}else {
return "\(components.day)天前"
}
}else {
return date.string(withStyle: style)
}
}
return nil
}
}
| mit | 8f25695db8432bf8866bef6fa74cace6 | 25.888889 | 143 | 0.551653 | 4.321429 | false | false | false | false |
wunshine/FoodStyle | FoodStyle/FoodStyle/Classes/View/DiaryTableViewCell.swift | 1 | 4467 | //
// DiaryTableViewCell.swift
// FoodStyle
//
// Created by Woz Wong on 16/3/23.
// Copyright © 2016年 code4Fun. All rights reserved.
//
import UIKit
class DiaryCell : UITableViewCell {
var model:DiaryCellModel{
get{
return DiaryCellModel()
}
set{
self.model = newValue
}
}
var picture:UIImageView = {
var pic = UIImageView(image: UIImage(named: "coreAnimation"))
return pic
}()
var diaryName:UILabel = {
let name = UILabel()
name.text = "奶油蛋糕"
name.sizeToFit()
return name
}()
var title:UILabel = {
let title = UILabel()
title.font = UIFont.systemFontOfSize(10)
title.text = "#吃货志#"
title.sizeToFit()
return title
}()
var zan:UIButton = {
var zan = UIButton()
zan.layer.cornerRadius = 3
zan.backgroundColor = GLOBAL_COLOR()
zan.setTitle("赞", forState: UIControlState.Normal)
zan.setTitle("已赞", forState: UIControlState.Selected)
zan.setImage(UIImage(named: "diary_liked"), forState: UIControlState.Selected)
zan.setImage(UIImage(named: "diary_like"), forState: UIControlState.Normal)
return zan
}()
var comment:UIButton = {
var comment = UIButton()
comment.layer.cornerRadius = 3
comment.backgroundColor = GLOBAL_COLOR()
comment.setTitle("评论", forState: UIControlState.Normal)
comment.setImage(UIImage(named: "diary_comment"), forState: UIControlState.Normal)
return comment
}()
var more:UIButton = {
var more = UIButton()
more.backgroundColor = UIColor.lightGrayColor()
more.layer.cornerRadius = 3
more.setImage(UIImage(named: "diary_menu"), forState: UIControlState.Normal)
return more
}()
var zanedPeople:UICollectionView = {
var layout = UICollectionViewFlowLayout()
layout.itemSize = CGSizeMake(SCREEN_RECT().width-20/8,44)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
var people = UICollectionView(frame: CGRectMake(0,0,SCREEN_RECT().width-20,44), collectionViewLayout: layout)
var item = UICollectionViewCell()
people.backgroundColor = UIColor.yellowColor()
people.contentSize = CGSizeMake(SCREEN_RECT().width-20,44)
item.contentView.addSubview(UIButton())
return people
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(picture)
addSubview(title)
addSubview(diaryName)
addSubview(zan)
addSubview(zanedPeople)
addSubview(comment)
addSubview(more)
}
required init?(coder aDecoder: NSCoder) {
fatalError("not imped")
}
override func layoutSubviews() {
super.layoutSubviews()
picture.snp_makeConstraints { (make) -> Void in
make.width.equalTo(self)
make.height.equalTo(200)
make.top.equalTo(self.snp_top)
}
diaryName.snp_makeConstraints { (make) -> Void in
make.top.equalTo(picture.snp_bottom).offset(20)
make.left.equalTo(self).offset(20)
make.height.equalTo(20)
}
title.snp_makeConstraints { (make) -> Void in
make.top.equalTo(diaryName.snp_bottom).offset(10)
make.left.equalTo(diaryName.snp_left)
make.height.equalTo(20)
}
zanedPeople.snp_makeConstraints { (make) -> Void in
make.top.equalTo(title.snp_bottom).offset(20)
make.centerX.equalTo(self.snp_centerX)
}
zan.snp_makeConstraints { (make) -> Void in
make.top.equalTo(zanedPeople.snp_bottom).offset(10)
make.left.equalTo(diaryName.snp_left)
make.width.equalTo(60)
make.height.equalTo(25)
}
comment.snp_makeConstraints { (make) -> Void in
make.left.equalTo(zan.snp_right).offset(20)
make.top.equalTo(zan.snp_top)
make.height.width.equalTo(zan)
}
more.snp_makeConstraints { (make) -> Void in
make.right.equalTo(self).offset(-10)
make.top.equalTo(comment.snp_top)
make.width.equalTo(40)
make.height.equalTo(comment)
}
}
}
| mit | aede92914bbecfe193a050a30968a908 | 30.048951 | 117 | 0.604054 | 4.27334 | false | false | false | false |
zvonler/PasswordElephant | external/github.com/apple/swift-protobuf/Sources/SwiftProtobuf/BinaryEncoder.swift | 9 | 4034 | // Sources/SwiftProtobuf/BinaryEncoder.swift - Binary encoding support
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Core support for protobuf binary encoding. Note that this is built
/// on the general traversal machinery.
///
// -----------------------------------------------------------------------------
import Foundation
/*
* Encoder for Binary Protocol Buffer format
*/
internal struct BinaryEncoder {
private var pointer: UnsafeMutablePointer<UInt8>
init(forWritingInto pointer: UnsafeMutablePointer<UInt8>) {
self.pointer = pointer
}
private mutating func append(_ byte: UInt8) {
pointer.pointee = byte
pointer = pointer.successor()
}
private mutating func append(contentsOf data: Data) {
let count = data.count
data.copyBytes(to: pointer, count: count)
pointer = pointer.advanced(by: count)
}
private mutating func append(contentsOf bufferPointer: UnsafeBufferPointer<UInt8>) {
let count = bufferPointer.count
pointer.assign(from: bufferPointer.baseAddress!, count: count)
pointer = pointer.advanced(by: count)
}
func distance(pointer: UnsafeMutablePointer<UInt8>) -> Int {
return pointer.distance(to: self.pointer)
}
mutating func appendUnknown(data: Data) {
append(contentsOf: data)
}
mutating func startField(fieldNumber: Int, wireFormat: WireFormat) {
startField(tag: FieldTag(fieldNumber: fieldNumber, wireFormat: wireFormat))
}
mutating func startField(tag: FieldTag) {
putVarInt(value: UInt64(tag.rawValue))
}
mutating func putVarInt(value: UInt64) {
var v = value
while v > 127 {
append(UInt8(v & 0x7f | 0x80))
v >>= 7
}
append(UInt8(v))
}
mutating func putVarInt(value: Int64) {
putVarInt(value: UInt64(bitPattern: value))
}
mutating func putVarInt(value: Int) {
putVarInt(value: Int64(value))
}
mutating func putZigZagVarInt(value: Int64) {
let coded = ZigZag.encoded(value)
putVarInt(value: coded)
}
mutating func putBoolValue(value: Bool) {
append(value ? 1 : 0)
}
mutating func putFixedUInt64(value: UInt64) {
var v = value.littleEndian
let n = MemoryLayout<UInt64>.size
memcpy(pointer, &v, n)
pointer = pointer.advanced(by: n)
}
mutating func putFixedUInt32(value: UInt32) {
var v = value.littleEndian
let n = MemoryLayout<UInt32>.size
memcpy(pointer, &v, n)
pointer = pointer.advanced(by: n)
}
mutating func putFloatValue(value: Float) {
let n = MemoryLayout<Float>.size
var v = value
var nativeBytes: UInt32 = 0
memcpy(&nativeBytes, &v, n)
var littleEndianBytes = nativeBytes.littleEndian
memcpy(pointer, &littleEndianBytes, n)
pointer = pointer.advanced(by: n)
}
mutating func putDoubleValue(value: Double) {
let n = MemoryLayout<Double>.size
var v = value
var nativeBytes: UInt64 = 0
memcpy(&nativeBytes, &v, n)
var littleEndianBytes = nativeBytes.littleEndian
memcpy(pointer, &littleEndianBytes, n)
pointer = pointer.advanced(by: n)
}
// Write a string field, including the leading index/tag value.
mutating func putStringValue(value: String) {
let count = value.utf8.count
putVarInt(value: count)
for b in value.utf8 {
pointer.pointee = b
pointer = pointer.successor()
}
}
mutating func putBytesValue(value: Data) {
putVarInt(value: value.count)
append(contentsOf: value)
}
}
| gpl-3.0 | 926ddc292937ee4fe3ccbdbff6ba117a | 28.881481 | 88 | 0.612048 | 4.384783 | false | false | false | false |
bvanzile/StarHero | StarHero/Objects/Fighter Ship/FighterShipTurnToLookState.swift | 1 | 2571 | //
// FighterShipTurnToLookState.swift
// StarHero
//
// Created by Bryan Van Zile on 5/26/19.
// Copyright © 2019 Bryan Van Zile. All rights reserved.
//
import Foundation
class FighterShipTurnToLookState: State {
// Singleton instance to pass to the state machine
static var sharedInstance: FighterShipTurnToLookState = FighterShipTurnToLookState()
// Initializer, private as this shouldn't be initialized outside of the singleton
private init() { }
// Function for entering into a state
func enter(object: BaseObject) {
if let fighterShip = object as? FighterShip {
// If we see an enemy ship, start attacking it
if fighterShip.seesAttackableEnemy() {
// Begin the pursuit on the closest fighter ship in vision
if let closest = fighterShip.getClosestEnemyToAttack() {
// Start going after the closest ship
fighterShip.steeringBehavior?.setToPursue(target: closest)
fighterShip.stateMachine?.changeState(newState: FighterShipAttackState.sharedInstance)
}
else {
fighterShip.stateMachine?.changeState(newState: FighterShipWanderState.sharedInstance)
}
}
// If the steering behavior wasn't set then we have to cancel moving into this state and go back to wandering
else if fighterShip.steeringBehavior?.getActiveBehavior() != SteeringBehaviors.Go {
print("Failed to go in the direction")
fighterShip.stateMachine?.changeState(newState: FighterShipWanderState.sharedInstance)
}
}
}
// Function for exiting a state
func exit(object: BaseObject) {
if let _ = object as? FighterShip {
}
}
// Function for updating a state
func execute(object: BaseObject, dTime: TimeInterval) {
if let fighterShip = object as? FighterShip {
fighterShip.updateVelocity(timeElapsed: dTime)
fighterShip.updatePosition(timeElapsed: dTime)
fighterShip.updateNode()
// Check to see if we fully turned and then go back to wandering
if let neededHeading = fighterShip.steeringBehavior?.targetPosition {
if fighterShip.heading.dot(vector: neededHeading) < 0.1 {
fighterShip.stateMachine?.changeState(newState: FighterShipWanderState.sharedInstance)
}
}
}
}
}
| mit | 0c50fa6a760126fea7386503ac3396c9 | 39.15625 | 121 | 0.626848 | 4.830827 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Collections/TextSearch/TextSearchResultCell.swift | 1 | 7198 | //
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import UIKit
import WireSyncEngine
final class TextSearchResultCell: UITableViewCell {
fileprivate let messageTextLabel = SearchResultLabel()
fileprivate let footerView = TextSearchResultFooter()
fileprivate let userImageViewContainer = UIView()
fileprivate let userImageView = UserImageView()
fileprivate let separatorView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.from(scheme: .separator)
return view
}()
fileprivate var observerToken: Any?
let resultCountView: RoundedTextBadge = {
let roundedTextBadge = RoundedTextBadge()
roundedTextBadge.backgroundColor = .lightGraphite
return roundedTextBadge
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
userImageView.userSession = ZMUserSession.shared()
userImageView.initialsFont = .systemFont(ofSize: 11, weight: .light)
accessibilityIdentifier = "search result cell"
contentView.addSubview(footerView)
selectionStyle = .none
messageTextLabel.accessibilityIdentifier = "text search result"
messageTextLabel.numberOfLines = 1
messageTextLabel.setContentCompressionResistancePriority(UILayoutPriority.required, for: .vertical)
messageTextLabel.setContentHuggingPriority(UILayoutPriority.required, for: .vertical)
contentView.addSubview(messageTextLabel)
userImageViewContainer.addSubview(userImageView)
contentView.addSubview(userImageViewContainer)
contentView.addSubview(separatorView)
resultCountView.textLabel.accessibilityIdentifier = "count of matches"
contentView.addSubview(resultCountView)
createConstraints()
textLabel?.textColor = .from(scheme: .background)
textLabel?.font = .smallSemiboldFont
}
fileprivate func createConstraints() {
[userImageView, userImageViewContainer, footerView, messageTextLabel, resultCountView, separatorView].prepareForLayout()
NSLayoutConstraint.activate([
userImageView.heightAnchor.constraint(equalToConstant: 24),
userImageView.widthAnchor.constraint(equalTo: userImageView.heightAnchor),
userImageView.centerXAnchor.constraint(equalTo: userImageViewContainer.centerXAnchor),
userImageView.centerYAnchor.constraint(equalTo: userImageViewContainer.centerYAnchor),
userImageViewContainer.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
userImageViewContainer.topAnchor.constraint(equalTo: contentView.topAnchor),
userImageViewContainer.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
userImageViewContainer.widthAnchor.constraint(equalToConstant: 48),
messageTextLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10),
messageTextLabel.leadingAnchor.constraint(equalTo: userImageViewContainer.trailingAnchor),
messageTextLabel.trailingAnchor.constraint(equalTo: resultCountView.leadingAnchor, constant: -16),
messageTextLabel.bottomAnchor.constraint(equalTo: footerView.topAnchor, constant: -4),
footerView.leadingAnchor.constraint(equalTo: userImageViewContainer.trailingAnchor),
footerView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
footerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10),
resultCountView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
resultCountView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
resultCountView.heightAnchor.constraint(equalToConstant: 20),
resultCountView.widthAnchor.constraint(greaterThanOrEqualToConstant: 24),
separatorView.leadingAnchor.constraint(equalTo: userImageViewContainer.trailingAnchor),
separatorView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
separatorView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
separatorView.heightAnchor.constraint(equalToConstant: .hairline)
])
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
message = .none
queries = []
}
private func updateTextView() {
guard let message = message else {
return
}
if message.isObfuscated {
let obfuscatedText = messageTextLabel.text?.obfuscated() ?? ""
messageTextLabel.configure(with: obfuscatedText, queries: [])
messageTextLabel.isObfuscated = true
return
}
guard let text = message.textMessageData?.messageText else {
return
}
messageTextLabel.configure(with: text, queries: queries)
let totalMatches = messageTextLabel.estimatedMatchesCount
resultCountView.isHidden = totalMatches <= 1
resultCountView.textLabel.text = "\(totalMatches)"
resultCountView.updateCollapseConstraints(isCollapsed: false)
}
func configure(with newMessage: ZMConversationMessage, queries newQueries: [String]) {
message = newMessage
queries = newQueries
userImageView.user = newMessage.senderUser
footerView.message = newMessage
if let userSession = ZMUserSession.shared() {
observerToken = MessageChangeInfo.add(observer: self,
for: newMessage,
userSession: userSession)
}
updateTextView()
}
var message: ZMConversationMessage? = .none
var queries: [String] = []
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
let backgroundColor = UIColor.from(scheme: .contentBackground)
let foregroundColor = UIColor.from(scheme: .textForeground)
contentView.backgroundColor = highlighted ? backgroundColor.mix(foregroundColor, amount: 0.1) : backgroundColor
}
}
extension TextSearchResultCell: ZMMessageObserver {
func messageDidChange(_ changeInfo: MessageChangeInfo) {
updateTextView()
}
}
| gpl-3.0 | 13e5c20c9852e62e178718ebd67ec390 | 40.131429 | 128 | 0.713393 | 5.721781 | false | false | false | false |
danielsaidi/KeyboardKit | Sources/KeyboardKit/UIKit/Buttons/UIKeyboardButton+Gestures.swift | 1 | 3010 | //
// UIKeyboardButton+Gestures.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2021-01-28.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import UIKit
public extension UIKeyboardButton {
/**
This function adds keyboard gestures to the button in a
certain input view controller.
*/
func addKeyboardGestures(in vc: KeyboardInputViewController) {
gestureRecognizers?.forEach { removeGestureRecognizer($0) }
if action == .nextKeyboard { return setupAsNextKeyboardButton(in: vc) }
vc.addDoubleTapGesture(to: self)
vc.addTapGesture(to: self)
vc.addLongPressGesture(to: self)
vc.addRepeatingGesture(to: self)
}
}
private extension KeyboardInputViewController {
func addDoubleTapGesture(to button: UIKeyboardButton) {
let gesture = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap))
gesture.numberOfTapsRequired = 2
gesture.delegate = self
button.addGestureRecognizer(gesture)
}
func addLongPressGesture(to button: UIKeyboardButton) {
let gesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
button.addGestureRecognizer(gesture)
}
func addRepeatingGesture(to button: UIKeyboardButton) {
weak var button = button
let gesture = UIRepeatingGestureRecognizer { [weak self] in
self?.handle(.repeatPress, on: button)
}
button?.addGestureRecognizer(gesture)
}
func addTapGesture(to button: UIKeyboardButton) {
let gesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
button.addGestureRecognizer(gesture)
}
func handle(_ gesture: KeyboardGesture, on button: UIView?) {
guard let button = button as? UIKeyboardButton else { return }
keyboardActionHandler.handle(gesture, on: button.action, sender: button)
}
}
@objc private extension KeyboardInputViewController {
func handleDoubleTap(_ gesture: UIGestureRecognizer) {
handle(.doubleTap, on: gesture.view)
}
func handleLongPress(_ gesture: UIGestureRecognizer) {
guard gesture.state == .began else { return }
handle(.longPress, on: gesture.view)
}
func handleRepeat(_ gesture: UIGestureRecognizer) {
handle(.repeatPress, on: gesture.view)
}
func handleTap(_ gesture: UIGestureRecognizer) {
handle(.tap, on: gesture.view)
(gesture.view as? UIKeyboardButton)?.animateStandardTap()
}
}
// MARK: - UIGestureRecognizerDelegate
/**
This delegate is required, to be able to use the double-tap
gesture without cancelling out single taps.
*/
extension KeyboardInputViewController: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
true
}
}
| mit | 25e12b12fb319fa7c96adf1a45f2a8c2 | 31.354839 | 164 | 0.69126 | 5.040201 | false | false | false | false |
twostraws/HackingWithSwift | Classic/project23/Project17/GameViewController.swift | 1 | 1213 | //
// GameViewController.swift
// Project17
//
// Created by TwoStraws on 18/08/2016.
// Copyright © 2016 Paul Hudson. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| unlicense | d4c64046a740da9ab9e4234a4e3d72c9 | 23.734694 | 77 | 0.565182 | 5.509091 | false | false | false | false |
DylanSecreast/uoregon-cis-portfolio | uoregon-cis-399/assignment1/Assignment1/Source/TriathlonEvent.swift | 1 | 3179 | //
// TriathlonEvent.swift
// Assignment1
//
// Dylan Secreast
// CIS 399 - 1/18/17
//
class TriathlonEvent {
var triathlon: Triathlon // #1
private(set) var eventPerformed: Bool = false // #3
var participantDict = [String:Int]() // #4.1
var currentlyRegistered: [Participant] = [] // #5.1
var randomValue: Double // #7.1
func register(_ participant: Participant) -> () { // #4
guard !eventPerformed else {
fatalError()
}
participantDict[participant.name] = 0
currentlyRegistered.append(participant) // #5.2
}
var registeredParticipants: [Participant] { // #5
get {
return currentlyRegistered
}
}
func raceTime(for participant: Participant) -> Int? { // #6
guard let time = participantDict[participant.name] else {
return nil
}
return time
}
func simulate(_ sport: Sport, for participant: Participant, randomValue: Double) -> () { // #7
guard let time = participantDict[participant.name] else {
return
}
print(participant.name + " is about to begin " + sport.description)
if sport == participant.favoriteSport || randomValue >= 0.05 {
let simTime = participant.completionTime(for: sport, in: triathlon)
participantDict[participant.name] = time + simTime
print(participant.name, "finished the", sport.description, "event in", simTime, "minutes; their total race time is now", participantDict[participant.name]!)
}
if sport != participant.favoriteSport && randomValue < 0.05 {
participantDict[participant.name] = nil
print(participant.name, "could not finish the", sport.description, "event and will not finish the race")
}
}
func simulate() -> () { // #8
guard !eventPerformed else {
fatalError()
}
for sport in Triathlon.Sports {
for participant in currentlyRegistered {
simulate(sport, for: participant, randomValue: randomValue)
}
print("KEKKEKEKEKEKEK")
}
eventPerformed = true
}
var winner: Participant? { // #9
get {
guard eventPerformed else {
fatalError()
}
var currentWinner: Participant?
var currentTime: Int = 0
for (name, time) in participantDict {
if time < currentTime {
currentTime = time
for participant in currentlyRegistered {
if participant.name == name {
currentWinner = participant
}
}
}
}
return currentWinner
}
}
func getWinner() -> Participant? {
return winner
}
init(triathlon: Triathlon) { // #2
self.triathlon = triathlon
randomValue = Double.random() // #7.1
}
}
| gpl-3.0 | 14bb40e6d4e780b3f3e590855fddf393 | 32.114583 | 168 | 0.525952 | 4.744776 | false | false | false | false |
imcaffrey/Spring | Spring/Spring.swift | 1 | 16901 | // The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
@objc public protocol Springable {
var autostart: Bool { get set }
var autohide: Bool { get set }
var animation: String { get set }
var force: CGFloat { get set }
var delay: CGFloat { get set }
var duration: CGFloat { get set }
var damping: CGFloat { get set }
var velocity: CGFloat { get set }
var repeatCount: Float { get set }
var x: CGFloat { get set }
var y: CGFloat { get set }
var scaleX: CGFloat { get set }
var scaleY: CGFloat { get set }
var rotate: CGFloat { get set }
var opacity: CGFloat { get set }
var animateFrom: Bool { get set }
var curve: String { get set }
// UIView
var layer : CALayer { get }
var transform : CGAffineTransform { get set }
var alpha : CGFloat { get set }
}
public class Spring : NSObject {
private var view : Springable
init(_ view: Springable) {
self.view = view
}
private var autostart: Bool { set { self.view.autostart = newValue } get { return self.view.autostart }}
private var autohide: Bool { set { self.view.autohide = newValue } get { return self.view.autohide }}
private var animation: String { set { self.view.animation = newValue } get { return self.view.animation }}
private var force: CGFloat { set { self.view.force = newValue } get { return self.view.force }}
private var delay: CGFloat { set { self.view.delay = newValue } get { return self.view.delay }}
private var duration: CGFloat { set { self.view.duration = newValue } get { return self.view.duration }}
private var damping: CGFloat { set { self.view.damping = newValue } get { return self.view.damping }}
private var velocity: CGFloat { set { self.view.velocity = newValue } get { return self.view.velocity }}
private var repeatCount: Float { set { self.view.repeatCount = newValue } get { return self.view.repeatCount }}
private var x: CGFloat { set { self.view.x = newValue } get { return self.view.x }}
private var y: CGFloat { set { self.view.y = newValue } get { return self.view.y }}
private var scaleX: CGFloat { set { self.view.scaleX = newValue } get { return self.view.scaleX }}
private var scaleY: CGFloat { set { self.view.scaleY = newValue } get { return self.view.scaleY }}
private var rotate: CGFloat { set { self.view.rotate = newValue } get { return self.view.rotate }}
private var opacity: CGFloat { set { self.view.opacity = newValue } get { return self.view.opacity }}
private var animateFrom: Bool { set { self.view.animateFrom = newValue } get { return self.view.animateFrom }}
private var curve: String { set { self.view.curve = newValue } get { return self.view.curve }}
// UIView
private var layer : CALayer { return view.layer }
private var transform : CGAffineTransform { get { return view.transform } set { view.transform = newValue }}
private var alpha: CGFloat { get { return view.alpha } set { view.alpha = newValue } }
func animatePreset() {
if animation == "" {
return
}
switch animation {
case "slideLeft":
x = 300*force
case "slideRight":
x = -300*force
case "slideDown":
y = -300*force
case "slideUp":
y = 300*force
case "squeezeLeft":
x = 300
scaleX = 3*force
case "squeezeRight":
x = -300
scaleX = 3*force
case "squeezeDown":
y = -300
scaleY = 3*force
case "squeezeUp":
y = 300
scaleY = 3*force
case "fadeIn":
opacity = 0
case "fadeOut":
animateFrom = false
opacity = 0
case "fadeOutIn":
let animation = CABasicAnimation()
animation.keyPath = "opacity"
animation.fromValue = 1
animation.toValue = 0
animation.timingFunction = getTimingFunction(curve)
animation.duration = CFTimeInterval(duration)
animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
animation.autoreverses = true
layer.addAnimation(animation, forKey: "fade")
case "fadeInLeft":
opacity = 0
x = 300*force
case "fadeInRight":
x = -300*force
opacity = 0
case "fadeInDown":
y = -300*force
opacity = 0
case "fadeInUp":
y = 300*force
opacity = 0
case "zoomIn":
opacity = 0
scaleX = 2*force
scaleY = 2*force
case "zoomOut":
animateFrom = false
opacity = 0
scaleX = 2*force
scaleY = 2*force
case "fall":
animateFrom = false
rotate = 15 * CGFloat(M_PI/180)
y = 600*force
case "shake":
let animation = CAKeyframeAnimation()
animation.keyPath = "position.x"
animation.values = [0, 30*force, -30*force, 30*force, 0]
animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
animation.timingFunction = getTimingFunction(curve)
animation.duration = CFTimeInterval(duration)
animation.additive = true
animation.repeatCount = repeatCount
animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.addAnimation(animation, forKey: "shake")
case "pop":
let animation = CAKeyframeAnimation()
animation.keyPath = "transform.scale"
animation.values = [0, 0.2*force, -0.2*force, 0.2*force, 0]
animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
animation.timingFunction = getTimingFunction(curve)
animation.duration = CFTimeInterval(duration)
animation.additive = true
animation.repeatCount = repeatCount
animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.addAnimation(animation, forKey: "pop")
case "flipX":
rotate = 0
scaleX = 1
scaleY = 1
var perspective = CATransform3DIdentity
perspective.m34 = -1.0 / layer.frame.size.width/2
let animation = CABasicAnimation()
animation.keyPath = "transform"
animation.fromValue = NSValue(CATransform3D:
CATransform3DMakeRotation(0, 0, 0, 0))
animation.toValue = NSValue(CATransform3D:
CATransform3DConcat(perspective, CATransform3DMakeRotation(CGFloat(M_PI), 0, 1, 0)))
animation.duration = CFTimeInterval(duration)
animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
animation.timingFunction = getTimingFunction(curve)
layer.addAnimation(animation, forKey: "3d")
case "flipY":
var perspective = CATransform3DIdentity
perspective.m34 = -1.0 / layer.frame.size.width/2
let animation = CABasicAnimation()
animation.keyPath = "transform"
animation.fromValue = NSValue(CATransform3D:
CATransform3DMakeRotation(0, 0, 0, 0))
animation.toValue = NSValue(CATransform3D:
CATransform3DConcat(perspective,CATransform3DMakeRotation(CGFloat(M_PI), 1, 0, 0)))
animation.duration = CFTimeInterval(duration)
animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
animation.timingFunction = getTimingFunction(curve)
layer.addAnimation(animation, forKey: "3d")
case "morph":
let morphX = CAKeyframeAnimation()
morphX.keyPath = "transform.scale.x"
morphX.values = [1, 1.3*force, 0.7, 1.3*force, 1]
morphX.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
morphX.timingFunction = getTimingFunction(curve)
morphX.duration = CFTimeInterval(duration)
morphX.repeatCount = repeatCount
morphX.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.addAnimation(morphX, forKey: "morphX")
let morphY = CAKeyframeAnimation()
morphY.keyPath = "transform.scale.y"
morphY.values = [1, 0.7, 1.3*force, 0.7, 1]
morphY.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
morphY.timingFunction = getTimingFunction(curve)
morphY.duration = CFTimeInterval(duration)
morphY.repeatCount = repeatCount
morphY.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.addAnimation(morphY, forKey: "morphY")
case "squeeze":
let morphX = CAKeyframeAnimation()
morphX.keyPath = "transform.scale.x"
morphX.values = [1, 1.5*force, 0.5, 1.5*force, 1]
morphX.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
morphX.timingFunction = getTimingFunction(curve)
morphX.duration = CFTimeInterval(duration)
morphX.repeatCount = repeatCount
morphX.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.addAnimation(morphX, forKey: "morphX")
let morphY = CAKeyframeAnimation()
morphY.keyPath = "transform.scale.y"
morphY.values = [1, 0.5, 1, 0.5, 1]
morphY.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
morphY.timingFunction = getTimingFunction(curve)
morphY.duration = CFTimeInterval(duration)
morphY.repeatCount = repeatCount
morphY.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.addAnimation(morphY, forKey: "morphY")
case "flash":
let animation = CABasicAnimation()
animation.keyPath = "opacity"
animation.fromValue = 1
animation.toValue = 0
animation.duration = CFTimeInterval(duration)
animation.repeatCount = repeatCount * 2.0
animation.autoreverses = true
animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.addAnimation(animation, forKey: "flash")
case "wobble":
let animation = CAKeyframeAnimation()
animation.keyPath = "transform.rotation"
animation.values = [0, 0.3*force, -0.3*force, 0.3*force, 0]
animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
animation.duration = CFTimeInterval(duration)
animation.additive = true
animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.addAnimation(animation, forKey: "wobble")
let x = CAKeyframeAnimation()
x.keyPath = "position.x"
x.values = [0, 30*force, -30*force, 30*force, 0]
x.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
x.timingFunction = getTimingFunction(curve)
x.duration = CFTimeInterval(duration)
x.additive = true
x.repeatCount = repeatCount
x.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.addAnimation(x, forKey: "x")
case "swing":
let animation = CAKeyframeAnimation()
animation.keyPath = "transform.rotation"
animation.values = [0, 0.3*force, -0.3*force, 0.3*force, 0]
animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
animation.duration = CFTimeInterval(duration)
animation.additive = true
animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.addAnimation(animation, forKey: "swing")
default:
x = 300
}
}
func getTimingFunction(curve: String) -> CAMediaTimingFunction {
switch curve {
case "easeIn":
return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
case "easeOut":
return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
case "easeInOut":
return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
case "linear":
return CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
case "spring":
return CAMediaTimingFunction(controlPoints: 0.5, 1.1+Float(force/3), 1, 1)
default:
return CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
}
}
func getAnimationOptions(curve: String) -> UIViewAnimationOptions {
switch curve {
case "easeIn":
return UIViewAnimationOptions.CurveEaseIn
case "easeOut":
return UIViewAnimationOptions.CurveEaseOut
case "easeInOut":
return UIViewAnimationOptions.CurveEaseInOut
case "linear":
return UIViewAnimationOptions.CurveLinear
case "spring":
return UIViewAnimationOptions.CurveLinear
default:
return UIViewAnimationOptions.CurveLinear
}
}
public func animate() {
animateFrom = true
animatePreset()
setView {}
}
public func animateNext(completion: () -> ()) {
animateFrom = true
animatePreset()
setView {
completion()
}
}
public func animateTo() {
animateFrom = false
animatePreset()
setView {}
}
public func animateToNext(completion: () -> ()) {
animateFrom = false
animatePreset()
setView {
completion()
}
}
public func customAwakeFromNib() {
if autohide {
alpha = 0
}
}
public func customDidMoveToWindow() {
if autostart {
alpha = 0
animateFrom = true
animatePreset()
setView {}
}
}
func setView(completion: () -> ()) {
if animateFrom {
let translate = CGAffineTransformMakeTranslation(self.x, self.y)
let scale = CGAffineTransformMakeScale(self.scaleX, self.scaleY)
let rotate = CGAffineTransformMakeRotation(self.rotate)
let translateAndScale = CGAffineTransformConcat(translate, scale)
self.transform = CGAffineTransformConcat(rotate, translateAndScale)
self.alpha = self.opacity
}
UIView.animateWithDuration( NSTimeInterval(duration),
delay: NSTimeInterval(delay),
usingSpringWithDamping: damping,
initialSpringVelocity: velocity,
options: getAnimationOptions(curve),
animations: {
if self.animateFrom {
self.transform = CGAffineTransformIdentity
self.alpha = 1
}
else {
let translate = CGAffineTransformMakeTranslation(self.x, self.y)
let scale = CGAffineTransformMakeScale(self.scaleX, self.scaleY)
let rotate = CGAffineTransformMakeRotation(self.rotate)
let translateAndScale = CGAffineTransformConcat(translate, scale)
self.transform = CGAffineTransformConcat(rotate, translateAndScale)
self.alpha = self.opacity
}
}, { finished in
completion()
self.resetAll()
})
}
func reset() {
x = 0
y = 0
opacity = 1
}
func resetAll() {
x = 0
y = 0
animation = ""
opacity = 1
scaleX = 1
scaleY = 1
rotate = 0
damping = 0.7
velocity = 0.7
repeatCount = 1
delay = 0
duration = 0.7
}
} | mit | d52490a9ce618fee879489e7d23050b1 | 39.052133 | 115 | 0.594817 | 4.834382 | false | false | false | false |
spacedrabbit/Swift-CatGram | The CatTasticals/SRCatTableViewController.swift | 1 | 3494 | //
// SRCatTableViewController.swift
// The CatTasticals
//
// Created by Louis Tur on 5/11/15.
// Copyright (c) 2015 Louis Tur. All rights reserved.
//
import UIKit
class SRCatTableViewController: PFQueryTableViewController {
let cellIdentifier:String = "CatCell"
override init(style: UITableViewStyle, className: String!) {
super.init(style: style, className: className)
self.pullToRefreshEnabled = true
self.paginationEnabled = false
self.objectsPerPage = 25
self.parseClassName = className
self.tableView.rowHeight = 350
self.tableView.allowsSelection = false
}
required init!(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
override func viewDidLoad() {
tableView.registerNib(UINib(nibName: "CatViewerTableViewCell", bundle: nil), forCellReuseIdentifier:cellIdentifier)
super.viewDidLoad()
}
override func queryForTable() -> PFQuery {
var query:PFQuery = PFQuery(className: self.parseClassName!)
if (objects?.count == 0){
query.cachePolicy = PFCachePolicy.CacheThenNetwork
}
query.orderByAscending(SRParseConsts.CatTasticalConsts.nameKey)
return query
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
var cell:CatViewerTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CatViewerTableViewCell
if ( cell == nil ){
cell = NSBundle.mainBundle().loadNibNamed("CatViewerTableViewCell", owner: self, options: nil)[0] as? CatViewerTableViewCell
}
cell?.parseObject = object
if let pfObject = object {
cell?.catNameLabel?.text = pfObject[SRParseConsts.CatTasticalConsts.nameKey] as? String
var votes:Int? = pfObject["votes"] as? Int
if votes == nil{
votes = 0
}
cell?.catVotesLabel?.text = "\(votes!) votes"
var credit:String? = pfObject["cc_by"] as? String
if credit != nil {
cell?.catCreditLabel?.text = "\(credit!) / CC 2.0"
}
cell?.catImageView?.image = nil
if var urlString:String? = pfObject["url"] as? String {
var url:NSURL? = NSURL(string: urlString!)
if var url:NSURL? = NSURL(string: urlString!){
var error:NSError?
var request:NSURLRequest = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 5.0)
NSOperationQueue.mainQueue().cancelAllOperations()
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {
(response:NSURLResponse!, imageData:NSData!, error:NSError!) -> Void in
cell?.catImageView?.image = UIImage(data: imageData)
})
}
}
}
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | dc52abbf0b6d13aa8ce95e625d30ce4e | 34.292929 | 154 | 0.587293 | 5.367127 | false | false | false | false |
imfree-jdcastro/Evrythng-iOS-SDK | Evrythng-iOS/Credentials.swift | 1 | 1218 | //
// Credentials.swift
// EvrythngiOS
//
// Created by JD Castro on 26/05/2017.
// Copyright © 2017 ImFree. All rights reserved.
//
import UIKit
import Moya_SwiftyJSONMapper
import SwiftyJSON
public final class Credentials: ALSwiftyJSONAble {
public var jsonData: JSON?
public var evrythngUser: String?
public var evrythngApiKey: String?
public var activationCode: String?
public var email: String?
public var password: String?
public var status: CredentialStatus?
public init?(jsonData: JSON) {
self.jsonData = jsonData
self.evrythngUser = jsonData["evrythngUser"].string
self.evrythngApiKey = jsonData["evrythngApiKey"].string
self.activationCode = jsonData["activationCode"].string
self.email = jsonData["email"].string
self.password = jsonData["password"].string
self.status = CredentialStatus(rawValue: jsonData["status"].stringValue)
}
public init(email: String, password: String) {
self.email = email
self.password = password
}
}
public enum CredentialStatus: String{
case Active = "active"
case Inactive = "inactive"
case Anonymous = "anonymous"
}
| apache-2.0 | f50601cc7aa0a7eab4ed6837088f1d0d | 26.044444 | 80 | 0.675431 | 4.196552 | false | false | false | false |
felixjendrusch/Matryoshka | MatryoshkaPlayground/MatryoshkaPlayground/Models/User.swift | 1 | 839 | // Copyright (c) 2015 Felix Jendrusch. All rights reserved.
import Runes
import Argo
public struct User: Equatable {
public var id: Int
public var username: String
public init(id: Int, username: String) {
self.id = id
self.username = username
}
}
public func == (lhs: User, rhs: User) -> Bool {
return lhs.id == rhs.id
&& lhs.username == rhs.username
}
extension User: Printable {
public var description: String {
return "User(id: \(id), username: \(username))"
}
}
extension User: Decodable {
private static func create(id: Int)(username: String) -> User {
return User(id: id, username: username)
}
public static func decode(json: JSON) -> Decoded<User> {
return create
<^> json <| "id"
<*> json <| "username"
}
}
| mit | 86e904d68cfadaca3676cc34c19a42d5 | 21.675676 | 67 | 0.593564 | 3.83105 | false | false | false | false |
gkye/TheMovieDatabaseSwiftWrapper | Sources/TMDBSwift/Models/TVSeries.swift | 1 | 4538 | import Foundation
/// <#Description#>
public struct TVSeries: Decodable {
/// <#Description#>
public var id: Int
/// <#Description#>
public var backdropPath: String?
// public var epidsodeRunTimes: [Int]?
// public var firstAirDate: Date?
/// <#Description#>
public var genres: [Genre]?
/// <#Description#>
public var homepage: String?
// public var isInProduction: Bool?
/// <#Description#>
public var originalLanguage: Language?
/// <#Description#>
public var overview: String?
/// <#Description#>
public var popularity: Double?
/// <#Description#>
public var posterPath: String?
/// <#Description#>
public var productionCompanies: [Company]?
/// <#Description#>
public var productionCountries: [Country]?
/// <#Description#>
public var spokenLanguages: [Language]?
/// <#Description#>
public var status: String? // change to enum?
/// <#Description#>
public var tagline: String?
/// <#Description#>
public var voteAverage: Double?
/// <#Description#>
public var voteCount: Int?
enum CodingKeys: String, CodingKey {
case id
case adult
case backdropPath = "backdrop_path"
case budget
case collection = "belongs_to_collection"
case genres
case homepage
case imdbID = "imdb_id"
case originalLanguage = "original_language"
case originalTitle = "original_title"
case overview
case popularity
case posterPath = "poster_path"
case productionCompanies = "production_companies"
case productionCountries = "production_countries"
case releaseDate = "release_date"
case revenue
case runtime
case spokenLanguages = "spoken_languages"
case status
case tagline
case title
case video
case voteAverage = "vote_average"
case voteCount = "vote_count"
}
enum SpokenLanguageCodingKeys: String, CodingKey {
case language = "iso_639_1"
}
enum ProductionCompanyCodingKeys: String, CodingKey {
case country = "iso_3166_1"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
backdropPath = try? container.decode(String.self, forKey: .backdropPath)
genres = try? container.decode([Genre].self, forKey: .genres)
homepage = try? container.decode(String.self, forKey: .homepage)
originalLanguage = try? container.decode(Language.self, forKey: .originalLanguage)
overview = try? container.decode(String.self, forKey: .overview)
popularity = try? container.decode(Double.self, forKey: .popularity)
posterPath = try? container.decode(String.self, forKey: .posterPath)
productionCompanies = try? container.decode([Company].self, forKey: .productionCompanies)
if var countryContent = try? container.nestedUnkeyedContainer(forKey: .productionCountries) {
var countries: [Country] = []
while !countryContent.isAtEnd {
if let country = try? countryContent.nestedContainer(keyedBy: ProductionCompanyCodingKeys.self) {
if let supportedCountry = try? country.decode(Country.self, forKey: .country) {
countries.append(supportedCountry)
}
} else {
break
}
}
productionCountries = countries
}
if var languageContent = try? container.nestedUnkeyedContainer(forKey: .spokenLanguages) {
var languages: [Language] = []
while !languageContent.isAtEnd {
if let language = try? languageContent.nestedContainer(keyedBy: SpokenLanguageCodingKeys.self) {
if let supportedLanguage = try? language.decode(Language.self, forKey: .language) {
languages.append(supportedLanguage)
}
} else {
break
}
}
spokenLanguages = languages
}
status = try? container.decode(String.self, forKey: .status)
tagline = try? container.decode(String.self, forKey: .tagline)
voteAverage = try? container.decode(Double.self, forKey: .voteAverage)
voteCount = try? container.decode(Int.self, forKey: .voteCount)
}
}
| mit | 099e111fa3d4f1c5380494ac791430f1 | 35.304 | 113 | 0.613266 | 4.746862 | false | false | false | false |
therealbnut/swift | test/Parse/ConditionalCompilation/basicParseErrors.swift | 1 | 1960 | // RUN: %target-typecheck-verify-swift -D FOO -D BAZ
#if FOO == BAZ // expected-error{{expected '&&' or '||' expression}}
var x = 0
#endif
#if ^FOO // expected-error {{expected unary '!' expression}}
var y = 0
#endif
#if foo(BAR) // expected-error {{unexpected platform condition (expected 'canImport', 'os', 'arch', or 'swift')}}
var z = 0
#endif
#if FOO || !FOO
func f() {}
#endif ; f() // expected-error {{extra tokens following conditional compilation directive}}
#if FOO || !FOO
func g() {}
#else g() // expected-error {{extra tokens following conditional compilation directive}}
#endif
#if FOO || !FOO
func h() {}
#else /* aaa */
#endif /* bbb */
#if foo.bar()
.baz() // expected-error {{unexpected platform condition (expected 'canImport', 'os', 'arch', or 'swift')}}
#endif
struct S {
#if FOO
#else
#else // expected-error {{further conditions after #else are unreachable}}
#endif
#if FOO
#elseif BAR
#elseif BAZ
#else
#endif
}
#if canImport(01101101_01101111_01101111_01100100) // expected-error {{unexpected platform condition argument: expected identifier}}
#elseif canImport(Foundation) ** FOO // expected-error{{expected '&&' or '||' expression}}
#else
#endif
#if FOO
#else
#else // expected-error {{further conditions after #else are unreachable}}
#endif
#if FOO
#elseif BAR
#elseif BAZ
#else
#endif
#if os(youOS) // expected-warning {{unknown operating system for build configuration 'os'}}
#endif
#if arch(leg) // expected-warning {{unknown architecture for build configuration 'arch'}}
#endif
#if _endian(mid) // expected-warning {{unknown endianness for build configuration '_endian'}}
#endif
LABEL: #if true // expected-error {{expected statement}}
func fn_i() {}
#endif
fn_i() // OK
try #if false // expected-error {{expected expression}}
#else
func fn_j() {}
#endif
fn_j() // OK
#if foo || bar || nonExistent() // expected-error {{expected only one argument to platform condition}}
#endif
| apache-2.0 | 62af98f380d8551469e8c9dc023b6a26 | 22.058824 | 132 | 0.67551 | 3.438596 | false | false | false | false |
zhixingxi/JJA_Swift | JJA_Swift/Pods/TimedSilver/Sources/UIKit/UIImage+TSOrientation.swift | 1 | 3091 | //
// UIImage+Orientation.swift
// TimedSilver
// Source: https://github.com/hilen/TimedSilver
//
// Created by Hilen on 2/17/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
import CoreGraphics
import Accelerate
//https://github.com/cosnovae/fixUIImageOrientation/blob/master/fixImageOrientation.swift
public extension UIImage {
/**
Fix the image's orientation
- parameter src: the source image
- returns: new image
*/
class func ts_fixImageOrientation(_ src:UIImage) -> UIImage {
if src.imageOrientation == UIImageOrientation.up {
return src
}
var transform: CGAffineTransform = CGAffineTransform.identity
switch src.imageOrientation {
case UIImageOrientation.down, UIImageOrientation.downMirrored:
transform = transform.translatedBy(x: src.size.width, y: src.size.height)
transform = transform.rotated(by: CGFloat(M_PI))
break
case UIImageOrientation.left, UIImageOrientation.leftMirrored:
transform = transform.translatedBy(x: src.size.width, y: 0)
transform = transform.rotated(by: CGFloat(M_PI_2))
break
case UIImageOrientation.right, UIImageOrientation.rightMirrored:
transform = transform.translatedBy(x: 0, y: src.size.height)
transform = transform.rotated(by: CGFloat(-M_PI_2))
break
case UIImageOrientation.up, UIImageOrientation.upMirrored:
break
}
switch src.imageOrientation {
case UIImageOrientation.upMirrored, UIImageOrientation.downMirrored:
transform.translatedBy(x: src.size.width, y: 0)
transform.scaledBy(x: -1, y: 1)
break
case UIImageOrientation.leftMirrored, UIImageOrientation.rightMirrored:
transform.translatedBy(x: src.size.height, y: 0)
transform.scaledBy(x: -1, y: 1)
case UIImageOrientation.up, UIImageOrientation.down, UIImageOrientation.left, UIImageOrientation.right:
break
}
let ctx:CGContext = CGContext(data: nil, width: Int(src.size.width), height: Int(src.size.height), bitsPerComponent: src.cgImage!.bitsPerComponent, bytesPerRow: 0, space: src.cgImage!.colorSpace!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
ctx.concatenate(transform)
switch src.imageOrientation {
case UIImageOrientation.left, UIImageOrientation.leftMirrored, UIImageOrientation.right, UIImageOrientation.rightMirrored:
ctx.draw(src.cgImage!, in: CGRect(x: 0, y: 0, width: src.size.height, height: src.size.width))
break
default:
ctx.draw(src.cgImage!, in: CGRect(x: 0, y: 0, width: src.size.width, height: src.size.height))
break
}
let cgimage:CGImage = ctx.makeImage()!
let image:UIImage = UIImage(cgImage: cgimage)
return image
}
}
| mit | 5fab3e0bfaaad1f2acb201ae976989cd | 34.930233 | 262 | 0.646278 | 4.746544 | false | false | false | false |
trivago/Dobby | DobbyTests/MatcherSpec.swift | 2 | 11620 | import Quick
import Nimble
import Dobby
class MatcherSpec: QuickSpec {
override func spec() {
describe("Matching") {
context("a matching function") {
let matcher: Dobby.Matcher<Int> = matches { $0 == 0 }
it("succeeds if the matching function returns true") {
expect(matcher.matches(0)).to(beTrue())
}
it("fails if the matching function returns false") {
expect(matcher.matches(1)).to(beFalse())
}
}
context("anything") {
let matcher: Dobby.Matcher<Int> = any()
it("always succeeds") {
expect(matcher.matches(0)).to(beTrue())
expect(matcher.matches(1)).to(beTrue())
}
}
context("anything but whatever (not)") {
let matcher: Dobby.Matcher<Int> = not(0)
it("succeeds if the given matcher is not matched") {
expect(matcher.matches(1)).to(beTrue())
}
it("fails if the given matcher is matched") {
expect(matcher.matches(0)).to(beFalse())
}
}
context("nothing") {
let matcher: Dobby.Matcher<Int?> = none()
it("succeeds if the actual value equals nil") {
expect(matcher.matches(nil)).to(beTrue())
}
it("fails if the actual value does not equal nil") {
expect(matcher.matches(0)).to(beFalse())
}
}
context("something") {
let matcher: Dobby.Matcher<Int?> = some(0)
it("succeeds if the given matcher is matched") {
expect(matcher.matches(0)).to(beTrue())
}
it("fails if the given matcher is not matched") {
expect(matcher.matches(nil)).to(beFalse())
expect(matcher.matches(1)).to(beFalse())
}
}
context("a value") {
let matcher: Dobby.Matcher<Int> = equals(0)
it("succeeds if the actual value equals the expected value") {
expect(matcher.matches(0)).to(beTrue())
}
it("fails if the actual value does not equal the expected value") {
expect(matcher.matches(1)).to(beFalse())
}
}
context("a 2-tuple") {
let matcher: Dobby.Matcher<(Int, Int)> = equals((0, 1))
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches(0, 1)).to(beTrue())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches(1, 1)).to(beFalse())
expect(matcher.matches(0, 0)).to(beFalse())
}
}
context("a 3-tuple") {
let matcher: Dobby.Matcher<(Int, Int, Int)> = equals((0, 1, 2))
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches(0, 1, 2)).to(beTrue())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches(1, 1, 2)).to(beFalse())
expect(matcher.matches(0, 0, 2)).to(beFalse())
expect(matcher.matches(0, 1, 1)).to(beFalse())
}
}
context("a 4-tuple") {
let matcher: Dobby.Matcher<(Int, Int, Int, Int)> = equals((0, 1, 2, 3))
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches(0, 1, 2, 3)).to(beTrue())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches(1, 1, 2, 3)).to(beFalse())
expect(matcher.matches(0, 0, 2, 3)).to(beFalse())
expect(matcher.matches(0, 1, 1, 3)).to(beFalse())
expect(matcher.matches(0, 1, 2, 2)).to(beFalse())
}
}
context("a 5-tuple") {
let matcher: Dobby.Matcher<(Int, Int, Int, Int, Int)> = equals((0, 1, 2, 3, 4))
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches(0, 1, 2, 3, 4)).to(beTrue())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches(1, 1, 2, 3, 4)).to(beFalse())
expect(matcher.matches(0, 0, 2, 3, 4)).to(beFalse())
expect(matcher.matches(0, 1, 1, 3, 4)).to(beFalse())
expect(matcher.matches(0, 1, 2, 2, 4)).to(beFalse())
expect(matcher.matches(0, 1, 2, 3, 3)).to(beFalse())
}
}
context("an array") {
let matcher: Dobby.Matcher<[Int]> = equals([0, 1, 2])
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches([0, 1, 2])).to(beTrue())
}
it("fails if the amount of actual values differs from the amount of expected values") {
expect(matcher.matches([0, 1])).to(beFalse())
expect(matcher.matches([0, 1, 2, 3])).to(beFalse())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches([1, 1, 2])).to(beFalse())
expect(matcher.matches([0, 0, 2])).to(beFalse())
expect(matcher.matches([0, 1, 1])).to(beFalse())
}
}
context("a dictionary") {
let matcher: Dobby.Matcher<[Int: Int]> = equals([0: 0, 1: 1, 2: 2])
it("succeeds if all actual pairs equal the expected pairs") {
expect(matcher.matches([0: 0, 1: 1, 2: 2])).to(beTrue())
}
it("fails if the amount of actual pairs differs from the amount of expected pairs") {
expect(matcher.matches([0: 0, 1: 1])).to(beFalse())
expect(matcher.matches([0: 0, 1: 1, 2: 2, 3: 3])).to(beFalse())
}
it("fails if any actual pair does not equal the expected pair") {
expect(matcher.matches([0: 1, 1: 1, 2: 2])).to(beFalse())
expect(matcher.matches([0: 0, 1: 0, 2: 2])).to(beFalse())
expect(matcher.matches([0: 0, 1: 1, 2: 1])).to(beFalse())
}
}
context("a 2-tuple of matchers") {
let matcher: Dobby.Matcher<(Int, Int)> = matches((equals(0), equals(1)))
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches(0, 1)).to(beTrue())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches(1, 1)).to(beFalse())
expect(matcher.matches(0, 0)).to(beFalse())
}
}
context("a 3-tuple of matchers") {
let matcher: Dobby.Matcher<(Int, Int, Int)> = matches((equals(0), equals(1), equals(2)))
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches(0, 1, 2)).to(beTrue())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches(1, 1, 2)).to(beFalse())
expect(matcher.matches(0, 0, 2)).to(beFalse())
expect(matcher.matches(0, 1, 1)).to(beFalse())
}
}
context("a 4-tuple of matchers") {
let matcher: Dobby.Matcher<(Int, Int, Int, Int)> = matches((equals(0), equals(1), equals(2), equals(3)))
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches(0, 1, 2, 3)).to(beTrue())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches(1, 1, 2, 3)).to(beFalse())
expect(matcher.matches(0, 0, 2, 3)).to(beFalse())
expect(matcher.matches(0, 1, 1, 3)).to(beFalse())
expect(matcher.matches(0, 1, 2, 2)).to(beFalse())
}
}
context("a 5-tuple of matchers") {
let matcher: Dobby.Matcher<(Int, Int, Int, Int, Int)> = matches((equals(0), equals(1), equals(2), equals(3), equals(4)))
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches(0, 1, 2, 3, 4)).to(beTrue())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches(1, 1, 2, 3, 4)).to(beFalse())
expect(matcher.matches(0, 0, 2, 3, 4)).to(beFalse())
expect(matcher.matches(0, 1, 1, 3, 4)).to(beFalse())
expect(matcher.matches(0, 1, 2, 2, 4)).to(beFalse())
expect(matcher.matches(0, 1, 2, 3, 3)).to(beFalse())
}
}
context("an array of matchers") {
let matcher: Dobby.Matcher<[Int]> = matches([equals(0), equals(1), equals(2)])
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches([0, 1, 2])).to(beTrue())
}
it("fails if the amount of actual values differs from the amount of expected values") {
expect(matcher.matches([0, 1])).to(beFalse())
expect(matcher.matches([0, 1, 2, 3])).to(beFalse())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches([1, 1, 2])).to(beFalse())
expect(matcher.matches([0, 0, 2])).to(beFalse())
expect(matcher.matches([0, 1, 1])).to(beFalse())
}
}
context("a dictionary of matchers") {
let matcher: Dobby.Matcher<[Int: Int]> = matches([0: equals(0), 1: equals(1), 2: equals(2)])
it("succeeds if all actual pairs equal the expected pairs") {
expect(matcher.matches([0: 0, 1: 1, 2: 2])).to(beTrue())
}
it("fails if the amount of actual pairs differs from the amount of expected pairs") {
expect(matcher.matches([0: 0, 1: 1])).to(beFalse())
expect(matcher.matches([0: 0, 1: 1, 2: 2, 3: 3])).to(beFalse())
}
it("fails if any actual pair does not equal the expected pair") {
expect(matcher.matches([0: 1, 1: 1, 2: 2])).to(beFalse())
expect(matcher.matches([0: 0, 1: 0, 2: 2])).to(beFalse())
expect(matcher.matches([0: 0, 1: 1, 2: 1])).to(beFalse())
expect(matcher.matches([3: 0, 4: 1, 5: 2])).to(beFalse())
}
}
}
}
}
| apache-2.0 | 064f4558623c7e13eb6e067ae72104f3 | 41.564103 | 136 | 0.47315 | 4.34068 | false | false | false | false |
ahoppen/swift | test/SILGen/builtins.swift | 2 | 38485 | // RUN: %target-swift-emit-silgen -parse-stdlib %s -disable-access-control -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s
// RUN: %target-swift-emit-sil -Onone -parse-stdlib %s -disable-access-control -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck -check-prefix=CANONICAL %s
import Swift
protocol ClassProto : class { }
struct Pointer {
var value: Builtin.RawPointer
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins3foo{{[_0-9a-zA-Z]*}}F
func foo(_ x: Builtin.Int1, y: Builtin.Int1) -> Builtin.Int1 {
// CHECK: builtin "cmp_eq_Int1"
return Builtin.cmp_eq_Int1(x, y)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8load_pod{{[_0-9a-zA-Z]*}}F
func load_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64
// CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.load(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8load_obj{{[_0-9a-zA-Z]*}}F
func load_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject
// CHECK: [[VAL:%.*]] = load [copy] [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.load(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins12load_raw_pod{{[_0-9a-zA-Z]*}}F
func load_raw_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [align=1] $*Builtin.Int64
// CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.loadRaw(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins12load_raw_obj{{[_0-9a-zA-Z]*}}F
func load_raw_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [align=1] $*Builtin.NativeObject
// CHECK: [[VAL:%.*]] = load [copy] [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.loadRaw(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins18load_invariant_pod{{[_0-9a-zA-Z]*}}F
func load_invariant_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [invariant] $*Builtin.Int64
// CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.loadInvariant(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins18load_invariant_obj{{[_0-9a-zA-Z]*}}F
func load_invariant_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [invariant] $*Builtin.NativeObject
// CHECK: [[VAL:%.*]] = load [copy] [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.loadInvariant(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8load_gen{{[_0-9a-zA-Z]*}}F
func load_gen<T>(_ x: Builtin.RawPointer) -> T {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T
// CHECK: copy_addr [[ADDR]] to [initialization] {{%.*}}
return Builtin.load(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8move_pod{{[_0-9a-zA-Z]*}}F
func move_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64
// CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.take(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8move_obj{{[_0-9a-zA-Z]*}}F
func move_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject
// CHECK: [[VAL:%.*]] = load [take] [[ADDR]]
// CHECK-NOT: copy_value [[VAL]]
// CHECK: return [[VAL]]
return Builtin.take(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8move_gen{{[_0-9a-zA-Z]*}}F
func move_gen<T>(_ x: Builtin.RawPointer) -> T {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T
// CHECK: copy_addr [take] [[ADDR]] to [initialization] {{%.*}}
return Builtin.take(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins11destroy_pod{{[_0-9a-zA-Z]*}}F
func destroy_pod(_ x: Builtin.RawPointer) {
var x = x
// CHECK: [[XBOX:%[0-9]+]] = alloc_box
// CHECK-NOT: pointer_to_address
// CHECK-NOT: destroy_addr
// CHECK-NOT: destroy_value
// CHECK: destroy_value [[XBOX]] : ${{.*}}{
// CHECK-NOT: destroy_value
return Builtin.destroy(Builtin.Int64.self, x)
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins11destroy_obj{{[_0-9a-zA-Z]*}}F
func destroy_obj(_ x: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject
// CHECK: destroy_addr [[ADDR]]
return Builtin.destroy(Builtin.NativeObject.self, x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins11destroy_gen{{[_0-9a-zA-Z]*}}F
func destroy_gen<T>(_ x: Builtin.RawPointer, _: T) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T
// CHECK: destroy_addr [[ADDR]]
return Builtin.destroy(T.self, x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins10assign_pod{{[_0-9a-zA-Z]*}}F
func assign_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) {
var x = x
var y = y
// CHECK: alloc_box
// CHECK: alloc_box
// CHECK-NOT: alloc_box
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64
// CHECK-NOT: load [[ADDR]]
// CHECK: assign {{%.*}} to [[ADDR]]
// CHECK: destroy_value
// CHECK: destroy_value
// CHECK-NOT: destroy_value
Builtin.assign(x, y)
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins10assign_obj{{[_0-9a-zA-Z]*}}F
func assign_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject
// CHECK: assign {{%.*}} to [[ADDR]]
// CHECK-NOT: destroy_value
Builtin.assign(x, y)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins12assign_tuple{{[_0-9a-zA-Z]*}}F
func assign_tuple(_ x: (Builtin.Int64, Builtin.NativeObject),
y: Builtin.RawPointer) {
var x = x
var y = y
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*(Builtin.Int64, Builtin.NativeObject)
// CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]]
// CHECK: assign {{%.*}} to [[T0]]
// CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]]
// CHECK: assign {{%.*}} to [[T0]]
// CHECK: destroy_value
Builtin.assign(x, y)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins10assign_gen{{[_0-9a-zA-Z]*}}F
func assign_gen<T>(_ x: T, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T
// CHECK: copy_addr [take] {{%.*}} to [[ADDR]] :
Builtin.assign(x, y)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8init_pod{{[_0-9a-zA-Z]*}}F
func init_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64
// CHECK-NOT: load [[ADDR]]
// CHECK: store {{%.*}} to [trivial] [[ADDR]]
// CHECK-NOT: destroy_value [[ADDR]]
Builtin.initialize(x, y)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8init_obj{{[_0-9a-zA-Z]*}}F
func init_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject
// CHECK-NOT: load [[ADDR]]
// CHECK: store [[SRC:%.*]] to [init] [[ADDR]]
// CHECK-NOT: destroy_value [[SRC]]
Builtin.initialize(x, y)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8init_gen{{[_0-9a-zA-Z]*}}F
func init_gen<T>(_ x: T, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T
// CHECK: copy_addr [[OTHER_LOC:%.*]] to [initialization] [[ADDR]]
// CHECK-NOT: destroy_addr [[OTHER_LOC]]
Builtin.initialize(x, y)
}
class C {}
class D {}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins22class_to_native_object{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[ARG:%.*]] : @guaranteed $C):
// CHECK-NEXT: debug_value
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK-NEXT: [[OBJ:%.*]] = unchecked_ref_cast [[ARG_COPY]] : $C to $Builtin.NativeObject
// CHECK-NEXT: return [[OBJ]]
func class_to_native_object(_ c:C) -> Builtin.NativeObject {
return Builtin.castToNativeObject(c)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins32class_archetype_to_native_object{{[_0-9a-zA-Z]*}}F
func class_archetype_to_native_object<T : C>(_ t: T) -> Builtin.NativeObject {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[COPY]] : $T to $Builtin.NativeObject
// CHECK-NOT: destroy_value [[COPY]]
// CHECK-NOT: destroy_value [[OBJ]]
// CHECK: return [[OBJ]]
return Builtin.castToNativeObject(t)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins34class_existential_to_native_object{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[ARG:%.*]] : @guaranteed $ClassProto):
// CHECK-NEXT: debug_value
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK-NEXT: [[REF:%[0-9]+]] = open_existential_ref [[ARG_COPY]] : $ClassProto
// CHECK-NEXT: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.NativeObject
// CHECK-NEXT: return [[PTR]]
func class_existential_to_native_object(_ t:ClassProto) -> Builtin.NativeObject {
return Builtin.unsafeCastToNativeObject(t as ClassProto)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins24class_from_native_object{{[_0-9a-zA-Z]*}}F
func class_from_native_object(_ p: Builtin.NativeObject) -> C {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[CAST:%.*]] = unchecked_ref_cast [[COPY]] : $Builtin.NativeObject to $C
// CHECK-NOT: destroy_value [[COPY]]
// CHECK-NOT: destroy_value [[CAST]]
// CHECK: return [[CAST]]
return Builtin.castFromNativeObject(p)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins34class_archetype_from_native_object{{[_0-9a-zA-Z]*}}F
func class_archetype_from_native_object<T : C>(_ p: Builtin.NativeObject) -> T {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[CAST:%.*]] = unchecked_ref_cast [[COPY]] : $Builtin.NativeObject to $T
// CHECK-NOT: destroy_value [[COPY]]
// CHECK-NOT: destroy_value [[CAST]]
// CHECK: return [[CAST]]
return Builtin.castFromNativeObject(p)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins41objc_class_existential_from_native_object{{[_0-9a-zA-Z]*}}F
func objc_class_existential_from_native_object(_ p: Builtin.NativeObject) -> AnyObject {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[CAST:%.*]] = unchecked_ref_cast [[COPY]] : $Builtin.NativeObject to $AnyObject
// CHECK-NOT: destroy_value [[COPY]]
// CHECK-NOT: destroy_value [[CAST]]
// CHECK: return [[CAST]]
return Builtin.castFromNativeObject(p)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins20class_to_raw_pointer{{[_0-9a-zA-Z]*}}F
func class_to_raw_pointer(_ c: C) -> Builtin.RawPointer {
// CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer
// CHECK: return [[RAW]]
return Builtin.bridgeToRawPointer(c)
}
func class_archetype_to_raw_pointer<T : C>(_ t: T) -> Builtin.RawPointer {
return Builtin.bridgeToRawPointer(t)
}
protocol CP: class {}
func existential_to_raw_pointer(_ p: CP) -> Builtin.RawPointer {
return Builtin.bridgeToRawPointer(p)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins18obj_to_raw_pointer{{[_0-9a-zA-Z]*}}F
func obj_to_raw_pointer(_ c: Builtin.NativeObject) -> Builtin.RawPointer {
// CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer
// CHECK: return [[RAW]]
return Builtin.bridgeToRawPointer(c)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins22class_from_raw_pointer{{[_0-9a-zA-Z]*}}F
func class_from_raw_pointer(_ p: Builtin.RawPointer) -> C {
// CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $C
// CHECK: [[C_COPY:%.*]] = copy_value [[C]]
// CHECK: return [[C_COPY]]
return Builtin.bridgeFromRawPointer(p)
}
func class_archetype_from_raw_pointer<T : C>(_ p: Builtin.RawPointer) -> T {
return Builtin.bridgeFromRawPointer(p)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins20obj_from_raw_pointer{{[_0-9a-zA-Z]*}}F
func obj_from_raw_pointer(_ p: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.NativeObject
// CHECK: [[C_COPY:%.*]] = copy_value [[C]]
// CHECK: return [[C_COPY]]
return Builtin.bridgeFromRawPointer(p)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins28existential_from_raw_pointer{{[_0-9a-zA-Z]*}}F
func existential_from_raw_pointer(_ p: Builtin.RawPointer) -> AnyObject {
// CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $AnyObject
// CHECK: [[C_COPY:%.*]] = copy_value [[C]]
// CHECK: return [[C_COPY]]
return Builtin.bridgeFromRawPointer(p)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins9gep_raw64{{[_0-9a-zA-Z]*}}F
func gep_raw64(_ p: Builtin.RawPointer, i: Builtin.Int64) -> Builtin.RawPointer {
// CHECK: [[GEP:%.*]] = index_raw_pointer
// CHECK: return [[GEP]]
return Builtin.gepRaw_Int64(p, i)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins9gep_raw32{{[_0-9a-zA-Z]*}}F
func gep_raw32(_ p: Builtin.RawPointer, i: Builtin.Int32) -> Builtin.RawPointer {
// CHECK: [[GEP:%.*]] = index_raw_pointer
// CHECK: return [[GEP]]
return Builtin.gepRaw_Int32(p, i)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins3gep{{[_0-9a-zA-Z]*}}F
func gep<Elem>(_ p: Builtin.RawPointer, i: Builtin.Word, e: Elem.Type) -> Builtin.RawPointer {
// CHECK: [[P2A:%.*]] = pointer_to_address %0
// CHECK: [[GEP:%.*]] = index_addr [[P2A]] : $*Elem, %1 : $Builtin.Word
// CHECK: [[A2P:%.*]] = address_to_pointer [[GEP]]
// CHECK: return [[A2P]]
return Builtin.gep_Word(p, i, e)
}
public final class Header { }
// CHECK-LABEL: sil hidden [ossa] @$s8builtins20allocWithTailElems_1{{[_0-9a-zA-Z]*}}F
func allocWithTailElems_1<T>(n: Builtin.Word, ty: T.Type) -> Header {
// CHECK: [[M:%.*]] = metatype $@thick Header.Type
// CHECK: [[A:%.*]] = alloc_ref [tail_elems $T * %0 : $Builtin.Word] $Header
// CHECK: return [[A]]
return Builtin.allocWithTailElems_1(Header.self, n, ty)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins20allocWithTailElems_3{{[_0-9a-zA-Z]*}}F
func allocWithTailElems_3<T1, T2, T3>(n1: Builtin.Word, ty1: T1.Type, n2: Builtin.Word, ty2: T2.Type, n3: Builtin.Word, ty3: T3.Type) -> Header {
// CHECK: [[M:%.*]] = metatype $@thick Header.Type
// CHECK: [[A:%.*]] = alloc_ref [tail_elems $T1 * %0 : $Builtin.Word] [tail_elems $T2 * %2 : $Builtin.Word] [tail_elems $T3 * %4 : $Builtin.Word] $Header
// CHECK: return [[A]]
return Builtin.allocWithTailElems_3(Header.self, n1, ty1, n2, ty2, n3, ty3)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins16projectTailElems{{[_0-9a-zA-Z]*}}F
func projectTailElems<T>(h: Header, ty: T.Type) -> Builtin.RawPointer {
// CHECK: bb0([[ARG1:%.*]] : @guaranteed $Header
// CHECK: [[TA:%.*]] = ref_tail_addr [[ARG1]] : $Header
// CHECK: [[A2P:%.*]] = address_to_pointer [[TA]]
// CHECK: return [[A2P]]
return Builtin.projectTailElems(h, ty)
}
// CHECK: } // end sil function '$s8builtins16projectTailElems1h2tyBpAA6HeaderC_xmtlF'
// Make sure we borrow if this is owned.
//
// CHECK-LABEL: sil hidden [ossa] @$s8builtins21projectTailElemsOwned{{[_0-9a-zA-Z]*}}F
func projectTailElemsOwned<T>(h: __owned Header, ty: T.Type) -> Builtin.RawPointer {
// CHECK: bb0([[ARG1:%.*]] : @owned $Header
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [lexical] [[ARG1]]
// CHECK: [[TA:%.*]] = ref_tail_addr [[BORROWED_ARG1]] : $Header
// -- Once we have passed the address through a2p, we no longer provide any guarantees.
// -- We still need to make sure that the a2p itself is in the borrow site though.
// CHECK: [[A2P:%.*]] = address_to_pointer [[TA]]
// CHECK: end_borrow [[BORROWED_ARG1]]
// CHECK: destroy_value [[ARG1]]
// CHECK: return [[A2P]]
return Builtin.projectTailElems(h, ty)
}
// CHECK: } // end sil function '$s8builtins21projectTailElemsOwned{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden [ossa] @$s8builtins11getTailAddr{{[_0-9a-zA-Z]*}}F
func getTailAddr<T1, T2>(start: Builtin.RawPointer, i: Builtin.Word, ty1: T1.Type, ty2: T2.Type) -> Builtin.RawPointer {
// CHECK: [[P2A:%.*]] = pointer_to_address %0
// CHECK: [[TA:%.*]] = tail_addr [[P2A]] : $*T1, %1 : $Builtin.Word, $T2
// CHECK: [[A2P:%.*]] = address_to_pointer [[TA]]
// CHECK: return [[A2P]]
return Builtin.getTailAddr_Word(start, i, ty1, ty2)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins25beginUnpairedModifyAccess{{[_0-9a-zA-Z]*}}F
func beginUnpairedModifyAccess<T1>(address: Builtin.RawPointer, scratch: Builtin.RawPointer, ty1: T1.Type) {
// CHECK: [[P2A_ADDR:%.*]] = pointer_to_address %0
// CHECK: [[P2A_SCRATCH:%.*]] = pointer_to_address %1
// CHECK: begin_unpaired_access [modify] [dynamic] [builtin] [[P2A_ADDR]] : $*T1, [[P2A_SCRATCH]] : $*Builtin.UnsafeValueBuffer
// CHECK: [[RESULT:%.*]] = tuple ()
// CHECK: [[RETURN:%.*]] = tuple ()
// CHECK: return [[RETURN]] : $()
Builtin.beginUnpairedModifyAccess(address, scratch, ty1);
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins30performInstantaneousReadAccess{{[_0-9a-zA-Z]*}}F
func performInstantaneousReadAccess<T1>(address: Builtin.RawPointer, scratch: Builtin.RawPointer, ty1: T1.Type) {
// CHECK: [[P2A_ADDR:%.*]] = pointer_to_address %0
// CHECK: [[SCRATCH:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer
// CHECK: begin_unpaired_access [read] [dynamic] [no_nested_conflict] [builtin] [[P2A_ADDR]] : $*T1, [[SCRATCH]] : $*Builtin.UnsafeValueBuffer
// CHECK-NOT: end_{{.*}}access
// CHECK: [[RESULT:%.*]] = tuple ()
// CHECK: [[RETURN:%.*]] = tuple ()
// CHECK: return [[RETURN]] : $()
Builtin.performInstantaneousReadAccess(address, ty1);
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins15legacy_condfail{{[_0-9a-zA-Z]*}}F
func legacy_condfail(_ i: Builtin.Int1) {
Builtin.condfail(i)
// CHECK: cond_fail {{%.*}} : $Builtin.Int1, "unknown runtime failure"
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8condfail{{[_0-9a-zA-Z]*}}F
func condfail(_ i: Builtin.Int1) {
Builtin.condfail_message(i, StaticString("message").unsafeRawPointer)
// CHECK: builtin "condfail_message"({{%.*}} : $Builtin.Int1, {{%.*}} : $Builtin.RawPointer) : $()
}
struct S {}
@objc class O {}
@objc protocol OP1 {}
@objc protocol OP2 {}
protocol P {}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins10canBeClass{{[_0-9a-zA-Z]*}}F
func canBeClass<T>(_: T) {
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(O.self)
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(OP1.self)
// -- FIXME: 'OP1 & OP2' doesn't parse as a value
typealias ObjCCompo = OP1 & OP2
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(ObjCCompo.self)
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(S.self)
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(C.self)
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(P.self)
typealias MixedCompo = OP1 & P
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(MixedCompo.self)
// CHECK: builtin "canBeClass"<T>
Builtin.canBeClass(T.self)
}
// FIXME: "T.Type.self" does not parse as an expression
// CHECK-LABEL: sil hidden [ossa] @$s8builtins18canBeClassMetatype{{[_0-9a-zA-Z]*}}F
func canBeClassMetatype<T>(_: T) {
// CHECK: integer_literal $Builtin.Int8, 0
typealias OT = O.Type
Builtin.canBeClass(OT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias OP1T = OP1.Type
Builtin.canBeClass(OP1T.self)
// -- FIXME: 'OP1 & OP2' doesn't parse as a value
typealias ObjCCompoT = (OP1 & OP2).Type
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(ObjCCompoT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias ST = S.Type
Builtin.canBeClass(ST.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias CT = C.Type
Builtin.canBeClass(CT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias PT = P.Type
Builtin.canBeClass(PT.self)
typealias MixedCompoT = (OP1 & P).Type
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(MixedCompoT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias TT = T.Type
Builtin.canBeClass(TT.self)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins11fixLifetimeyyAA1CCF : $@convention(thin) (@guaranteed C) -> () {
func fixLifetime(_ c: C) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $C):
// CHECK: fix_lifetime [[ARG]] : $C
Builtin.fixLifetime(c)
}
// CHECK: } // end sil function '$s8builtins11fixLifetimeyyAA1CCF'
// CHECK-LABEL: sil hidden [ossa] @$s8builtins20assert_configuration{{[_0-9a-zA-Z]*}}F
func assert_configuration() -> Builtin.Int32 {
return Builtin.assert_configuration()
// CHECK: [[APPLY:%.*]] = builtin "assert_configuration"() : $Builtin.Int32
// CHECK: return [[APPLY]] : $Builtin.Int32
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins17assumeNonNegativeyBwBwF
func assumeNonNegative(_ x: Builtin.Word) -> Builtin.Word {
return Builtin.assumeNonNegative_Word(x)
// CHECK: [[APPLY:%.*]] = builtin "assumeNonNegative_Word"(%0 : $Builtin.Word) : $Builtin.Word
// CHECK: return [[APPLY]] : $Builtin.Word
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins11autoreleaseyyAA1OCF : $@convention(thin) (@guaranteed O) -> () {
// ==> SEMANTIC ARC TODO: This will be unbalanced... should we allow it?
// CHECK: bb0([[ARG:%.*]] : @guaranteed $O):
// CHECK: unmanaged_autorelease_value [[ARG]]
// CHECK: } // end sil function '$s8builtins11autoreleaseyyAA1OCF'
func autorelease(_ o: O) {
Builtin.autorelease(o)
}
// The 'unreachable' builtin is emitted verbatim by SILGen and eliminated during
// diagnostics.
// CHECK-LABEL: sil hidden [ossa] @$s8builtins11unreachable{{[_0-9a-zA-Z]*}}F
// CHECK: builtin "unreachable"()
// CHECK: return
// CANONICAL-LABEL: sil hidden @$s8builtins11unreachableyyF : $@convention(thin) () -> () {
func unreachable() {
Builtin.unreachable()
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins15reinterpretCast_1xBw_AA1DCAA1CCSgAGtAG_BwtF : $@convention(thin) (@guaranteed C, Builtin.Word) -> (Builtin.Word, @owned D, @owned Optional<C>, @owned C)
// CHECK: bb0([[ARG1:%.*]] : @guaranteed $C, [[ARG2:%.*]] : $Builtin.Word):
// CHECK-NEXT: debug_value
// CHECK-NEXT: debug_value
// CHECK-NEXT: [[ARG1_COPY1:%.*]] = copy_value [[ARG1]]
// CHECK-NEXT: [[ARG1_TRIVIAL:%.*]] = unchecked_trivial_bit_cast [[ARG1_COPY1]] : $C to $Builtin.Word
// CHECK-NEXT: [[ARG1_COPY2:%.*]] = copy_value [[ARG1]]
// CHECK-NEXT: [[ARG1_D:%.*]] = unchecked_ref_cast [[ARG1_COPY2]] : $C to $D
// CHECK-NEXT: [[ARG1_COPY3:%.*]] = copy_value [[ARG1]]
// CHECK-NEXT: [[ARG1_OPT:%.*]] = unchecked_ref_cast [[ARG1_COPY3]] : $C to $Optional<C>
// CHECK-NEXT: [[ARG2_FROM_WORD:%.*]] = unchecked_bitwise_cast [[ARG2]] : $Builtin.Word to $C
// CHECK-NEXT: [[ARG2_FROM_WORD_COPY:%.*]] = copy_value [[ARG2_FROM_WORD]]
// CHECK-NEXT: destroy_value [[ARG1_COPY1]]
// CHECK-NEXT: [[RESULT:%.*]] = tuple ([[ARG1_TRIVIAL]] : $Builtin.Word, [[ARG1_D]] : $D, [[ARG1_OPT]] : $Optional<C>, [[ARG2_FROM_WORD_COPY:%.*]] : $C)
// CHECK: return [[RESULT]]
func reinterpretCast(_ c: C, x: Builtin.Word) -> (Builtin.Word, D, C?, C) {
return (Builtin.reinterpretCast(c) as Builtin.Word,
Builtin.reinterpretCast(c) as D,
Builtin.reinterpretCast(c) as C?,
Builtin.reinterpretCast(x) as C)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins19reinterpretAddrOnly{{[_0-9a-zA-Z]*}}F
func reinterpretAddrOnly<T, U>(_ t: T) -> U {
// CHECK: unchecked_addr_cast {{%.*}} : $*T to $*U
return Builtin.reinterpretCast(t)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins28reinterpretAddrOnlyToTrivial{{[_0-9a-zA-Z]*}}F
func reinterpretAddrOnlyToTrivial<T>(_ t: T) -> Int {
// CHECK: copy_addr %0 to [initialization] [[INPUT:%.*]] : $*T
// CHECK: [[ADDR:%.*]] = unchecked_addr_cast [[INPUT]] : $*T to $*Int
// CHECK: [[VALUE:%.*]] = load [trivial] [[ADDR]]
// CHECK: destroy_addr [[INPUT]]
return Builtin.reinterpretCast(t)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins27reinterpretAddrOnlyLoadable{{[_0-9a-zA-Z]*}}F
func reinterpretAddrOnlyLoadable<T>(_ a: Int, _ b: T) -> (T, Int) {
// CHECK: [[BUF:%.*]] = alloc_stack $Int
// CHECK: store {{%.*}} to [trivial] [[BUF]]
// CHECK: [[RES1:%.*]] = unchecked_addr_cast [[BUF]] : $*Int to $*T
// CHECK: copy_addr [[RES1]] to [initialization]
return (Builtin.reinterpretCast(a) as T,
// CHECK: [[RES:%.*]] = unchecked_addr_cast {{%.*}} : $*T to $*Int
// CHECK: load [trivial] [[RES]]
Builtin.reinterpretCast(b) as Int)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins18castToBridgeObject{{[_0-9a-zA-Z]*}}F
// CHECK: [[ARG_COPY:%.*]] = copy_value %0
// CHECK: [[BO:%.*]] = ref_to_bridge_object [[ARG_COPY]] : $C, {{%.*}} : $Builtin.Word
// CHECK-NOT: destroy_value [[ARG_COPY]]
// CHECK: return [[BO]]
func castToBridgeObject(_ c: C, _ w: Builtin.Word) -> Builtin.BridgeObject {
return Builtin.castToBridgeObject(c, w)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins23castRefFromBridgeObject{{[_0-9a-zA-Z]*}}F
// CHECK: bridge_object_to_ref [[BO:%.*]] : $Builtin.BridgeObject to $C
func castRefFromBridgeObject(_ bo: Builtin.BridgeObject) -> C {
return Builtin.castReferenceFromBridgeObject(bo)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins30castBitPatternFromBridgeObject{{[_0-9a-zA-Z]*}}F
// CHECK: bridge_object_to_word [[BO:%.*]] : $Builtin.BridgeObject to $Builtin.Word
// CHECK-NOT: destroy_value [[BO]]
func castBitPatternFromBridgeObject(_ bo: Builtin.BridgeObject) -> Builtin.Word {
return Builtin.castBitPatternFromBridgeObject(bo)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins16beginCOWMutationySbAA1CCzF
// CHECK: [[L:%.*]] = load [take] [[ADDR:%[0-9]*]]
// CHECK: ([[U:%.*]], [[B:%.*]]) = begin_cow_mutation [[L]]
// CHECK: store [[B]] to [init] [[ADDR]]
// CHECK: apply {{%[0-9]*}}([[U]]
func beginCOWMutation(_ c: inout C) -> Bool {
return Bool(_builtinBooleanLiteral: Builtin.beginCOWMutation(&c))
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins23beginCOWMutation_nativeySbAA1CCzF
// CHECK: [[L:%.*]] = load [take] [[ADDR:%[0-9]*]]
// CHECK: ([[U:%.*]], [[B:%.*]]) = begin_cow_mutation [native] [[L]]
// CHECK: store [[B]] to [init] [[ADDR]]
// CHECK: apply {{%[0-9]*}}([[U]]
func beginCOWMutation_native(_ c: inout C) -> Bool {
return Bool(_builtinBooleanLiteral: Builtin.beginCOWMutation_native(&c))
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins14endCOWMutationyyAA1CCzF
// CHECK: [[L:%.*]] = load [take] [[ADDR:%[0-9]*]]
// CHECK: [[B:%.*]] = end_cow_mutation [[L]]
// CHECK: store [[B]] to [init] [[ADDR]]
func endCOWMutation(_ c: inout C) {
Builtin.endCOWMutation(&c)
}
// ----------------------------------------------------------------------------
// isUnique variants
// ----------------------------------------------------------------------------
// NativeObject
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8isUnique{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Optional<Builtin.NativeObject>):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Optional<Builtin.NativeObject>
// CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Optional<Builtin.NativeObject>
// CHECK: return
func isUnique(_ ref: inout Builtin.NativeObject?) -> Bool {
return Bool(_builtinBooleanLiteral: Builtin.isUnique(&ref))
}
// NativeObject nonNull
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8isUnique{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Builtin.NativeObject):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0
// CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Builtin.NativeObject
// CHECK: return
func isUnique(_ ref: inout Builtin.NativeObject) -> Bool {
return Bool(_builtinBooleanLiteral: Builtin.isUnique(&ref))
}
// AnyObject (ObjC)
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8isUnique{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Optional<AnyObject>):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0
// CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Optional<AnyObject>
// CHECK: return
func isUnique(_ ref: inout Builtin.AnyObject?) -> Bool {
return Bool(_builtinBooleanLiteral: Builtin.isUnique(&ref))
}
// AnyObject (ObjC) nonNull
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8isUnique{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*AnyObject):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0
// CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*AnyObject
// CHECK: return
func isUnique(_ ref: inout Builtin.AnyObject) -> Bool {
return Bool(_builtinBooleanLiteral: Builtin.isUnique(&ref))
}
// BridgeObject nonNull
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8isUnique{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Builtin.BridgeObject):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0
// CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Builtin.BridgeObject
// CHECK: return
func isUnique(_ ref: inout Builtin.BridgeObject) -> Bool {
return Bool(_builtinBooleanLiteral: Builtin.isUnique(&ref))
}
// BridgeObject nonNull native
// CHECK-LABEL: sil hidden [ossa] @$s8builtins15isUnique_native{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Builtin.BridgeObject):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0
// CHECK: [[CAST:%.*]] = unchecked_addr_cast [[WRITE]] : $*Builtin.BridgeObject to $*Builtin.NativeObject
// CHECK: return
func isUnique_native(_ ref: inout Builtin.BridgeObject) -> Bool {
return Bool(_builtinBooleanLiteral: Builtin.isUnique_native(&ref))
}
// ----------------------------------------------------------------------------
// Builtin.castReference
// ----------------------------------------------------------------------------
class A {}
protocol PUnknown {}
protocol PClass : class {}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins19refcast_generic_any{{[_0-9a-zA-Z]*}}F
// CHECK: unchecked_ref_cast_addr T in %{{.*}} : $*T to AnyObject in %{{.*}} : $*AnyObject
func refcast_generic_any<T>(_ o: T) -> AnyObject {
return Builtin.castReference(o)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins17refcast_class_anyyyXlAA1ACF :
// CHECK: bb0([[ARG:%.*]] : @guaranteed $A):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_CASTED:%.*]] = unchecked_ref_cast [[ARG_COPY]] : $A to $AnyObject
// CHECK-NOT: destroy_value [[ARG]]
// CHECK: return [[ARG_CASTED]]
// CHECK: } // end sil function '$s8builtins17refcast_class_anyyyXlAA1ACF'
func refcast_class_any(_ o: A) -> AnyObject {
return Builtin.castReference(o)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins20refcast_punknown_any{{[_0-9a-zA-Z]*}}F
// CHECK: unchecked_ref_cast_addr PUnknown in %{{.*}} : $*PUnknown to AnyObject in %{{.*}} : $*AnyObject
func refcast_punknown_any(_ o: PUnknown) -> AnyObject {
return Builtin.castReference(o as PUnknown)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins18refcast_pclass_anyyyXlAA6PClass_pF :
// CHECK: bb0([[ARG:%.*]] : @guaranteed $PClass):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_CAST:%.*]] = unchecked_ref_cast [[ARG_COPY]] : $PClass to $AnyObject
// CHECK: return [[ARG_CAST]]
// CHECK: } // end sil function '$s8builtins18refcast_pclass_anyyyXlAA6PClass_pF'
func refcast_pclass_any(_ o: PClass) -> AnyObject {
return Builtin.castReference(o as PClass)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins20refcast_any_punknown{{[_0-9a-zA-Z]*}}F
// CHECK: unchecked_ref_cast_addr AnyObject in %{{.*}} : $*AnyObject to PUnknown in %{{.*}} : $*PUnknown
func refcast_any_punknown(_ o: AnyObject) -> PUnknown {
return Builtin.castReference(o)
}
// => SEMANTIC ARC TODO: This function is missing a borrow + extract + copy.
//
// CHECK-LABEL: sil hidden [ossa] @$s8builtins22unsafeGuaranteed_class{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%.*]] : @guaranteed $A):
// CHECK: [[P_COPY:%.*]] = copy_value [[P]]
// CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<A>([[P_COPY]] : $A)
// CHECK: ([[R:%.*]], [[K:%.*]]) = destructure_tuple [[T]]
// CHECK: destroy_value [[R]]
// CHECK: [[P_COPY:%.*]] = copy_value [[P]]
// CHECK: return [[P_COPY]] : $A
// CHECK: }
func unsafeGuaranteed_class(_ a: A) -> A {
Builtin.unsafeGuaranteed(a)
return a
}
// CHECK-LABEL: $s8builtins24unsafeGuaranteed_generic{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%.*]] : @guaranteed $T):
// CHECK: [[P_COPY:%.*]] = copy_value [[P]]
// CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P_COPY]] : $T)
// CHECK: ([[R:%.*]], [[K:%.*]]) = destructure_tuple [[T]]
// CHECK: destroy_value [[R]]
// CHECK: [[P_RETURN:%.*]] = copy_value [[P]]
// CHECK: return [[P_RETURN]] : $T
// CHECK: }
func unsafeGuaranteed_generic<T: AnyObject> (_ a: T) -> T {
Builtin.unsafeGuaranteed(a)
return a
}
// CHECK_LABEL: sil hidden [ossa] @$s8builtins31unsafeGuaranteed_generic_return{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%.*]] : @guaranteed $T):
// CHECK: [[P_COPY:%.*]] = copy_value [[P]]
// CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P_COPY]] : $T)
// CHECK: ([[R:%.*]], [[K:%.*]]) = destructure_tuple [[T]]
// CHECK: [[S:%.*]] = tuple ([[R]] : $T, [[K]] : $Builtin.Int8)
// CHECK: return [[S]] : $(T, Builtin.Int8)
// CHECK: }
func unsafeGuaranteed_generic_return<T: AnyObject> (_ a: T) -> (T, Builtin.Int8) {
return Builtin.unsafeGuaranteed(a)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins19unsafeGuaranteedEnd{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%.*]] : $Builtin.Int8):
// CHECK: builtin "unsafeGuaranteedEnd"([[P]] : $Builtin.Int8)
// CHECK: [[S:%.*]] = tuple ()
// CHECK: return [[S]] : $()
// CHECK: }
func unsafeGuaranteedEnd(_ t: Builtin.Int8) {
Builtin.unsafeGuaranteedEnd(t)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins10bindMemory{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%.*]] : $Builtin.RawPointer, [[I:%.*]] : $Builtin.Word, [[T:%.*]] : $@thick T.Type):
// CHECK: %{{.*}} = bind_memory [[P]] : $Builtin.RawPointer, [[I]] : $Builtin.Word to $*T
// CHECK: return {{%.*}} : $()
// CHECK: }
func bindMemory<T>(ptr: Builtin.RawPointer, idx: Builtin.Word, _: T.Type) {
Builtin.bindMemory(ptr, idx, T.self)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins12rebindMemory{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%.*]] : $Builtin.RawPointer, [[I:%.*]] : $Builtin.Word, [[T:%.*]] : $@thick T.Type):
// CHECK: [[BIND:%.*]] = bind_memory [[P]] : $Builtin.RawPointer, [[I]] : $Builtin.Word to $*T
// CHECK: [[REBIND:%.*]] = rebind_memory [[P]] : $Builtin.RawPointer to [[BIND]] : $Builtin.Word
// CHECK: %{{.*}} = rebind_memory [[P]] : $Builtin.RawPointer to [[REBIND]] : $Builtin.Word
// CHECK: return {{%.*}} : $()
// CHECK: }
func rebindMemory<T>(ptr: Builtin.RawPointer, idx: Builtin.Word, _: T.Type) {
let previousBindings = Builtin.bindMemory(ptr, idx, T.self)
let genericBinding = Builtin.rebindMemory(ptr, previousBindings)
Builtin.rebindMemory(ptr, genericBinding)
}
//===----------------------------------------------------------------------===//
// RC Operations
//===----------------------------------------------------------------------===//
// SILGen test:
//
// CHECK-LABEL: sil hidden [ossa] @$s8builtins6retain{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed Builtin.NativeObject) -> () {
// CHECK: bb0([[P:%.*]] : @guaranteed $Builtin.NativeObject):
// CHECK: unmanaged_retain_value [[P]]
// CHECK: } // end sil function '$s8builtins6retain{{[_0-9a-zA-Z]*}}F'
// SIL Test. This makes sure that we properly clean up in -Onone SIL.
// CANONICAL-LABEL: sil hidden @$s8builtins6retain{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed Builtin.NativeObject) -> () {
// CANONICAL: bb0([[P:%.*]] : $Builtin.NativeObject):
// CANONICAL: strong_retain [[P]]
// CANONICAL-NOT: retain
// CANONICAL-NOT: release
// CANONICAL: } // end sil function '$s8builtins6retain{{[_0-9a-zA-Z]*}}F'
func retain(ptr: Builtin.NativeObject) {
Builtin.retain(ptr)
}
// SILGen test:
//
// CHECK-LABEL: sil hidden [ossa] @$s8builtins7release{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed Builtin.NativeObject) -> () {
// CHECK: bb0([[P:%.*]] : @guaranteed $Builtin.NativeObject):
// CHECK: unmanaged_release_value [[P]]
// CHECK-NOT: destroy_value [[P]]
// CHECK: } // end sil function '$s8builtins7release{{[_0-9a-zA-Z]*}}F'
// SIL Test. Make sure even in -Onone code, we clean this up properly:
// CANONICAL-LABEL: sil hidden @$s8builtins7release{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed Builtin.NativeObject) -> () {
// CANONICAL: bb0([[P:%.*]] : $Builtin.NativeObject):
// CANONICAL-NEXT: debug_value
// CANONICAL-NEXT: strong_release [[P]]
// CANONICAL-NEXT: tuple
// CANONICAL-NEXT: tuple
// CANONICAL-NEXT: return
// CANONICAL: } // end sil function '$s8builtins7release{{[_0-9a-zA-Z]*}}F'
func release(ptr: Builtin.NativeObject) {
Builtin.release(ptr)
}
//===----------------------------------------------------------------------===//
// Other Operations
//===----------------------------------------------------------------------===//
func once_helper(_ context: Builtin.RawPointer) {}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins4once7controlyBp_tF
// CHECK: [[T0:%.*]] = function_ref @$s8builtins11once_helperyyBpFTo : $@convention(c) (Builtin.RawPointer) -> ()
// CHECK-NEXT: builtin "once"(%0 : $Builtin.RawPointer, [[T0]] : $@convention(c) (Builtin.RawPointer) -> ())
func once(control: Builtin.RawPointer) {
Builtin.once(control, once_helper)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins19valueToBridgeObjectyBbSuF : $@convention(thin) (UInt) -> @owned Builtin.BridgeObject {
// CHECK: bb0([[UINT:%.*]] : $UInt):
// CHECK: [[BI:%.*]] = struct_extract [[UINT]] : $UInt, #UInt._value
// CHECK: [[CAST:%.*]] = value_to_bridge_object [[BI]]
// CHECK: [[RET:%.*]] = copy_value [[CAST]] : $Builtin.BridgeObject
// CHECK: return [[RET]] : $Builtin.BridgeObject
// CHECK: } // end sil function '$s8builtins19valueToBridgeObjectyBbSuF'
func valueToBridgeObject(_ x: UInt) -> Builtin.BridgeObject {
return Builtin.valueToBridgeObject(x._value)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins10assumeTrueyyBi1_F
// CHECK: builtin "assume_Int1"({{.*}} : $Builtin.Int1)
// CHECK: return
func assumeTrue(_ x: Builtin.Int1) {
Builtin.assume_Int1(x)
}
// CHECK: sil hidden [ossa] @$s8builtins15assumeAlignmentyyBp_BwtF : $@convention(thin) (Builtin.RawPointer, Builtin.Word) -> () {
// CHECK: builtin "assumeAlignment"(%{{.*}} : $Builtin.RawPointer, %{{.*}} : $Builtin.Word) : $Builtin.RawPointer
// CHECK: return
func assumeAlignment(_ p: Builtin.RawPointer, _ x: Builtin.Word) {
Builtin.assumeAlignment(p, x)
}
| apache-2.0 | c0f6263c435f490c9e93d3ad192183b3 | 42 | 200 | 0.625309 | 3.204413 | false | false | false | false |
Kijjakarn/Crease-Pattern-Analyzer | CreasePatternAnalyzer/Models/PointVector.swift | 1 | 3391 | //
// PointVector.swift
// CreasePatternAnalyzer
//
// Copyright © 2016-2017 Kijjakarn Praditukrit. All rights reserved.
//
import Darwin
struct PointVector: Hashable, CustomStringConvertible {
var x = 0.0
var y = 0.0
var magnitude: Double {
return sqrt(magnitudeSquared())
}
var hashValue: Int {
let fx = x/main.paper.width
let fy = y/main.paper.height
let nx = Int(floor(0.5 + fx*Double(main.numX)))
let ny = Int(floor(0.5 + fy*Double(main.numY)))
return 1 + nx*main.numY + ny
}
var description: String {
let xx = Float(x)
let yy = Float(y)
return "(\(abs(xx) < main.εF ? 0 : xx), \(abs(yy) < main.εF ? 0 : yy))"
}
init(_ x: Double, _ y: Double) {
self.x = x
self.y = y
}
func magnitudeSquared() -> Double {
return x*x + y*y
}
func dot(_ point: PointVector) -> Double {
return x*point.x + y*point.y
}
// Rotate the PointVector counterclockwise about the origin
// angle is in radians
func rotatedBy(_ angle: Double) -> PointVector {
let sn = sin(angle)
let cs = cos(angle)
return PointVector(x*cs - y*sn, x*sn + y*cs)
}
// Rotate the PointVector counterclockwise about the origin
func rotatedBy90() -> PointVector {
return PointVector(-y, x)
}
func normalized() -> PointVector {
let mag = magnitude
return PointVector(x/mag, y/mag)
}
// Make PointVector close to zero equal to (0, 0)
mutating func chop() {
if abs(x) < main.ε { x = 0 }
if abs(y) < main.ε { y = 0 }
}
func chopped() -> PointVector {
return PointVector(abs(x) < main.ε ? 0 : x, abs(y) < main.ε ? 0 : y)
}
}
func ==(left: PointVector, right: PointVector) -> Bool {
return left.hashValue == right.hashValue
}
// Operator overloads for PointVector
func +(left: PointVector, right: PointVector) -> PointVector {
return PointVector(left.x + right.x, left.y + right.y)
}
func -(left: PointVector, right: PointVector) -> PointVector {
return PointVector(left.x - right.x, left.y - right.y)
}
func *(left: PointVector, right: PointVector) -> PointVector {
return PointVector(left.x * right.x, left.y * right.y)
}
func /(left: PointVector, right: PointVector) -> PointVector {
return PointVector(left.x / right.x, left.y / right.y)
}
func +(left: PointVector, distance: Double) -> PointVector {
return PointVector(left.x + distance, left.y + distance)
}
func -(left: PointVector, distance: Double) -> PointVector {
return PointVector(left.x - distance, left.y - distance)
}
func *(left: PointVector, distance: Double) -> PointVector {
return PointVector(left.x * distance, left.y * distance)
}
func /(left: PointVector, distance: Double) -> PointVector {
return PointVector(left.x / distance, left.y / distance)
}
func +=(left: inout PointVector, right: PointVector) {
left.x = left.x + right.x
left.y = left.y + right.y
}
func -=(left: inout PointVector, right: PointVector) {
left.x = left.x - right.x
left.y = left.y - right.y
}
func *=(left: inout PointVector, right: PointVector) {
left.x = left.x * right.x
left.y = left.y * right.y
}
func /=(left: inout PointVector, right: PointVector) {
left.x = left.x / right.x
left.y = left.y / right.y
}
| gpl-3.0 | 4ea4a919dc441f1b7dbddc6b4a6b6ff1 | 27.2 | 79 | 0.611111 | 3.317647 | false | false | false | false |
tdquang/CarlWrite | CVCalendar/CVCalendarTouchController.swift | 1 | 4601 | //
// CVCalendarTouchController.swift
// CVCalendar Demo
//
// Created by Eugene Mozharovsky on 17/03/15.
// Copyright (c) 2015 GameApp. All rights reserved.
//
import UIKit
class CVCalendarTouchController {
private unowned let calendarView: CalendarView
// MARK: - Properties
var coordinator: Coordinator {
get {
return calendarView.coordinator
}
}
/// Init.
init(calendarView: CalendarView) {
self.calendarView = calendarView
}
}
// MARK: - Events receive
extension CVCalendarTouchController {
func receiveTouchLocation(location: CGPoint, inMonthView monthView: CVCalendarMonthView, withSelectionType selectionType: CVSelectionType) {
let weekViews = monthView.weekViews
if let dayView = ownerTouchLocation(location, onMonthView: monthView) where dayView.userInteractionEnabled {
receiveTouchOnDayView(dayView, withSelectionType: selectionType)
}
}
func receiveTouchLocation(location: CGPoint, inWeekView weekView: CVCalendarWeekView, withSelectionType selectionType: CVSelectionType) {
let monthView = weekView.monthView
let index = weekView.index
let weekViews = monthView.weekViews
if let dayView = ownerTouchLocation(location, onWeekView: weekView) where dayView.userInteractionEnabled {
receiveTouchOnDayView(dayView, withSelectionType: selectionType)
}
}
func receiveTouchOnDayView(dayView: CVCalendarDayView) {
coordinator.performDayViewSingleSelection(dayView)
}
}
// MARK: - Events management
private extension CVCalendarTouchController {
func receiveTouchOnDayView(dayView: CVCalendarDayView, withSelectionType selectionType: CVSelectionType) {
if let calendarView = dayView.weekView.monthView.calendarView {
switch selectionType {
case .Single:
coordinator.performDayViewSingleSelection(dayView)
calendarView.didSelectDayView(dayView)
case let .Range(.Started):
print("Received start of range selection.")
case let .Range(.Changed):
print("Received change of range selection.")
case let .Range(.Ended):
print("Received end of range selection.")
default: break
}
}
}
func monthViewLocation(location: CGPoint, doesBelongToDayView dayView: CVCalendarDayView) -> Bool {
var dayViewFrame = dayView.frame
let weekIndex = dayView.weekView.index
let appearance = dayView.calendarView.appearance
if weekIndex > 0 {
dayViewFrame.origin.y += dayViewFrame.height
dayViewFrame.origin.y *= CGFloat(dayView.weekView.index)
}
if dayView != dayView.weekView.dayViews!.first! {
dayViewFrame.origin.y += appearance.spaceBetweenWeekViews! * CGFloat(weekIndex)
}
if location.x >= dayViewFrame.origin.x && location.x <= CGRectGetMaxX(dayViewFrame) && location.y >= dayViewFrame.origin.y && location.y <= CGRectGetMaxY(dayViewFrame) {
return true
} else {
return false
}
}
func weekViewLocation(location: CGPoint, doesBelongToDayView dayView: CVCalendarDayView) -> Bool {
let dayViewFrame = dayView.frame
if location.x >= dayViewFrame.origin.x && location.x <= CGRectGetMaxX(dayViewFrame) && location.y >= dayViewFrame.origin.y && location.y <= CGRectGetMaxY(dayViewFrame) {
return true
} else {
return false
}
}
func ownerTouchLocation(location: CGPoint, onMonthView monthView: CVCalendarMonthView) -> DayView? {
var owner: DayView?
let weekViews = monthView.weekViews
for weekView in weekViews {
for dayView in weekView.dayViews! {
if self.monthViewLocation(location, doesBelongToDayView: dayView) {
owner = dayView
return owner
}
}
}
return owner
}
func ownerTouchLocation(location: CGPoint, onWeekView weekView: CVCalendarWeekView) -> DayView? {
var owner: DayView?
let dayViews = weekView.dayViews
for dayView in dayViews {
if weekViewLocation(location, doesBelongToDayView: dayView) {
owner = dayView
return owner
}
}
return owner
}
} | mit | 08bdc3ad434d18922d8aa8aaf9e47b5d | 33.343284 | 177 | 0.631167 | 5.694307 | false | false | false | false |
louisdh/lioness | Sources/Lioness/Standard Library/StdLib.swift | 1 | 1022 | //
// StdLib.swift
// Lioness
//
// Created by Louis D'hauwe on 11/12/2016.
// Copyright © 2016 - 2017 Silver Fox. All rights reserved.
//
import Foundation
public class StdLib {
private let sources = ["Arithmetic", "Geometry", "Graphics"]
public init() {
}
public func stdLibCode() throws -> String {
var stdLib = ""
#if SWIFT_PACKAGE
// Swift packages don't currently have a resources folder
var url = URL(fileURLWithPath: #file)
url.deleteLastPathComponent()
url.appendPathComponent("Sources")
let resourcesPath = url.path
#else
let bundle = Bundle(for: type(of: self))
guard let resourcesPath = bundle.resourcePath else {
throw StdLibError.resourceNotFound
}
#endif
for sourceName in sources {
let resourcePath = "\(resourcesPath)/\(sourceName).lion"
let source = try String(contentsOfFile: resourcePath, encoding: .utf8)
stdLib += source
}
return stdLib
}
enum StdLibError: Error {
case resourceNotFound
}
}
| mit | c2fa72c22a90910d709ea23f448c36b5 | 16.305085 | 73 | 0.666014 | 3.659498 | false | false | false | false |
albinekcom/BitBay-Ticker-iOS | Codebase/Models/Ticker.swift | 1 | 1873 | struct Ticker: Codable {
struct Currency: Codable {
let id: String
let name: String?
let precision: Int
}
let id: String
let firstCurrency: Currency
let secondCurrency: Currency
let highestBid: Double?
let lowestAsk: Double?
let rate: Double?
let previousRate: Double?
let highestRate: Double?
let lowestRate: Double?
let volume: Double?
let average: Double?
}
extension Ticker {
var change: Double? {
guard let average = average,
let rate = rate else { return nil }
return rate - average
}
var changeRatio: Double? {
guard let change = change,
let average = average else { return nil }
return change / average
}
var volumeValue: Double? {
guard let volume = volume,
let rate = rate else { return nil }
return volume * rate
}
}
extension Ticker: Equatable {
static func == (lhs: Ticker, rhs: Ticker) -> Bool {
lhs.id == rhs.id &&
lhs.highestBid == rhs.highestBid &&
lhs.lowestAsk == rhs.lowestAsk &&
lhs.rate == rhs.rate &&
lhs.previousRate == rhs.previousRate &&
lhs.highestRate == rhs.highestRate &&
lhs.lowestRate == rhs.lowestRate &&
lhs.volume == rhs.volume &&
lhs.average == rhs.average
}
}
extension Ticker: Comparable {
static func <(lhs: Ticker, rhs: Ticker) -> Bool {
lhs.secondCurrency.id == rhs.secondCurrency.id ? lhs.firstCurrency.id < rhs.firstCurrency.id : lhs.secondCurrency.id < rhs.secondCurrency.id
}
}
extension Array where Element == Ticker {
subscript(tickerId: String) -> Ticker? {
first { $0.id == tickerId }
}
}
| mit | b55fb9fcf3b67c152a9d527f45cd1638 | 21.566265 | 148 | 0.555259 | 4.295872 | false | false | false | false |
robertofrontado/OkDataSources | OkDataSourcesExample/OkDataSourcesExample/ViewControllers/CollectionViewController.swift | 2 | 1473 | //
// CollectionViewController.swift
// OkDataSourcesExample
//
// Created by Roberto Frontado on 4/8/16.
// Copyright © 2016 Roberto Frontado. All rights reserved.
//
import UIKit
class CollectionViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
var dataSource: OkCollectionViewDataSource<Item, CollectionViewCell>!
var delegate: OkCollectionViewDelegate<OkCollectionViewDataSource<Item, CollectionViewCell>>!
override func viewDidLoad() {
super.viewDidLoad()
dataSource = OkCollectionViewDataSource()
delegate = OkCollectionViewDelegate(dataSource: dataSource,
onItemClicked: { (item, position) in
self.showAlertMessage("\(item.value) clicked")
})
delegate.setOnPullToRefresh(collectionView) { (refreshControl) -> Void in
print("refreshed")
refreshControl.endRefreshing()
}
delegate.setOnPagination { (item) -> Void in
self.addMockItems(self.dataSource.items.count)
}
collectionView.dataSource = dataSource
collectionView.delegate = delegate
addMockItems()
}
private func addMockItems(_ count: Int = 0) {
var items = [Item]()
for i in count..<(count + 30) {
items.append(Item(value: "Item \(i)"))
}
dataSource.items.append(contentsOf: items)
collectionView.reloadData()
}
}
| apache-2.0 | 9653602c6027a56c073f702dab3277bc | 31.711111 | 97 | 0.649457 | 5.12892 | false | false | false | false |
frootloops/swift | test/IRGen/unexploded-calls.swift | 1 | 1582 | // RUN: %swift -target thumbv7-unknown-windows-msvc -parse-stdlib -parse-as-library -I %S/Inputs/usr/include -module-name Swift -S -emit-ir -o - %s | %FileCheck %s
// RUN: %swift -target thumbv7-unknown-linux-gnueabihf -parse-stdlib -parse-as-library -I %S/Inputs/usr/include -module-name Swift -S -emit-ir -o - %s | %FileCheck %s
// RUN: %swift -target thumbv7-unknown-linux-gnueabi -Xcc -mfloat-abi=hard -parse-stdlib -parse-as-library -I %S/Inputs/usr/include -module-name Swift -S -emit-ir -o - %s | %FileCheck %s
// REQUIRES: CODEGENERATOR=ARM
struct Float {
let _value: Builtin.FPIEEE32
}
typealias CFloat = Float
typealias Void = ()
import SRoA
public func g(_ s : S) {
return f(s)
}
// CHECK: define {{.*}}swiftcc void @_T0s1gySC1SVF(float, float) {{.*}}{
// CHECK: entry:
// CHECK: [[ALLOCA:%[-._0-9a-zA-Z]+]] = alloca %TSC1SV, align 4
// CHECK: %2 = bitcast %TSC1SV* [[ALLOCA]] to i8*
// CHECK: [[ALLOCA]].f = getelementptr inbounds %TSC1SV, %TSC1SV* [[ALLOCA]], i32 0, i32 0
// CHECK: [[ALLOCA]].f._value = getelementptr inbounds %TSf, %TSf* [[ALLOCA]].f, i32 0, i32 0
// CHECK: store float %0, float* [[ALLOCA]].f._value, align 4
// CHECK: [[ALLOCA]].g = getelementptr inbounds %TSC1SV, %TSC1SV* [[ALLOCA]], i32 0, i32 1
// CHECK: [[ALLOCA]].g._value = getelementptr inbounds %TSf, %TSf* [[ALLOCA]].g, i32 0, i32 0
// CHECK: store float %1, float* [[ALLOCA]].g._value, align 4
// CHECK: %3 = bitcast %TSC1SV* [[ALLOCA]] to %struct.S*
// CHECK: %4 = load %struct.S, %struct.S* %3, align 4
// CHECK: call void @f(%struct.S %4)
// CHECK: }
| apache-2.0 | 0c04de2f60584db410a437006b7a0639 | 45.529412 | 186 | 0.640961 | 2.804965 | false | false | false | false |
Bartlebys/Bartleby | Bartleby.xOS/extensions/String+Helpers.swift | 1 | 6313 | //
// String+Helpers.swift
// BartlebyKit
//
// Created by Benoit Pereira da silva on 08/06/2017.
//
//
import Foundation
// MARK: - String extension
public extension String {
public func contains(string: String) -> Bool {
return (self.range(of: string) != nil)
}
public func contains(_ string: String,compareOptions:NSString.CompareOptions) -> Bool {
return (self.range(of: string, options: compareOptions, range: self.fullCharactersRange(), locale: Locale.current) != nil )
}
public func isMatching(_ regex: String) -> Bool {
do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let matchCount = regex.numberOfMatches(in: self, options: [], range: NSMakeRange(0, self.count))
return matchCount > 0
} catch {
glog("\(error)", file:#file, function:#function, line: #line)
}
return false
}
public func getMatches(_ regex: String, options: NSRegularExpression.Options) -> [NSTextCheckingResult]? {
do {
let regex = try NSRegularExpression(pattern: regex, options: options)
let matches = regex.matches(in: self, options: [], range: NSMakeRange(0, self.count))
return matches
} catch {
glog("\(error)", file:#file, function:#function, line: #line)
}
return nil
}
public func fullCharactersRange() -> Range<Index> {
return Range(uncheckedBounds: (lower: self.startIndex, upper: self.endIndex))
}
public func firstCharacterRange()->Range<Index> {
return Range(uncheckedBounds: (lower: self.startIndex, upper: self.startIndex))
}
public func lastCharacterRange()->Range<Index> {
return Range(uncheckedBounds: (lower: self.endIndex, upper: self.endIndex))
}
public func jsonPrettify()->String{
do {
if let d=self.data(using:.utf8){
let jsonObject = try JSONSerialization.jsonObject(with: d, options:[])
let jsonObjectData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
if let prettyString = String(data: jsonObjectData, encoding: .utf8){
return prettyString
}
}
} catch {
return self
}
return self
}
public func fullNSRange()->NSRange{
return NSRange(location: 0, length: self.count)
}
/*
public func nsRange(from range: Range<String.Index>) -> NSRange {
let utf16 = self.utf16
let from = range.lowerBound.samePosition(in: utf16)
let to = range.upperBound.samePosition(in: utf16)
return NSRange(location: utf16.distance(from: utf16.startIndex, to: from),
length: utf16.distance(from: from, to: to))
}
*/
public func range(from nsRange: NSRange) -> Range<String.Index>? {
let utf16 = self.utf16
guard
let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
let to16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location + nsRange.length, limitedBy: utf16.endIndex),
let from = from16.samePosition(in: self),
let to = to16.samePosition(in: self)
else { return nil }
return from ..< to
}
/// Removes the characters in the sub NSRange.
/// The method is ignoring the invalid ranges.
///
/// - Parameter range: the range of char to remove
public mutating func removeSubNSRange(_ range:NSRange){
let rangeEndLocation = range.location + range.length
let charCount = self.count
let prefixed = range.location > 0 ? PString.substr(self, 0, range.location) : ""
let postFixed = rangeEndLocation < charCount ? PString.substr(self, rangeEndLocation) : ""
self = prefixed + postFixed
}
// MARK: - levenshtein distance
// https://en.wikipedia.org/wiki/Levenshtein_distance
public func bestCandidate(candidates: [String]) -> (distance:Int,string:String) {
var selectedCandidate:String=""
var minDistance: Int=Int.max
for candidate in candidates {
let distance=self.levenshtein(candidate)
if distance<minDistance {
minDistance=distance
selectedCandidate=candidate
}
}
return (minDistance,selectedCandidate)
}
/// Computes the levenshteinDistance between
///
/// - Parameter string: string to compare to
/// - Returns: return the distance
public func levenshtein( _ string: String) -> Int {
guard self != "" && string != "" else{
return Int.max
}
let a = Array(self.utf16)
let b = Array(string.utf16)
let dist = Array2D(cols: a.count + 1, rows: b.count + 1)
for i in 1...a.count {
dist[i, 0] = i
}
for j in 1...b.count {
dist[0, j] = j
}
for i in 1...a.count {
for j in 1...b.count {
if a[i-1] == b[j-1] {
dist[i, j] = dist[i-1, j-1] // noopo
} else {
dist[i,j] = min(numbers:
dist[i-1, j] + 1, // deletion
dist[i, j-1] + 1, // insertion
dist[i-1, j-1] + 1 // substitution
)
}
}
}
return dist[a.count, b.count]
}
private func min(numbers: Int...) -> Int {
return numbers.reduce(numbers[0], {$0 < $1 ? $0 : $1})
}
private class Array2D {
var cols: Int, rows: Int
var matrix: [Int]
init(cols: Int, rows: Int) {
self.cols = cols
self.rows = rows
matrix = Array(repeating:0, count:cols*rows)
}
subscript(col: Int, row: Int) -> Int {
get {
return matrix[cols * row + col]
}
set {
matrix[cols*row+col] = newValue
}
}
func colCount() -> Int {
return self.cols
}
func rowCount() -> Int {
return self.rows
}
}
}
| apache-2.0 | fc29b39d21a29208deff7c81d53758fb | 29.645631 | 131 | 0.554887 | 4.291638 | false | false | false | false |
jjbourdev/JBButton | JBButton/JBLayouting.swift | 1 | 9182 | //
// JBLayouting.swift
// JBButton
//
// Created by Jérôme Boursier on 17/06/2016.
// Copyright © 2016 Jérôme Boursier. All rights reserved.
//
// MARK:- Extension for animation stuff
private typealias JBLayouting = JBButton
public extension JBLayouting {
// MARK:- Layouting
override public func drawRect(rect: CGRect) {
self.cleanView()
let imageView = UIImageView(image: self.image)
let frames: (CGRect, CGRect)?
switch positionValue {
case .top:
frames = self.layoutForTop(fromImageView: imageView)
case .bottom:
frames = self.layoutForBottom(fromImageView: imageView)
case .left:
frames = self.layoutForLeft(fromImageView: imageView)
case .right:
frames = self.layoutForRight(fromImageView: imageView)
case .centered:
frames = self.layoutForCentered(fromImageView: imageView)
}
// Setup image
self.setupImageView(withFrame: frames!.0)
// Setup label
self.setupLabel(withFrame: frames!.1)
// Add subviews
self.addSubview(self.titleLabel!)
self.addSubview(self.imageView!)
}
/**
Cleans the view
*/
private func cleanView() {
if self.titleLabel!.isDescendantOfView(self) {
self.titleLabel!.removeFromSuperview()
}
if !self.imageView!.isDescendantOfView(self) {
self.imageView!.removeFromSuperview()
}
}
/**
Determines the layout of the button if the selected layout option is `.top`
- parameter imageView: the imageView containing the image to display
- returns: a tuple containing the frames of both the image and the label
*/
private func layoutForTop(fromImageView imageView: UIImageView) -> (CGRect, CGRect) {
let imageViewFrame = CGRect(
x: self.frame.width/2 - imageView.frame.width/2,
y: 0 + self.customPadding,
width: imageView.frame.width,
height: imageView.frame.height)
let titleLabelFrame = CGRect(
x: 0 + self.customPadding,
y: imageView.frame.height + self.customPadding,
width: self.frame.width - 2 * self.customPadding,
height: self.frame.height - imageView.frame.height - 2 * self.customPadding)
return (imageViewFrame, titleLabelFrame)
}
/**
Determines the layout of the button if the selected layout option is `.bottom`
- parameter imageView: the imageView containing the image to display
- returns: a tuple containing the frames of both the image and the label
*/
private func layoutForBottom(fromImageView imageView: UIImageView) -> (CGRect, CGRect) {
let imageViewFrame = CGRect(
x: self.frame.width/2 - imageView.frame.width/2,
y: self.frame.height - imageView.frame.height - self.customPadding,
width: imageView.frame.width,
height: imageView.frame.height)
let titleLabelFrame = CGRect(
x: 0 + self.customPadding,
y: 0 + self.customPadding,
width: self.frame.width - 2 * self.customPadding,
height: self.frame.height - imageView.frame.height - 2 * self.customPadding)
return (imageViewFrame, titleLabelFrame)
}
/**
Determines the layout of the button if the selected layout option is `.left`
- parameter imageView: the imageView containing the image to display
- returns: a tuple containing the frames of both the image and the label
*/
private func layoutForLeft(fromImageView imageView: UIImageView) -> (CGRect, CGRect) {
let imageViewFrame = CGRect(
x: 0 + self.customPadding,
y: self.frame.height/2 - imageView.frame.height/2,
width: imageView.frame.width,
height: imageView.frame.height)
let titleLabelFrame = CGRect(
x: imageView.frame.width + self.customPadding,
y: 0 + self.customPadding,
width: self.frame.width - imageView.frame.width - 2 * self.customPadding,
height: self.frame.height - 2 * self.customPadding)
return (imageViewFrame, titleLabelFrame)
}
/**
Determines the layout of the button if the selected layout option is `.right`
- parameter imageView: the imageView containing the image to display
- returns: a tuple containing the frames of both the image and the label
*/
private func layoutForRight(fromImageView imageView: UIImageView) -> (CGRect, CGRect) {
let imageViewFrame = CGRect(
x: self.frame.width - imageView.frame.width - self.customPadding,
y: self.frame.height/2 - imageView.frame.height/2,
width: imageView.frame.width,
height: imageView.frame.height)
let titleLabelFrame = CGRect(
x: 0 + self.customPadding,
y: 0 + self.customPadding,
width: self.frame.width - imageView.frame.width - 2 * self.customPadding,
height: self.frame.height - 2 * self.customPadding)
return (imageViewFrame, titleLabelFrame)
}
/**
Determines the layout of the button if the selected layout option is `.centered`
- parameter imageView: the imageView containing the image to display
- returns: a tuple containing the frames of both the image and the label
*/
internal func layoutForCentered(fromImageView imageView: UIImageView) -> (CGRect, CGRect) {
let imageViewFrame = CGRect(
x: self.frame.width/2 - imageView.frame.width/2,
y: self.frame.height/2 - imageView.frame.height/2,
width: imageView.frame.width,
height: imageView.frame.height)
return (imageViewFrame, CGRect.zero)
}
/**
Determines the layout of the default frame for the loader
- returns: the default frame for the loader
*/
internal func defaultFrameForLoader() -> CGRect {
return CGRect(
x: self.frame.width/2 - self.titleLabel!.frame.height/4,
y: self.frame.height/2 - self.titleLabel!.frame.height/4,
width: self.titleLabel!.frame.height/2,
height: self.titleLabel!.frame.height/2)
}
/**
Determines the frame of the loader
- returns: The calculated frame of the loader
*/
internal func determineLoaderFrame() -> CGRect {
if self.customLoader?.frame != CGRect.zero {
return self.customLoader!.frame
}
if self.hideTitleOnLoad {
// hide title and center
self.positionValue = Position.centered
if self.image == nil {
// hide title and default center
return self.defaultFrameForLoader()
} else {
// hide title and center
let center = CGPoint(x: self.frame.width/2 - self.imageView!.frame.height/2,
y: self.frame.height/2 - self.imageView!.frame.height/2)
self.customLoader?.center = center
self.customLoader?.frame.size = self.imageView!.frame.size
return self.customLoader!.frame
}
} else {
if self.image == nil {
// hide title and default center
self.positionValue = Position.centered
return self.defaultFrameForLoader()
} else {
// frame = image frame
return self.imageView!.frame
}
}
}
/**
Setups the imageView with user defined attributes
- parameter frame: the frame of the imageView previously calculated
*/
private func setupImageView(withFrame frame: CGRect) {
self.imageView?.frame = frame
self.imageView?.tintColor = self.imageColor
self.imageView?.backgroundColor = UIColor.clearColor()
if self.image != nil {
switch self.renderingMode {
case .original:
self.imageView?.image = self.image!.imageWithRenderingMode(.AlwaysOriginal)
case .template:
self.imageView?.image = self.image!.imageWithRenderingMode(.AlwaysTemplate)
}
}
}
/**
Setups the label with user defined attributes
- parameter frame: the frame of the label previously calculated
*/
private func setupLabel(withFrame frame: CGRect) {
self.titleLabel = UILabel(frame: frame)
self.titleLabel?.text = self.title
self.titleLabel?.textColor = self.titleColor
self.titleLabel?.textAlignment = NSTextAlignment(rawValue: NSInteger(self.titleAlignment)) ?? .Left
self.titleLabel?.font = self.customFont
self.titleLabel?.backgroundColor = UIColor.clearColor()
}
}
| mit | f34feae65127e1189dfeb67addbeaa01 | 35.272727 | 107 | 0.600414 | 4.858126 | false | false | false | false |
Beaver/BeaverCodeGen | Pods/SourceKittenFramework/Source/SourceKittenFramework/JSONOutput.swift | 1 | 4788 | //
// JSONOutput.swift
// SourceKitten
//
// Created by Thomas Goyne on 9/17/15.
// Copyright © 2015 SourceKitten. All rights reserved.
//
import Foundation
/**
JSON Object to JSON String.
- parameter object: Object to convert to JSON.
- returns: JSON string representation of the input object.
*/
public func toJSON(_ object: Any) -> String {
if let array = object as? [Any], array.isEmpty {
return "[\n\n]"
}
do {
let options: JSONSerialization.WritingOptions
#if swift(>=3.2)
#if os(Linux)
options = [.prettyPrinted, .sortedKeys]
#else
if #available(macOS 10.13, *) {
options = [.prettyPrinted, .sortedKeys]
} else {
options = .prettyPrinted
}
#endif
#else
options = .prettyPrinted
#endif
let prettyJSONData = try JSONSerialization.data(withJSONObject: object, options: options)
if let jsonString = String(data: prettyJSONData, encoding: .utf8) {
return jsonString
}
} catch {}
return ""
}
/**
Convert [String: SourceKitRepresentable] to `NSDictionary`.
- parameter dictionary: [String: SourceKitRepresentable] to convert.
- returns: JSON-serializable value.
*/
public func toNSDictionary(_ dictionary: [String: SourceKitRepresentable]) -> NSDictionary {
var anyDictionary = [String: Any]()
for (key, object) in dictionary {
switch object {
case let object as [SourceKitRepresentable]:
anyDictionary[key] = object.map { toNSDictionary($0 as! [String: SourceKitRepresentable]) }
case let object as [[String: SourceKitRepresentable]]:
anyDictionary[key] = object.map { toNSDictionary($0) }
case let object as [String: SourceKitRepresentable]:
anyDictionary[key] = toNSDictionary(object)
case let object as String:
anyDictionary[key] = object
case let object as Int64:
anyDictionary[key] = NSNumber(value: object)
case let object as Bool:
anyDictionary[key] = NSNumber(value: object)
case let object as Any:
anyDictionary[key] = object
default:
fatalError("Should never happen because we've checked all SourceKitRepresentable types")
}
}
return anyDictionary.bridge()
}
#if !os(Linux)
public func declarationsToJSON(_ decl: [String: [SourceDeclaration]]) -> String {
let keyValueToDictionary: ((String, [SourceDeclaration])) -> [String: Any] = { [$0.0: toOutputDictionary($0.1)] }
let dictionaries: [[String: Any]] = decl.map(keyValueToDictionary).sorted { $0.keys.first! < $1.keys.first! }
return toJSON(dictionaries)
}
private func toOutputDictionary(_ decl: SourceDeclaration) -> [String: Any] {
var dict = [String: Any]()
func set(_ key: SwiftDocKey, _ value: Any?) {
if let value = value {
dict[key.rawValue] = value
}
}
func setA(_ key: SwiftDocKey, _ value: [Any]?) {
if let value = value, !value.isEmpty {
dict[key.rawValue] = value
}
}
set(.kind, decl.type.rawValue)
set(.filePath, decl.location.file)
set(.docFile, decl.location.file)
set(.docLine, Int(decl.location.line))
set(.docColumn, Int(decl.location.column))
set(.name, decl.name)
set(.usr, decl.usr)
set(.parsedDeclaration, decl.declaration)
set(.documentationComment, decl.commentBody)
set(.parsedScopeStart, Int(decl.extent.start.line))
set(.parsedScopeEnd, Int(decl.extent.end.line))
set(.swiftDeclaration, decl.swiftDeclaration)
set(.alwaysDeprecated, decl.availability?.alwaysDeprecated)
set(.alwaysUnavailable, decl.availability?.alwaysUnavailable)
set(.deprecationMessage, decl.availability?.deprecationMessage)
set(.unavailableMessage, decl.availability?.unavailableMessage)
setA(.docResultDiscussion, decl.documentation?.returnDiscussion.map(toOutputDictionary))
setA(.docParameters, decl.documentation?.parameters.map(toOutputDictionary))
setA(.substructure, decl.children.map(toOutputDictionary))
if decl.commentBody != nil {
set(.fullXMLDocs, "")
}
return dict
}
private func toOutputDictionary(_ decl: [SourceDeclaration]) -> [String: Any] {
return ["key.substructure": decl.map(toOutputDictionary), "key.diagnostic_stage": ""]
}
private func toOutputDictionary(_ param: Parameter) -> [String: Any] {
return ["name": param.name, "discussion": param.discussion.map(toOutputDictionary)]
}
private func toOutputDictionary(_ text: Text) -> [String: Any] {
switch text {
case .para(let str, let kind):
return ["kind": kind ?? "", "Para": str]
case .verbatim(let str):
return ["kind": "", "Verbatim": str]
}
}
#endif
| mit | 0d21c72046db231906597dec5dbb30f8 | 32.475524 | 117 | 0.654272 | 4.130285 | false | false | false | false |
xwu/swift | test/IRGen/async/throwing.swift | 1 | 4578 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -parse-as-library -Xfrontend -disable-availability-checking -g %s -module-name main -o %t/main
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: concurrency_runtime
// UNSUPPORTED: back_deployment_runtime
// https://bugs.swift.org/browse/SR-14333
// UNSUPPORTED: OS=windows-msvc
struct E : Error {}
func asyncCanThrowDoesThrow() async throws -> Int {
throw E()
}
func asyncCanThrowDoesntThrow() async throws -> Int {
return 0
}
func syncCanThrowDoesThrow() throws -> Int {
throw E()
}
func syncCanThrowDoesntThrow() throws -> Int {
return 0
}
func asyncCanThrowDoesThrowRecursive(_ index: Int) async throws -> Int {
if index > 0 {
return try await asyncCanThrowDoesThrowRecursive(index - 1)
} else {
return try await asyncCanThrowDoesThrow()
}
}
func asyncCanThrowDoesntThrowRecursive(_ index: Int) async throws -> Int {
if index > 0 {
return try await asyncCanThrowDoesntThrowRecursive(index - 1)
} else {
return try await asyncCanThrowDoesntThrow()
}
}
func syncCanThrowDoesThrowRecursive(_ index: Int) async throws -> Int {
if index > 0 {
return try await syncCanThrowDoesThrowRecursive(index - 1)
} else {
return try syncCanThrowDoesThrow()
}
}
func syncCanThrowDoesntThrowRecursive(_ index: Int) async throws -> Int {
if index > 0 {
return try await syncCanThrowDoesntThrowRecursive(index - 1)
} else {
return try syncCanThrowDoesntThrow()
}
}
func test<T>(_ work: () async throws -> T) async {
do {
let value = try await work()
print(value)
}
catch let error {
print(error)
}
}
// CHECK: E()
// CHECK: 0
// CHECK: E()
// CHECK: 0
func testRecursion() async {
await test { try await asyncCanThrowDoesThrowRecursive(10) }
await test { try await asyncCanThrowDoesntThrowRecursive(10) }
await test { try await syncCanThrowDoesThrowRecursive(10) }
await test { try await syncCanThrowDoesntThrowRecursive(10) }
}
func testAsyncDoesThrowThenSyncDoesThrow() async throws -> (Int, Int) {
let async = try await asyncCanThrowDoesThrow()
let sync = try syncCanThrowDoesThrow()
return (async, sync)
}
func testAsyncDoesThrowThenSyncDoesntThrow() async throws -> (Int, Int) {
let async = try await asyncCanThrowDoesThrow()
let sync = try syncCanThrowDoesntThrow()
return (async, sync)
}
func testAsyncDoesntThrowThenSyncDoesThrow() async throws -> (Int, Int) {
let async = try await asyncCanThrowDoesntThrow()
let sync = try syncCanThrowDoesThrow()
return (async, sync)
}
func testAsyncDoesntThrowThenSyncDoesntThrow() async throws -> (Int, Int) {
let async = try await asyncCanThrowDoesntThrow()
let sync = try syncCanThrowDoesntThrow()
return (async, sync)
}
func testSyncDoesThrowThenAsyncDoesThrow() async throws -> (Int, Int) {
let sync = try syncCanThrowDoesThrow()
let async = try await asyncCanThrowDoesThrow()
return (sync, async)
}
func testSyncDoesThrowThenAsyncDoesntThrow() async throws -> (Int, Int) {
let sync = try syncCanThrowDoesThrow()
let async = try await asyncCanThrowDoesntThrow()
return (sync, async)
}
func testSyncDoesntThrowThenAsyncDoesThrow() async throws -> (Int, Int) {
let sync = try syncCanThrowDoesntThrow()
let async = try await asyncCanThrowDoesThrow()
return (sync, async)
}
func testSyncDoesntThrowThenAsyncDoesntThrow() async throws -> (Int, Int) {
let sync = try syncCanThrowDoesntThrow()
let async = try await asyncCanThrowDoesntThrow()
return (sync, async)
}
public enum MyError : Error {
case a
}
// We used to crash on this.
public func throwLarge() async throws -> (Int, Int, Int, Int, Int, Int, Int, Int) {
throw MyError.a
}
// CHECK: E()
// CHECK: E()
// CHECK: E()
// CHECK: (0, 0)
// CHECK: E()
// CHECK: E()
// CHECK: E()
// CHECK: (0, 0)
func testMixture() async {
await test { try await testAsyncDoesThrowThenSyncDoesThrow() }
await test { try await testAsyncDoesThrowThenSyncDoesntThrow() }
await test { try await testAsyncDoesntThrowThenSyncDoesThrow() }
await test { try await testAsyncDoesntThrowThenSyncDoesntThrow() }
await test { try await testSyncDoesThrowThenAsyncDoesThrow() }
await test { try await testSyncDoesThrowThenAsyncDoesntThrow() }
await test { try await testSyncDoesntThrowThenAsyncDoesThrow() }
await test { try await testSyncDoesntThrowThenAsyncDoesntThrow() }
}
@main struct Main {
static func main() async {
await testRecursion()
await testMixture()
}
}
| apache-2.0 | 7d427d8830d7473eea103d9baadfad5e | 26.25 | 123 | 0.718436 | 3.570983 | false | true | false | false |
kiavashfaisali/KFSwiftImageLoader | KFSwiftImageLoader/Extensions/UIImageViewExtensions.swift | 1 | 11240 | //
// Created by Kiavash Faisali on 2015-03-17.
// Copyright (c) 2015 Kiavash Faisali. All rights reserved.
//
#if os(iOS)
import UIKit
// MARK: - UIImageView Associated Value Keys
fileprivate var indexPathIdentifierAssociationKey: UInt8 = 0
fileprivate var completionAssociationKey: UInt8 = 0
// MARK: - UIImageView Extensions
extension UIImageView: AssociatedValue {}
public extension UIImageView {
// MARK: - Associated Values
final internal var indexPathIdentifier: Int {
get {
return getAssociatedValue(key: &indexPathIdentifierAssociationKey, defaultValue: -1)
}
set {
setAssociatedValue(key: &indexPathIdentifierAssociationKey, value: newValue)
}
}
final internal var completion: ((_ finished: Bool, _ error: Error?) -> Void)? {
get {
return getAssociatedValue(key: &completionAssociationKey, defaultValue: nil)
}
set {
setAssociatedValue(key: &completionAssociationKey, value: newValue)
}
}
// MARK: - Image Loading Methods
/**
Asynchronously downloads an image and loads it into the `UIImageView` using a URL `String`.
- parameter urlString: The image URL in the form of a `String`.
- parameter placeholder: `UIImage?` representing a placeholder image that is loaded into the view while the asynchronous download takes place. The default value is `nil`.
- parameter completion: An optional closure that is called to indicate completion of the intended purpose of this method. It returns two values: the first is a `Bool` indicating whether everything was successful, and the second is `Error?` which will be non-nil should an error occur. The default value is `nil`.
*/
final func loadImage(urlString: String,
placeholder: UIImage? = nil,
completion: ((_ success: Bool, _ error: Error?) -> Void)? = nil)
{
guard let url = URL(string: urlString) else {
DispatchQueue.main.async {
completion?(false, nil)
}
return
}
loadImage(url: url, placeholder: placeholder, completion: completion)
}
/**
Asynchronously downloads an image and loads it into the `UIImageView` using a `URL`.
- parameter url: The image `URL`.
- parameter placeholder: `UIImage?` representing a placeholder image that is loaded into the view while the asynchronous download takes place. The default value is `nil`.
- parameter completion: An optional closure that is called to indicate completion of the intended purpose of this method. It returns two values: the first is a `Bool` indicating whether everything was successful, and the second is `Error?` which will be non-nil should an error occur. The default value is `nil`.
*/
final func loadImage(url: URL,
placeholder: UIImage? = nil,
completion: ((_ success: Bool, _ error: Error?) -> Void)? = nil)
{
let cacheManager = KFImageCacheManager.shared
var request = URLRequest(url: url, cachePolicy: cacheManager.session.configuration.requestCachePolicy, timeoutInterval: cacheManager.session.configuration.timeoutIntervalForRequest)
request.addValue("image/*", forHTTPHeaderField: "Accept")
loadImage(request: request, placeholder: placeholder, completion: completion)
}
/**
Asynchronously downloads an image and loads it into the `UIImageView` using a `URLRequest`.
- parameter request: The image URL in the form of a `URLRequest`.
- parameter placeholder: `UIImage?` representing a placeholder image that is loaded into the view while the asynchronous download takes place. The default value is `nil`.
- parameter completion: An optional closure that is called to indicate completion of the intended purpose of this method. It returns two values: the first is a `Bool` indicating whether everything was successful, and the second is `Error?` which will be non-nil should an error occur. The default value is `nil`.
*/
final func loadImage(request: URLRequest,
placeholder: UIImage? = nil,
completion: ((_ success: Bool, _ error: Error?) -> Void)? = nil)
{
self.completion = completion
self.indexPathIdentifier = -1
guard let urlAbsoluteString = request.url?.absoluteString else {
self.completion?(false, nil)
return
}
let cacheManager = KFImageCacheManager.shared
let fadeAnimationDuration = cacheManager.fadeAnimationDuration
let sharedURLCache = URLCache.shared
func loadImage(_ image: UIImage) -> Void {
UIView.transition(with: self, duration: fadeAnimationDuration, options: .transitionCrossDissolve, animations: {
self.image = image
})
self.completion?(true, nil)
}
// If there's already a cached image, load it into the image view.
if let image = cacheManager[urlAbsoluteString] {
loadImage(image)
}
// If there's already a cached response, load the image data into the image view.
else if let cachedResponse = sharedURLCache.cachedResponse(for: request), let image = UIImage(data: cachedResponse.data), let creationTimestamp = cachedResponse.userInfo?["creationTimestamp"] as? CFTimeInterval, (Date.timeIntervalSinceReferenceDate - creationTimestamp) < Double(cacheManager.diskCacheMaxAge) {
loadImage(image)
cacheManager[urlAbsoluteString] = image
}
// Either begin downloading the image or become an observer for an existing request.
else {
// Remove the stale disk-cached response (if any).
sharedURLCache.removeCachedResponse(for: request)
// Set the placeholder image if it was provided.
if let placeholder = placeholder {
self.image = placeholder
}
var parentView = self.superview
// Should the image be shown in a cell, walk the view hierarchy to retrieve the index path from the tableview or collectionview.
while parentView != nil {
switch parentView {
case let tableViewCell as UITableViewCell:
// Every tableview cell must be directly embedded within a tableview.
if let tableView = tableViewCell.superview as? UITableView,
let indexPath = tableView.indexPathForRow(at: tableViewCell.center)
{
self.indexPathIdentifier = indexPath.hashValue
}
case let collectionViewCell as UICollectionViewCell:
// Every collectionview cell must be directly embedded within a collectionview.
if let collectionView = collectionViewCell.superview as? UICollectionView,
let indexPath = collectionView.indexPathForItem(at: collectionViewCell.center)
{
self.indexPathIdentifier = indexPath.hashValue
}
default:
break
}
parentView = parentView?.superview
}
let initialIndexIdentifier = self.indexPathIdentifier
// If the image isn't already being downloaded, begin downloading the image.
if cacheManager.isDownloadingFromURL(urlAbsoluteString) == false {
cacheManager.setIsDownloadingFromURL(true, urlString: urlAbsoluteString)
let dataTask = cacheManager.session.dataTask(with: request) {
taskData, taskResponse, taskError in
guard let data = taskData, let response = taskResponse, let image = UIImage(data: data), taskError == nil else {
DispatchQueue.main.async {
cacheManager.setIsDownloadingFromURL(false, urlString: urlAbsoluteString)
cacheManager.removeImageCacheObserversForKey(urlAbsoluteString)
self.completion?(false, taskError)
}
return
}
DispatchQueue.main.async {
if initialIndexIdentifier == self.indexPathIdentifier {
UIView.transition(with: self, duration: fadeAnimationDuration, options: .transitionCrossDissolve, animations: {
self.image = image
})
}
cacheManager[urlAbsoluteString] = image
let responseDataIsCacheable = cacheManager.diskCacheMaxAge > 0 &&
Double(data.count) <= 0.05 * Double(sharedURLCache.diskCapacity) &&
(cacheManager.session.configuration.requestCachePolicy == .returnCacheDataElseLoad ||
cacheManager.session.configuration.requestCachePolicy == .returnCacheDataDontLoad) &&
(request.cachePolicy == .returnCacheDataElseLoad ||
request.cachePolicy == .returnCacheDataDontLoad)
if let httpResponse = response as? HTTPURLResponse, let url = httpResponse.url, responseDataIsCacheable {
if var allHeaderFields = httpResponse.allHeaderFields as? [String: String] {
allHeaderFields["Cache-Control"] = "max-age=\(cacheManager.diskCacheMaxAge)"
if let cacheControlResponse = HTTPURLResponse(url: url, statusCode: httpResponse.statusCode, httpVersion: "HTTP/1.1", headerFields: allHeaderFields) {
let cachedResponse = CachedURLResponse(response: cacheControlResponse, data: data, userInfo: ["creationTimestamp": Date.timeIntervalSinceReferenceDate], storagePolicy: .allowed)
sharedURLCache.storeCachedResponse(cachedResponse, for: request)
}
}
}
self.completion?(true, nil)
}
}
dataTask.resume()
}
// Since the image is already being downloaded and hasn't been cached, register the image view as a cache observer.
else {
weak var weakSelf = self
cacheManager.addImageCacheObserver(weakSelf!, initialIndexIdentifier: initialIndexIdentifier, key: urlAbsoluteString)
}
}
}
}
#endif
| mit | 5413c54e77138cd280463af6f1edf0a3 | 51.523364 | 320 | 0.594128 | 6.145435 | false | false | false | false |
naokits/my-programming-marathon | TinderLikePageBasedApp/TinderLikePageBasedApp/AppDelegate.swift | 1 | 4129 | //
// AppDelegate.swift
// TinderLikePageBasedApp
//
// Created by Naoki Tsutsui on 2/14/16.
// Copyright © 2016 Naoki Tsutsui. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// MARK: - Properties
var window: UIWindow?
// MARK: - Application Cycle
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
setupTinderLikePageBasedViewController()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Setup ViewController with Navigation
func setupTinderLikePageBasedViewController() {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let v1 = UIViewController()
v1.view.backgroundColor = UIColor.purpleColor()
let v2 = UIViewController()
v2.view.backgroundColor = UIColor.redColor()
let name = "Main"
let identifier = "MainViewController"
let storyboard = UIStoryboard(name: name, bundle: nil)
let v3 = storyboard.instantiateViewControllerWithIdentifier(identifier) as! MainViewController
let v4 = UIViewController()
v4.view.backgroundColor = UIColor.orangeColor()
let v5 = UIViewController()
v5.view.backgroundColor = UIColor.yellowColor()
// navigation bar (icons and strings)
let controllers = [v1,v2,v3,v4,v5]
// let iconAndTitles = NSArray(array: [UIImage(named:"photo")!, UIImage(named:"heart")!, UIImage(named:"conf")!, UIImage(named:"message")!, UIImage(named:"map")!])
// 中央のナビゲーションタイトルのみ文字列指定
let iconAndTitles = NSArray(array: [UIImage(named:"photo")!, UIImage(named:"heart")!, "設定", UIImage(named:"message")!, UIImage(named:"map")!])
let controller = AHPagingMenuViewController(controllers: controllers, icons: iconAndTitles, position:2)
controller.setShowArrow(false)
controller.setTransformScale(true)
controller.setDissectColor(UIColor(white: 0.756, alpha: 1.0));
controller.setSelectColor(UIColor(red: 0.963, green: 0.266, blue: 0.176, alpha: 1.000))
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.rootViewController = controller
self.window!.makeKeyAndVisible()
}
}
| mit | 6330de4bdc23ccbd3080a97fdcddbb25 | 45.386364 | 285 | 0.707496 | 5.02091 | false | false | false | false |
naokits/my-programming-marathon | Bluemix/StrongLoopDemo/StrongLoopClientDemo/StrongLoopClientDemo/Models/Login.swift | 1 | 2821 | //
// Login.swift
// StrongLoopClientDemo
//
// Created by Naoki Tsutsui on 5/14/16.
// Copyright © 2016 Naoki Tsutsui. All rights reserved.
//
import APIKit
struct Login {
var token: String?
var ttl: Int?
var created: String?
var userId: Int?
/*
"id": "XsTaFzM5wpdSQmi7EIXe71gNvitPeoHRrA7HDTuFJMEe0yQ9pmi2KATIMjy7rry6",
"ttl": 1209600,
"created": "2016-05-14T02:01:41.270Z",
"userId": 1
*/
init?(dic: [String: AnyObject]) {
guard let token = dic["id"] as? String else {
return nil
}
guard let ttl = dic["ttl"] as? Int else {
return nil
}
guard let created = dic["created"] as? String else {
return nil
}
guard let userId = dic["userId"] as? Int else {
return nil
}
self.token = token
self.ttl = ttl
self.created = created
self.userId = userId
}
}
protocol LoginRequestType: RequestType {
}
extension LoginRequestType {
var baseURL: NSURL {
return NSURL(string: demoBaseURL)!
}
}
struct LoginRequest: LoginRequestType {
typealias Response = Login
var method: HTTPMethod {
return .POST
}
var path: String {
return "/api/DemoUsers/login"
}
var email: String = ""
var password: String = ""
var parameters: [String: AnyObject] {
let body = [
"email": self.email,
"password": self.password,
]
return body
}
init(email: String, password: String) {
self.email = email
self.password = password
}
func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) -> Response? {
guard let dictionary = object as? [String: AnyObject] else {
return nil
}
guard let result = Login(dic: dictionary) else {
return nil
}
return result
}
}
struct LogoutRequest: LoginRequestType {
typealias Response = Login
var method: HTTPMethod {
return .POST
}
var path: String {
return "/api/DemoUsers/logout"
}
var accessToken: String = ""
var parameters: [String: AnyObject] {
return [
"access_token":self.accessToken,
]
}
init(accessToken: String) {
self.accessToken = accessToken
}
func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) -> Response? {
print(object)
guard let dictionary = object as? [String: AnyObject] else {
return nil
}
guard let result = Login(dic: dictionary) else {
return nil
}
return result
}
}
| mit | 152006358f5357e825c4eb0eef31b47a | 20.526718 | 93 | 0.549645 | 4.266263 | false | false | false | false |
drewcrawford/XcodeServerSDK | XcodeServerSDK/Server Entities/Contributor.swift | 2 | 1112 | //
// Contributor.swift
// XcodeServerSDK
//
// Created by Mateusz Zając on 21/07/15.
// Copyright © 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
// MARK: Constants
let kContributorName = "XCSContributorName"
let kContributorDisplayName = "XCSContributorDisplayName"
let kContributorEmails = "XCSContributorEmails"
public class Contributor: XcodeServerEntity {
public let name: String
public let displayName: String
public let emails: [String]
public required init(json: NSDictionary) {
self.name = json.stringForKey(kContributorName)
self.displayName = json.stringForKey(kContributorDisplayName)
self.emails = json.arrayForKey(kContributorEmails)
super.init(json: json)
}
public override func dictionarify() -> NSDictionary {
return [
kContributorName: self.name,
kContributorDisplayName: self.displayName,
kContributorEmails: self.emails
]
}
public func description() -> String {
return "\(displayName) [\(emails[0])]"
}
} | mit | 45869e761dfa98d32b9811d74f7a2c65 | 25.452381 | 69 | 0.667568 | 4.605809 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Stats/Insights/SiteStatsBaseTableViewController.swift | 1 | 1588 | import UIKit
/// Base class for site stats table view controllers
///
class SiteStatsBaseTableViewController: UIViewController {
let refreshControl = UIRefreshControl()
/// This property must be set before viewDidLoad is called - currently the classes that inherit are created from storyboards
/// When storyboard is removed it can be passed in as a parameter in an initializer
var tableStyle: UITableView.Style = .grouped
// MARK: - Properties
lazy var tableView: UITableView = {
UITableView(frame: .zero, style: tableStyle)
}()
override func viewDidLoad() {
super.viewDidLoad()
initTableView()
}
func initTableView() {
tableView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(tableView)
view.pinSubviewToAllEdges(tableView)
tableView.refreshControl = refreshControl
}
}
// MARK: - Tableview Datasource
// These methods aren't actually needed as the tableview is controlled by an instance of ImmuTableViewHandler.
// However, ImmuTableViewHandler requires that the owner of the tableview is a data source and delegate.
extension SiteStatsBaseTableViewController: TableViewContainer, UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return UITableViewCell()
}
}
| gpl-2.0 | 0bb40c187e6f86de2645ce7ffad362de | 30.137255 | 128 | 0.720403 | 5.533101 | false | false | false | false |
zhiquan911/SwiftChatKit | Pod/Classes/viewcontrollers/MediaDisplayViewController.swift | 1 | 8048 | //
// MediaDisplayViewController.swift
// SwiftChatKit
//
// Created by 麦志泉 on 15/10/10.
// Copyright © 2015年 CocoaPods. All rights reserved.
//
import UIKit
import AlamofireImage
import MediaPlayer
public class MediaDisplayViewController: UIViewController {
var imageViewPhoto: UIImageView!
var message: SCMessage!
var progressView: UIActivityIndicatorView!
var moviePlayerController: MPMoviePlayerController!
var buttonClose: UIButton!
func setupUI() {
self.view.backgroundColor = UIColor.blackColor()
if self.imageViewPhoto == nil {
self.imageViewPhoto = UIImageView(frame: self.view.bounds)
self.imageViewPhoto.userInteractionEnabled = true
self.imageViewPhoto.translatesAutoresizingMaskIntoConstraints = false
self.imageViewPhoto.contentMode = UIViewContentMode.ScaleAspectFit
self.imageViewPhoto.clipsToBounds = true
self.imageViewPhoto.hidden = true
self.view.addSubview(self.imageViewPhoto)
}
if self.progressView == nil {
self.progressView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
self.progressView.translatesAutoresizingMaskIntoConstraints = false
self.progressView.hidesWhenStopped = true
self.view.addSubview(self.progressView)
}
if self.moviePlayerController == nil {
self.moviePlayerController = MPMoviePlayerController()
self.moviePlayerController.repeatMode = MPMovieRepeatMode.One
self.moviePlayerController.scalingMode = MPMovieScalingMode.AspectFit
self.moviePlayerController.view.frame = self.view.frame
self.moviePlayerController.view.hidden = true
self.view.addSubview(self.moviePlayerController.view)
}
if self.buttonClose == nil {
self.buttonClose = UIButton(type: UIButtonType.Custom)
self.buttonClose.translatesAutoresizingMaskIntoConstraints = false
self.buttonClose.setImage(UIImage(named: "cancel_White"), forState: UIControlState.Normal)
self.buttonClose.backgroundColor = UIColor(white: 0, alpha: 0.55)
self.buttonClose.addTarget(self, action: "handleCloseButtonPress:", forControlEvents: UIControlEvents.TouchUpInside)
self.buttonClose.layer.cornerRadius = 15
self.buttonClose.layer.masksToBounds = true
self.view.addSubview(self.buttonClose)
}
let views = [
"imageViewPhoto": self.imageViewPhoto,
"progressView": self.progressView,
"buttonClose": self.buttonClose
]
//水平布局
self.view.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"H:|[imageViewPhoto]|",
options: NSLayoutFormatOptions(),
metrics: nil,
views:views))
//垂直布局
self.view.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|[imageViewPhoto]|",
options: NSLayoutFormatOptions(),
metrics: nil,
views:views))
//水平布局
self.view.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"H:|[progressView]|",
options: NSLayoutFormatOptions(),
metrics: nil,
views:views))
//垂直布局
self.view.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|[progressView]|",
options: NSLayoutFormatOptions(),
metrics: nil,
views:views))
//水平布局
self.view.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"H:[buttonClose(30)]-15-|",
options: NSLayoutFormatOptions(),
metrics: nil,
views:views))
//垂直布局
self.view.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-20-[buttonClose(30)]",
options: NSLayoutFormatOptions(),
metrics: nil,
views:views))
// //水平布局
// self.view.addConstraints(
// NSLayoutConstraint.constraintsWithVisualFormat(
// "H:|[moviePlayerController]|",
// options: NSLayoutFormatOptions(),
// metrics: nil,
// views:views))
//
// //垂直布局
// self.view.addConstraints(
// NSLayoutConstraint.constraintsWithVisualFormat(
// "V:|[moviePlayerController]|",
// options: NSLayoutFormatOptions(),
// metrics: nil,
// views:views))
//图片添加点击事件
let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "singleTapGestureRecognizerHandle:")
self.imageViewPhoto.addGestureRecognizer(tapGestureRecognizer)
}
override public func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
self.loadMedia()
}
deinit {
if self.message.messageMediaType == SCMessageMediaType.Video {
self.moviePlayerController.stop()
}
}
/**
加载图片
*/
func loadMedia () {
switch message.messageMediaType! {
case SCMessageMediaType.Photo:
self.imageViewPhoto.hidden = false
self.moviePlayerController.view.hidden = true
if message.photo != nil {
self.imageViewPhoto.image = message.photo
} else {
let filter = AspectScaledToFitSizeWithRoundedCornersFilter(
size: self.view.bounds.size,
radius: 0.0
)
self.imageViewPhoto.af_setImageWithURL(NSURL(string: message.originPhotoUrl)!, placeholderImage: SCMessageTableViewCell.kDefaultImage, filter: filter)
}
case SCMessageMediaType.Video:
self.imageViewPhoto.hidden = true
self.moviePlayerController.view.hidden = false
if message.videoPath.isEmpty {
self.moviePlayerController.contentURL = NSURL(string: message.videoUrl)
} else {
self.moviePlayerController.contentURL = SCConstants.videoFileFolder.URLByAppendingPathComponent(message.videoPath)
}
self.moviePlayerController.play()
default:break
}
}
/**
点击关闭按钮
- parameter sender:
*/
func handleCloseButtonPress(sender: AnyObject?) {
self.dismissViewControllerAnimated(true, completion: nil)
}
/**
点击事件
- parameter tapGestureRecognizer:
*/
func singleTapGestureRecognizerHandle(tapGestureRecognizer: UITapGestureRecognizer) {
if tapGestureRecognizer.state == UIGestureRecognizerState.Ended {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
override public func prefersStatusBarHidden() -> Bool {
return true
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
//增加一个图片加载完后的过滤
public struct AspectScaledToFitSizeWithRoundedCornersFilter: CompositeImageFilter {
public init(size: CGSize, radius: CGFloat, divideRadiusByImageScale: Bool = false) {
self.filters = [
AspectScaledToFitSizeFilter(size: size),
RoundedCornersFilter(radius: radius, divideRadiusByImageScale: divideRadiusByImageScale)
]
}
/// The image filters to apply to the image in sequential order.
public let filters: [ImageFilter]
}
| mit | b309622ce31684f7592e2cd64928c593 | 34.290179 | 166 | 0.61265 | 5.82535 | false | false | false | false |
khoren93/SwiftHub | SwiftHub/Extensions/UIView/UIView+Borders.swift | 1 | 4169 | //
// UIView+Borders.swift
// SwiftHub
//
// Created by Khoren Markosyan on 1/4/17.
// Copyright © 2017 Khoren Markosyan. All rights reserved.
//
import UIKit
import Foundation
// MARK: - Create your borders and assign them to a property on a view when you can via the create methods when possible. Otherwise you might end up with multiple borders being created.
extension UIView {
enum BorderSide {
case left, top, right, bottom
}
func defaultBorderColor() -> UIColor {
return UIColor.separator()
}
func defaultBorderDepth() -> CGFloat {
return Configs.BaseDimensions.borderWidth
}
/// Add Border for side with default params
///
/// - Parameter side: Border Side
/// - Returns: Border view
@discardableResult
func addBorder(for side: BorderSide) -> UIView {
return addBorder(for: side, color: defaultBorderColor(), depth: defaultBorderDepth())
}
/// Add Bottom Border with default params
///
/// - Parameters:
/// - leftInset: left inset
/// - rightInset: right inset
/// - Returns: Border view
@discardableResult
func addBottomBorder(leftInset: CGFloat = 10, rightInset: CGFloat = 0) -> UIView {
let border = UIView()
border.backgroundColor = defaultBorderColor()
self.addSubview(border)
border.snp.makeConstraints { (make) in
make.left.equalToSuperview().inset(leftInset)
make.right.equalToSuperview().inset(rightInset)
make.bottom.equalToSuperview()
make.height.equalTo(self.defaultBorderDepth())
}
return border
}
/// Add Top Border for side with color, depth, length and offsets
///
/// - Parameters:
/// - side: Border Side
/// - color: Border Color
/// - depth: Border Depth
/// - length: Border Length
/// - inset: Border Inset
/// - cornersInset: Border Corners Inset
/// - Returns: Border view
@discardableResult
func addBorder(for side: BorderSide, color: UIColor, depth: CGFloat, length: CGFloat = 0.0, inset: CGFloat = 0.0, cornersInset: CGFloat = 0.0) -> UIView {
let border = UIView()
border.backgroundColor = color
self.addSubview(border)
border.snp.makeConstraints { (make) in
switch side {
case .left:
if length != 0.0 {
make.height.equalTo(length)
make.centerY.equalToSuperview()
} else {
make.top.equalToSuperview().inset(cornersInset)
make.bottom.equalToSuperview().inset(cornersInset)
}
make.left.equalToSuperview().inset(inset)
make.width.equalTo(depth)
case .top:
if length != 0.0 {
make.width.equalTo(length)
make.centerX.equalToSuperview()
} else {
make.left.equalToSuperview().inset(cornersInset)
make.right.equalToSuperview().inset(cornersInset)
}
make.top.equalToSuperview().inset(inset)
make.height.equalTo(depth)
case .right:
if length != 0.0 {
make.height.equalTo(length)
make.centerY.equalToSuperview()
} else {
make.top.equalToSuperview().inset(cornersInset)
make.bottom.equalToSuperview().inset(cornersInset)
}
make.right.equalToSuperview().inset(inset)
make.width.equalTo(depth)
case .bottom:
if length != 0.0 {
make.width.equalTo(length)
make.centerX.equalToSuperview()
} else {
make.left.equalToSuperview().inset(cornersInset)
make.right.equalToSuperview().inset(cornersInset)
}
make.bottom.equalToSuperview().inset(inset)
make.height.equalTo(depth)
}
}
return border
}
}
| mit | e02a2b33f939120938d78807c55936e9 | 34.623932 | 185 | 0.56166 | 4.915094 | false | false | false | false |
mbuchetics/DataSource | DataSource/SectionDescriptor.swift | 1 | 7756 | //
// SectionDescriptor.swift
// DataSource
//
// Created by Matthias Buchetics on 15/03/2017.
// Copyright © 2017 aaa - all about apps GmbH. All rights reserved.
//
import UIKit
public enum HeaderFooter {
case none
case title(String)
case view(UIView)
}
public enum SectionHeight {
case value(_: CGFloat)
case automatic
case zero
func floatValue(for style: UITableView.Style) -> CGFloat {
switch self {
case .value(let value):
return value
case .automatic:
return UITableView.automaticDimension
case .zero:
return style == .plain ? 0.0 : CGFloat.leastNormalMagnitude
}
}
}
// MARK - SectionDescriptorType
public protocol SectionDescriptorType {
var identifier: String { get }
var isHiddenClosure: ((SectionType, Int) -> Bool)? { get }
// UITableViewDelegate
var headerClosure: ((SectionType, Int) -> HeaderFooter)? { get }
var footerClosure: ((SectionType, Int) -> HeaderFooter)? { get }
var headerHeightClosure: ((SectionType, Int) -> SectionHeight)? { get }
var footerHeightClosure: ((SectionType, Int) -> SectionHeight)? { get }
var willDisplayHeaderClosure: ((SectionType, UIView, Int) -> Void)? { get }
var willDisplayFooterClosure: ((SectionType, UIView, Int) -> Void)? { get }
}
// MARK - SectionDescriptor
public class SectionDescriptor<HeaderFooterContent>: SectionDescriptorType {
public let identifier: String
public init(_ identifier: String? = nil) {
if let identifier = identifier {
self.identifier = identifier
} else if HeaderFooterContent.self != Void.self {
self.identifier = String(describing: HeaderFooterContent.self)
} else {
self.identifier = ""
}
}
// MARK: Typed Getters
private func typedContent(_ section: SectionType) -> HeaderFooterContent {
guard let content = section.content as? HeaderFooterContent else {
fatalError("[DataSource] could not cast to expected section content type \(HeaderFooterContent.self)")
}
return content
}
// MARK: - UITableViewDelegate
// MARK: isHidden
public private(set) var isHiddenClosure: ((SectionType, Int) -> Bool)?
public func isHidden(_ closure: @escaping (HeaderFooterContent, Int) -> Bool) -> SectionDescriptor {
isHiddenClosure = { (section, index) in
closure(self.typedContent(section), index)
}
return self
}
public func isHidden(_ closure: @escaping () -> Bool) -> SectionDescriptor {
isHiddenClosure = { (_, _) in
closure()
}
return self
}
// MARK: header
public private(set) var headerClosure: ((SectionType, Int) -> HeaderFooter)?
public func header(_ closure: @escaping (HeaderFooterContent, Int) -> HeaderFooter) -> SectionDescriptor {
headerClosure = { [unowned self] (section, index) in
closure(self.typedContent(section), index)
}
return self
}
public func header(_ closure: @escaping () -> HeaderFooter) -> SectionDescriptor {
headerClosure = { (_, _) in
closure()
}
return self
}
// MARK: footer
public private(set) var footerClosure: ((SectionType, Int) -> HeaderFooter)?
public func footer(_ closure: @escaping (HeaderFooterContent, Int) -> HeaderFooter) -> SectionDescriptor {
footerClosure = { [unowned self] (section, index) in
closure(self.typedContent(section), index)
}
return self
}
public func footer(_ closure: @escaping () -> HeaderFooter) -> SectionDescriptor {
footerClosure = { (_, _) in
closure()
}
return self
}
// MARK: headerHeight
public private(set) var headerHeightClosure: ((SectionType, Int) -> SectionHeight)?
public func headerHeight(_ closure: @escaping (HeaderFooterContent, Int) -> SectionHeight) -> SectionDescriptor {
headerHeightClosure = { [unowned self](section, index) in
closure(self.typedContent(section), index)
}
return self
}
public func headerHeight(_ closure: @escaping () -> SectionHeight) -> SectionDescriptor {
headerHeightClosure = { (_, _) in
closure()
}
return self
}
// MARK: footerHeight
public private(set) var footerHeightClosure: ((SectionType, Int) -> SectionHeight)?
public func footerHeight(_ closure: @escaping (HeaderFooterContent, Int) -> SectionHeight) -> SectionDescriptor {
footerHeightClosure = { [unowned self] (section, index) in
closure(self.typedContent(section), index)
}
return self
}
public func footerHeight(_ closure: @escaping () -> SectionHeight) -> SectionDescriptor {
footerHeightClosure = { (_, _) in
closure()
}
return self
}
// MARK: willDisplayHeader
public private(set) var willDisplayHeaderClosure: ((SectionType, UIView, Int) -> Void)?
public func willDisplayHeader(_ closure: @escaping (HeaderFooterContent, UIView, Int) -> Void) -> SectionDescriptorType {
willDisplayHeaderClosure = { [unowned self] (section, view, index) in
closure(self.typedContent(section), view, index)
}
return self
}
public func willDisplayHeader(_ closure: @escaping () -> Void) -> SectionDescriptor {
willDisplayHeaderClosure = { (_, _, _) in
closure()
}
return self
}
// MARK: willDisplayFooter
public private(set) var willDisplayFooterClosure: ((SectionType, UIView, Int) -> Void)?
public func willDisplayFooter(_ closure: @escaping (HeaderFooterContent, UIView, Int) -> Void) -> SectionDescriptorType {
willDisplayFooterClosure = { [unowned self] (section, view, index) in
closure(self.typedContent(section), view, index)
}
return self
}
public func willDisplayFooter(_ closure: @escaping () -> Void) -> SectionDescriptor {
willDisplayFooterClosure = { (_, _, _) in
closure()
}
return self
}
// MARK: didEndDisplayingHeader
public private(set) var didEndDisplayingHeaderClosure: ((SectionType, UIView, Int) -> Void)?
public func didEndDisplayingHeader(_ closure: @escaping (HeaderFooterContent, UIView, Int) -> Void) -> SectionDescriptorType {
didEndDisplayingHeaderClosure = { [unowned self] (section, view, index) in
closure(self.typedContent(section), view, index)
}
return self
}
public func didEndDisplayingHeader(_ closure: @escaping () -> Void) -> SectionDescriptor {
didEndDisplayingHeaderClosure = { (_, _, _) in
closure()
}
return self
}
// MARK: didEndDisplayingFooter
public private(set) var didEndDisplayingFooterClosure: ((SectionType, UIView, Int) -> Void)?
public func didEndDisplayingFooter(_ closure: @escaping (HeaderFooterContent, UIView, Int) -> Void) -> SectionDescriptorType {
didEndDisplayingFooterClosure = { [unowned self] (section, view, index) in
closure(self.typedContent(section), view, index)
}
return self
}
public func didEndDisplayingFooter(_ closure: @escaping () -> Void) -> SectionDescriptor {
didEndDisplayingFooterClosure = { (_, _, _) in
closure()
}
return self
}
}
| mit | 163d4b28062544589849d7830c30a22b | 30.782787 | 130 | 0.609413 | 5.019417 | false | false | false | false |
m-nakada/Dropi | Dropi/ImageResizer.swift | 1 | 1456 | //
// ImageResizer.swift
// Dropi
//
// Created by m-nakada on 12/13/14.
// Copyright (c) 2014 mna. All rights reserved.
//
import Cocoa
struct ImageResizer {
var inputScale: Float
var inputAspectRatio: Float
var url: NSURL
var fileType: NSBitmapImageFileType? {
guard let pathExtension = url.pathExtension else { return nil }
switch (pathExtension.lowercaseString) {
case "png":
return .NSPNGFileType
case "jpg", "jpeg":
return .NSJPEGFileType
case "tif", "tiff":
return .NSTIFFFileType
default:
return .NSPNGFileType
}
}
init(inputScale: Float = 0.5, inputAspectRatio: Float = 1.0, url: NSURL) {
self.inputScale = inputScale
self.inputAspectRatio = inputAspectRatio
self.url = url
}
func resize() -> (CIImage?, NSBitmapImageFileType?) {
guard let image = CIImage(contentsOfURL: url) else { return (nil, nil) }
// Create resize filter
guard let filter = CIFilter(name: "CILanczosScaleTransform") else { return (nil, nil) }
filter.setValue(image, forKey: "inputImage")
filter.setValue(self.inputScale, forKey: "inputScale")
filter.setValue(self.inputAspectRatio, forKey: "inputAspectRatio")
// Get output image
guard let outputImage = filter.valueForKey("outputImage") as? CIImage else { return (nil, nil) }
guard let fileType = fileType else { return (outputImage, nil) }
return (outputImage, fileType)
}
}
| mit | 71dc978a92bc2e4b345893d008d3da3d | 28.12 | 100 | 0.673764 | 3.903485 | false | false | false | false |
milseman/swift | test/decl/protocol/req/associated_type_default.swift | 24 | 739 | // RUN: %target-typecheck-verify-swift
struct X { }
// Simple default definition for associated types.
protocol P1 {
associatedtype AssocType1 = Int
}
extension X : P1 { }
var i: X.AssocType1 = 17
// Dependent default definition for associated types
protocol P2 {
associatedtype AssocType2 = Self
}
extension X : P2 { }
var xAssoc2: X.AssocType2 = X()
// Dependent default definition for associated types that doesn't meet
// requirements.
protocol P3 {
associatedtype AssocType3 : P1 = Self // expected-note{{default type 'X2' for associated type 'AssocType3' (from protocol 'P3') does not conform to 'P1'}}
}
extension X : P3 { } // okay
struct X2 : P3 { } // expected-error{{type 'X2' does not conform to protocol 'P3'}}
| apache-2.0 | dc18fa5ecbed32f5b58298d5e049eadb | 23.633333 | 156 | 0.709066 | 3.50237 | false | false | false | false |
Karumi/Alamofire-Result | Tests/RequestTests.swift | 1 | 24183 | // RequestTests.swift
//
// Copyright (c) 2014-2015 Alamofire Software Foundation (http://alamofire.org)
//
// 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 Alamofire
import Foundation
import XCTest
import Result
class RequestInitializationTestCase: BaseTestCase {
func testRequestClassMethodWithMethodAndURL() {
// Given
let URLString = "https://httpbin.org/"
// When
let request = Alamofire.request(.GET, URLString)
// Then
XCTAssertNotNil(request.request, "request URL request should not be nil")
XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should match expected value")
XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
XCTAssertNil(request.response, "request response should be nil")
}
func testRequestClassMethodWithMethodAndURLAndParameters() {
// Given
let URLString = "https://httpbin.org/get"
// When
let request = Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
// Then
XCTAssertNotNil(request.request, "request URL request should not be nil")
XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should match expected value")
XCTAssertNotEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
XCTAssertEqual(request.request?.URL?.query ?? "", "foo=bar", "query is incorrect")
XCTAssertNil(request.response, "request response should be nil")
}
func testRequestClassMethodWithMethodURLParametersAndHeaders() {
// Given
let URLString = "https://httpbin.org/get"
let headers = ["Authorization": "123456"]
// When
let request = Alamofire.request(.GET, URLString, parameters: ["foo": "bar"], headers: headers)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should match expected value")
XCTAssertNotEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
XCTAssertEqual(request.request?.URL?.query ?? "", "foo=bar", "query is incorrect")
let authorizationHeader = request.request?.valueForHTTPHeaderField("Authorization") ?? ""
XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
XCTAssertNil(request.response, "response should be nil")
}
}
// MARK: -
class RequestResponseTestCase: BaseTestCase {
func testRequestResponse() {
// Given
let URLString = "https://httpbin.org/get"
let expectation = expectationWithDescription("GET request should succeed: \(URLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: NSData?
var error: NSError?
// When
Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
}
func testRequestResponseWithProgress() {
// Given
let randomBytes = 4 * 1024 * 1024
let URLString = "https://httpbin.org/bytes/\(randomBytes)"
let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var responseRequest: NSURLRequest?
var responseResponse: NSHTTPURLResponse?
var responseData: NSData?
var responseError: ErrorType?
// When
let request = Alamofire.request(.GET, URLString)
request.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
byteValues.append(bytes)
let progress = (
completedUnitCount: request.progress.completedUnitCount,
totalUnitCount: request.progress.totalUnitCount
)
progressValues.append(progress)
}
request.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response response should not be nil")
XCTAssertNotNil(responseData, "response data should not be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(
byteValue.totalBytes,
progressValue.completedUnitCount,
"total bytes should be equal to completed unit count"
)
XCTAssertEqual(
byteValue.totalBytesExpected,
progressValue.totalUnitCount,
"total bytes expected should be equal to total unit count"
)
}
}
if let
lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
}
func testRequestResponseWithStream() {
// Given
let randomBytes = 4 * 1024 * 1024
let URLString = "https://httpbin.org/bytes/\(randomBytes)"
let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var accumulatedData = [NSData]()
var responseRequest: NSURLRequest?
var responseResponse: NSHTTPURLResponse?
var responseData: NSData?
var responseError: ErrorType?
// When
let request = Alamofire.request(.GET, URLString)
request.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
byteValues.append(bytes)
let progress = (
completedUnitCount: request.progress.completedUnitCount,
totalUnitCount: request.progress.totalUnitCount
)
progressValues.append(progress)
}
request.stream { accumulatedData.append($0) }
request.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response response should not be nil")
XCTAssertNil(responseData, "response data should be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertGreaterThanOrEqual(accumulatedData.count, 1, "accumulated data should have one or more parts")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(
byteValue.totalBytes,
progressValue.completedUnitCount,
"total bytes should be equal to completed unit count"
)
XCTAssertEqual(
byteValue.totalBytesExpected,
progressValue.totalUnitCount,
"total bytes expected should be equal to total unit count"
)
}
}
if let
lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(
progressValueFractionalCompletion,
1.0,
"progress value fractional completion should equal 1.0"
)
XCTAssertEqual(
accumulatedData.reduce(Int64(0)) { $0 + $1.length },
lastByteValue.totalBytes,
"accumulated data length should match byte count"
)
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
}
func testPOSTRequestWithUnicodeParameters() {
// Given
let URLString = "https://httpbin.org/post"
let parameters = [
"french": "français",
"japanese": "日本語",
"arabic": "العربية",
"emoji": "😃"
]
let expectation = expectationWithDescription("request should succeed")
var response: Response<AnyObject, NSError>?
// When
Alamofire.request(.POST, URLString, parameters: parameters)
.responseJSON { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
if let response = response {
XCTAssertNotNil(response.request, "request should not be nil")
XCTAssertNotNil(response.response, "response should not be nil")
XCTAssertNotNil(response.data, "data should not be nil")
if let
JSON = response.result.value as? [String: AnyObject],
form = JSON["form"] as? [String: String]
{
XCTAssertEqual(form["french"], parameters["french"], "french parameter value should match form value")
XCTAssertEqual(form["japanese"], parameters["japanese"], "japanese parameter value should match form value")
XCTAssertEqual(form["arabic"], parameters["arabic"], "arabic parameter value should match form value")
XCTAssertEqual(form["emoji"], parameters["emoji"], "emoji parameter value should match form value")
} else {
XCTFail("form parameter in JSON should not be nil")
}
} else {
XCTFail("response should not be nil")
}
}
func testPOSTRequestWithBase64EncodedImages() {
// Given
let URLString = "https://httpbin.org/post"
let pngBase64EncodedString: String = {
let URL = URLForResource("unicorn", withExtension: "png")
let data = NSData(contentsOfURL: URL)!
return data.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
}()
let jpegBase64EncodedString: String = {
let URL = URLForResource("rainbow", withExtension: "jpg")
let data = NSData(contentsOfURL: URL)!
return data.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
}()
let parameters = [
"email": "[email protected]",
"png_image": pngBase64EncodedString,
"jpeg_image": jpegBase64EncodedString
]
let expectation = expectationWithDescription("request should succeed")
var response: Response<AnyObject, NSError>?
// When
Alamofire.request(.POST, URLString, parameters: parameters)
.responseJSON { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
if let response = response {
XCTAssertNotNil(response.request, "request should not be nil")
XCTAssertNotNil(response.response, "response should not be nil")
XCTAssertNotNil(response.data, "data should not be nil")
XCTAssertTrue(response.result.isSuccess, "result should be success")
if let
JSON = response.result.value as? [String: AnyObject],
form = JSON["form"] as? [String: String]
{
XCTAssertEqual(form["email"], parameters["email"], "email parameter value should match form value")
XCTAssertEqual(form["png_image"], parameters["png_image"], "png_image parameter value should match form value")
XCTAssertEqual(form["jpeg_image"], parameters["jpeg_image"], "jpeg_image parameter value should match form value")
} else {
XCTFail("form parameter in JSON should not be nil")
}
} else {
XCTFail("response should not be nil")
}
}
}
// MARK: -
extension Request {
private func preValidate(operation: Void -> Void) -> Self {
delegate.queue.addOperationWithBlock {
operation()
}
return self
}
private func postValidate(operation: Void -> Void) -> Self {
delegate.queue.addOperationWithBlock {
operation()
}
return self
}
}
// MARK: -
class RequestExtensionTestCase: BaseTestCase {
func testThatRequestExtensionHasAccessToTaskDelegateQueue() {
// Given
let URLString = "https://httpbin.org/get"
let expectation = expectationWithDescription("GET request should succeed: \(URLString)")
var responses: [String] = []
// When
Alamofire.request(.GET, URLString)
.preValidate {
responses.append("preValidate")
}
.validate()
.postValidate {
responses.append("postValidate")
}
.response { _, _, _, _ in
responses.append("response")
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
if responses.count == 3 {
XCTAssertEqual(responses[0], "preValidate", "response at index 0 should be preValidate")
XCTAssertEqual(responses[1], "postValidate", "response at index 1 should be postValidate")
XCTAssertEqual(responses[2], "response", "response at index 2 should be response")
} else {
XCTFail("responses count should be equal to 3")
}
}
}
// MARK: -
class RequestDescriptionTestCase: BaseTestCase {
func testRequestDescription() {
// Given
let URLString = "https://httpbin.org/get"
let request = Alamofire.request(.GET, URLString)
let initialRequestDescription = request.description
let expectation = expectationWithDescription("Request description should update: \(URLString)")
var finalRequestDescription: String?
var response: NSHTTPURLResponse?
// When
request.response { _, responseResponse, _, _ in
finalRequestDescription = request.description
response = responseResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertEqual(initialRequestDescription, "GET https://httpbin.org/get", "incorrect request description")
XCTAssertEqual(
finalRequestDescription ?? "",
"GET https://httpbin.org/get (\(response?.statusCode ?? -1))",
"incorrect request description"
)
}
}
// MARK: -
class RequestDebugDescriptionTestCase: BaseTestCase {
// MARK: Properties
let manager: Manager = {
let manager = Manager(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
manager.startRequestsImmediately = false
return manager
}()
let managerDisallowingCookies: Manager = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPShouldSetCookies = false
let manager = Manager(configuration: configuration)
manager.startRequestsImmediately = false
return manager
}()
// MARK: Tests
func testGETRequestDebugDescription() {
// Given
let URLString = "https://httpbin.org/get"
// When
let request = manager.request(.GET, URLString)
let components = cURLCommandComponents(request)
// Then
XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
XCTAssertFalse(components.contains("-X"), "command should not contain explicit -X flag")
XCTAssertEqual(components.last ?? "", "\"\(URLString)\"", "URL component should be equal")
}
func testPOSTRequestDebugDescription() {
// Given
let URLString = "https://httpbin.org/post"
// When
let request = manager.request(.POST, URLString)
let components = cURLCommandComponents(request)
// Then
XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
XCTAssertEqual(components[3..<5], ["-X", "POST"], "command should contain explicit -X flag")
XCTAssertEqual(components.last ?? "", "\"\(URLString)\"", "URL component should be equal")
}
func testPOSTRequestWithJSONParametersDebugDescription() {
// Given
let URLString = "https://httpbin.org/post"
// When
let request = manager.request(.POST, URLString, parameters: ["foo": "bar"], encoding: .JSON)
let components = cURLCommandComponents(request)
// Then
XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
XCTAssertEqual(components[3..<5], ["-X", "POST"], "command should contain explicit -X flag")
XCTAssertTrue(
request.debugDescription.rangeOfString("-H \"Content-Type: application/json\"") != nil,
"command should contain 'application/json' Content-Type"
)
XCTAssertTrue(
request.debugDescription.rangeOfString("-d \"{\\\"foo\\\":\\\"bar\\\"}\"") != nil,
"command data should contain JSON encoded parameters"
)
XCTAssertEqual(components.last ?? "", "\"\(URLString)\"", "URL component should be equal")
}
func testPOSTRequestWithCookieDebugDescription() {
// Given
let URLString = "https://httpbin.org/post"
let properties = [
NSHTTPCookieDomain: "httpbin.org",
NSHTTPCookiePath: "/post",
NSHTTPCookieName: "foo",
NSHTTPCookieValue: "bar",
]
let cookie = NSHTTPCookie(properties: properties)!
manager.session.configuration.HTTPCookieStorage?.setCookie(cookie)
// When
let request = manager.request(.POST, URLString)
let components = cURLCommandComponents(request)
// Then
XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal")
XCTAssertEqual(components[3..<5], ["-X", "POST"], "command should contain explicit -X flag")
XCTAssertEqual(components.last ?? "", "\"\(URLString)\"", "URL component should be equal")
XCTAssertEqual(components[5..<6], ["-b"], "command should contain -b flag")
}
func testPOSTRequestWithCookiesDisabledDebugDescription() {
// Given
let URLString = "https://httpbin.org/post"
let properties = [
NSHTTPCookieDomain: "httpbin.org",
NSHTTPCookiePath: "/post",
NSHTTPCookieName: "foo",
NSHTTPCookieValue: "bar",
]
let cookie = NSHTTPCookie(properties: properties)!
managerDisallowingCookies.session.configuration.HTTPCookieStorage?.setCookie(cookie)
// When
let request = managerDisallowingCookies.request(.POST, URLString)
let components = cURLCommandComponents(request)
// Then
let cookieComponents = components.filter { $0 == "-b" }
XCTAssertTrue(cookieComponents.isEmpty, "command should not contain -b flag")
}
func testThatRequestWithInvalidURLDebugDescription() {
// Given
let URLString = "invalid_url"
// When
let request = manager.request(.GET, URLString)
let debugDescription = request.debugDescription
// Then
XCTAssertNotNil(debugDescription, "debugDescription should not crash")
}
// MARK: Test Helper Methods
private func cURLCommandComponents(request: Request) -> [String] {
let whitespaceCharacterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()
return request.debugDescription.componentsSeparatedByCharactersInSet(whitespaceCharacterSet)
.filter { $0 != "" && $0 != "\\" }
}
}
| mit | a3dade29fd9ca1e1e3e00e99fe0f2641 | 38.10356 | 130 | 0.6301 | 5.542661 | false | false | false | false |
fluidsonic/JetPack | Sources/UI/Label.swift | 1 | 7184 | import UIKit
open class Label: View {
private lazy var delegateProxy: DelegateProxy = DelegateProxy(label: self)
private let linkTapRecognizer = UITapGestureRecognizer()
open var linkTapped: ((URL) -> Void)?
public override init() {
super.init()
isOpaque = false
layer.contentsScale = gridScaleFactor
setUpLinkTapRecognizer()
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open var additionalLinkHitZone: UIEdgeInsets {
get { return labelLayer.additionalLinkHitZone }
set { labelLayer.additionalLinkHitZone = newValue }
}
open var attributedText: NSAttributedString {
get { return labelLayer.attributedText }
set {
guard newValue != labelLayer.attributedText else {
return
}
labelLayer.attributedText = newValue
invalidateIntrinsicContentSize()
}
}
open override func didMoveToWindow() {
super.didMoveToWindow()
if window != nil {
layer.contentsScale = gridScaleFactor
}
else {
layer.removeAllAnimations()
}
}
open var font: UIFont {
get { return labelLayer.font }
set {
guard newValue != labelLayer.font else {
return
}
labelLayer.font = newValue
invalidateIntrinsicContentSize()
}
}
@objc
private func handleLinkTapRecognizer() {
guard let link = link(at: linkTapRecognizer.location(in: self)) else {
return
}
linkTapped?(link)
}
open var horizontalAlignment: TextAlignment.Horizontal {
get { return labelLayer.horizontalAlignment }
set { labelLayer.horizontalAlignment = newValue }
}
@available(*, deprecated, renamed: "letterSpacing")
open var kerning: TextLetterSpacing? {
get { return letterSpacing }
set { letterSpacing = newValue }
}
private var labelLayer: LabelLayer {
return layer as! LabelLayer
}
public final override class var layerClass: AnyObject.Type {
return LabelLayer.self
}
open var letterSpacing: TextLetterSpacing? {
get { return labelLayer.letterSpacing }
set {
guard newValue != labelLayer.letterSpacing else {
return
}
labelLayer.letterSpacing = letterSpacing
invalidateIntrinsicContentSize()
}
}
open var lineBreakMode: NSLineBreakMode {
get { return labelLayer.lineBreakMode }
set {
guard newValue != labelLayer.lineBreakMode else {
return
}
labelLayer.lineBreakMode = newValue
invalidateIntrinsicContentSize()
}
}
open var lineHeight: TextLineHeight {
get { return labelLayer.lineHeight }
set {
guard newValue != labelLayer.lineHeight else {
return
}
labelLayer.lineHeight = newValue
invalidateIntrinsicContentSize()
}
}
public func link(at point: CGPoint) -> URL? {
return labelLayer.link(at: layer.convert(point, to: labelLayer))?.url
}
open var maximumLineHeight: CGFloat? {
get { return labelLayer.maximumLineHeight }
set {
guard newValue != labelLayer.maximumLineHeight else {
return
}
labelLayer.maximumLineHeight = newValue
invalidateIntrinsicContentSize()
}
}
open var maximumNumberOfLines: Int? {
get { return labelLayer.maximumNumberOfLines }
set {
guard newValue != labelLayer.maximumNumberOfLines else {
return
}
labelLayer.maximumNumberOfLines = newValue
invalidateIntrinsicContentSize()
}
}
open override func measureOptimalSize(forAvailableSize availableSize: CGSize) -> CGSize {
guard availableSize.isPositive else {
return .zero
}
return labelLayer.size(thatFits: availableSize)
}
open var minimumLineHeight: CGFloat? {
get { return labelLayer.minimumLineHeight }
set {
guard newValue != labelLayer.minimumLineHeight else {
return
}
labelLayer.minimumLineHeight = newValue
invalidateIntrinsicContentSize()
}
}
open var minimumScaleFactor: CGFloat {
get { return labelLayer.minimumScaleFactor }
set {
guard newValue != labelLayer.minimumScaleFactor else {
return
}
labelLayer.minimumScaleFactor = newValue
invalidateIntrinsicContentSize()
}
}
open var numberOfLines: Int {
return labelLayer.numberOfLines
}
open var padding: UIEdgeInsets {
get { return labelLayer.padding }
set {
guard newValue != labelLayer.padding else {
return
}
labelLayer.padding = newValue
invalidateIntrinsicContentSize()
}
}
open var paragraphSpacing: CGFloat {
get { return labelLayer.paragraphSpacing }
set {
guard newValue != labelLayer.paragraphSpacing else {
return
}
labelLayer.paragraphSpacing = newValue
invalidateIntrinsicContentSize()
}
}
open override func pointInside(_ point: CGPoint, withEvent event: UIEvent?, additionalHitZone: UIEdgeInsets) -> Bool {
let isInsideLabel = super.pointInside(point, withEvent: event, additionalHitZone: additionalHitZone)
guard isInsideLabel || labelLayer.contains(layer.convert(point, to: labelLayer)) else {
return false
}
guard userInteractionLimitedToLinks else {
return isInsideLabel
}
return link(at: point) != nil
}
public func rect(forLine line: Int, in referenceView: UIView) -> CGRect {
return labelLayer.rect(forLine: line, in: referenceView.layer)
}
private func setUpLinkTapRecognizer() {
let recognizer = linkTapRecognizer
recognizer.delegate = delegateProxy
recognizer.addTarget(self, action: #selector(handleLinkTapRecognizer))
addGestureRecognizer(recognizer)
}
open override func shouldAnimateProperty(_ property: String) -> Bool {
if super.shouldAnimateProperty(property) {
return true
}
switch property {
case "actualTextColor", "actualTintColor":
return true
default:
return false
}
}
open var text: String {
get { return attributedText.string }
set { attributedText = NSAttributedString(string: newValue) }
}
open var textColor: UIColor {
get { return labelLayer.normalTextColor }
set { labelLayer.normalTextColor = newValue }
}
public var textColorDimsWithTint: Bool {
get { return labelLayer.textColorDimsWithTint }
set { labelLayer.textColorDimsWithTint = newValue }
}
open var textTransform: TextTransform? {
get { return labelLayer.textTransform }
set {
guard newValue != labelLayer.textTransform else {
return
}
labelLayer.textTransform = newValue
invalidateIntrinsicContentSize()
}
}
public var treatsLineFeedAsParagraphSeparator: Bool {
get { return labelLayer.treatsLineFeedAsParagraphSeparator }
set { labelLayer.treatsLineFeedAsParagraphSeparator = newValue }
}
open override func tintColorDidChange() {
super.tintColorDidChange()
labelLayer.updateTintColor(tintColor, adjustmentMode: tintAdjustmentMode)
}
open var userInteractionLimitedToLinks = true
open var verticalAlignment: TextAlignment.Vertical {
get { return labelLayer.verticalAlignment }
set { labelLayer.verticalAlignment = newValue }
}
private final class DelegateProxy: NSObject, UIGestureRecognizerDelegate {
private unowned var label: Label
init(label: Label) {
self.label = label
}
@objc
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return label.link(at: touch.location(in: label)) != nil
}
}
}
| mit | 0c89a6b540dc95d6025586aae6fc26f8 | 18.736264 | 119 | 0.72912 | 4.181607 | false | false | false | false |
kinetic-fit/sensors-swift-trainers | Sources/SwiftySensorsTrainers/WahooAdvancedFitnessMachineSerializer.swift | 1 | 7749 | //
// WahooAdvancedFitnessMachineSerializer.swift
// SwiftySensorsTrainers iOS
//
// Created by Josh Levine on 5/9/18.
// Copyright © 2018 Kinetic. All rights reserved.
//
import Foundation
func decodeTilt(lsb: UInt8, msb: UInt8) -> Double {
let unsignedValue = UInt16(msb) << 8 | UInt16(lsb)
let signedValue = Int16(bitPattern: unsignedValue)
return Double(signedValue) / 100
}
open class WahooAdvancedFitnessMachineSerializer {
public enum OpCode: UInt8 {
case getHubHeight = 1
case setHubHeight = 2
case getWheelBase = 3
case setWheelBase = 4
case getTargetTilt = 101
case setTargetTilt = 102
case getTiltMode = 103
case getCurrentTilt = 104
case getTiltLimits = 105
case eventPacket = 253 // Not a command op code - used in event packets to indicate the packet is an event
case responsePacket = 254 // Not a command op code - used in response packets to indicate the packet is a response
}
public enum ResponseCode: UInt8 {
case success = 1
case opCodeNotSupported = 2
case invalidParameter = 3
case operationFailed = 4
case deviceNotAvailable = 5
}
public enum EventCode: UInt8 {
case hubHeightChanged = 1
case wheelBaseChanged = 2
case targetTiltChanged = 50
case tiltModechanged = 51
case currentTiltChanged = 52
case tiltLimitsChanged = 53
case tiltLimitsAvailable = 54
}
public enum TiltMode: UInt8 {
case unlocked = 0
case locked = 1
case unknown = 255 // Unknown/invalid (tilt feature not available)
}
public struct CommandPacket {
public let opCode: OpCode
public let message: [UInt8]
public var bytes: [UInt8] { return [opCode.rawValue] + message }
public var data: Data { return Data(bytes) }
}
public struct ResponsePacket {
public let opCode: OpCode
public let responseCode: ResponseCode
public let bytes: [UInt8]
public static func parse(packet: [UInt8]) -> ResponsePacket? {
if packet.count < 3 || packet[0] != OpCode.responsePacket.rawValue {
return nil
}
guard let opCode = OpCode.init(rawValue: packet[1]), let responseCode = ResponseCode.init(rawValue: packet[2]) else {
return nil
}
let bytes = Array(packet.dropFirst(3))
return ResponsePacket(opCode: opCode, responseCode: responseCode, bytes: bytes)
}
public var hubHeight: UInt16? {
if [OpCode.getHubHeight, .setHubHeight].contains(opCode) && bytes.count >= 2 {
return UInt16(bytes[1]) << 8 | UInt16(bytes[0])
}
return nil
}
public var wheelBase: UInt16? {
if [OpCode.getWheelBase, .setWheelBase].contains(opCode) && bytes.count >= 2 {
return UInt16(bytes[1]) << 8 | UInt16(bytes[0])
}
return nil
}
public var targetTilt: Double? {
if [OpCode.getTargetTilt, .setTargetTilt].contains(opCode) && bytes.count >= 2 {
return Double(UInt16(bytes[1]) << 8 | UInt16(bytes[0])) / 100
}
return nil
}
public var tiltMode: TiltMode? {
if opCode == .getTiltMode && bytes.count >= 1 {
return TiltMode.init(rawValue: bytes[0])
}
return nil
}
public var currentTilt: Double? {
if opCode == .getCurrentTilt && bytes.count >= 1 {
return Double(UInt16(bytes[1]) << 8 | UInt16(bytes[0])) / 100
}
return nil
}
}
public struct EventPacket {
public let eventCode: EventCode
public let bytes: [UInt8]
public static func parse(packet: [UInt8]) -> EventPacket? {
if packet.count < 2 || packet[0] != OpCode.eventPacket.rawValue {
return nil
}
guard let eventCode = EventCode.init(rawValue: packet[1]) else {
return nil
}
let bytes = Array(packet.dropFirst(2))
return EventPacket(eventCode: eventCode, bytes: bytes)
}
public var hubHeight: UInt16? {
if eventCode == .hubHeightChanged && bytes.count >= 2 {
return UInt16(bytes[1]) << 8 | UInt16(bytes[0])
}
return nil
}
public var wheelBase: UInt16? {
if eventCode == .wheelBaseChanged && bytes.count >= 2 {
return UInt16(bytes[1]) << 8 | UInt16(bytes[0])
}
return nil
}
public var targetTilt: Double? {
if eventCode == .targetTiltChanged && bytes.count >= 2 {
return decodeTilt(lsb: bytes[0], msb: bytes[1])
}
return nil
}
public var tiltMode: TiltMode? {
if eventCode == .tiltModechanged && bytes.count >= 1 {
return TiltMode.init(rawValue: bytes[0])
}
return nil
}
public var currentTilt: Double? {
if eventCode == .currentTiltChanged && bytes.count >= 2 {
return decodeTilt(lsb: bytes[0], msb: bytes[1])
}
return nil
}
public var minimumTilt: Double? {
if [EventCode.tiltLimitsAvailable, .tiltLimitsChanged].contains(eventCode) && bytes.count >= 2 {
return decodeTilt(lsb: bytes[0], msb: bytes[1])
}
return nil
}
public var maximumTilt: Double? {
if [EventCode.tiltLimitsAvailable, .tiltLimitsChanged].contains(eventCode) && bytes.count >= 4 {
return decodeTilt(lsb: bytes[0], msb: bytes[1])
}
return nil
}
}
public static func getHubHeight() -> CommandPacket {
return CommandPacket(opCode: .getHubHeight, message: [])
}
public static func setHubHeight(millimeters: UInt16) -> CommandPacket {
let data = [
UInt8(millimeters & 0xFF),
UInt8(millimeters >> 8 & 0xFF)
]
return CommandPacket(opCode: .setHubHeight, message: data)
}
public static func getWheelBase() -> CommandPacket {
return CommandPacket(opCode: .getWheelBase, message: [])
}
public static func setWheelBase(millimeters: UInt16) -> CommandPacket {
let data = [
UInt8(millimeters & 0xFF),
UInt8(millimeters >> 8 & 0xFF)
]
return CommandPacket(opCode: .setWheelBase, message: data)
}
public static func getTargetTilt() -> CommandPacket {
return CommandPacket(opCode: .getTargetTilt, message: [])
}
public static func setTargetTilt(grade: Double) -> CommandPacket {
let targetTilt = UInt16(bitPattern: Int16(grade * 100))
let data = [
UInt8(targetTilt & 0xFF),
UInt8(targetTilt >> 8 & 0xFF)
]
return CommandPacket(opCode: .setTargetTilt, message: data)
}
public static func getTiltMode() -> CommandPacket {
return CommandPacket(opCode: .getTiltMode, message: [])
}
public static func getCurrentTilt() -> CommandPacket {
return CommandPacket(opCode: .getCurrentTilt, message: [])
}
public static func getTiltLimits() -> CommandPacket {
return CommandPacket(opCode: .getTiltLimits, message: [])
}
}
| mit | 35f113ebe7f9a83809c11404cdd3783a | 32.686957 | 129 | 0.559757 | 4.465706 | false | false | false | false |
myhgew/CodePractice | iOS/SwiftAssignment/Assignment2/Calculator/Calculator/CalculatorBrain.swift | 1 | 3490 | //
// CalculatorBrain.swift
// Calculator
//
// Created by yuhumai on 3/26/15.
// Copyright (c) 2015 yuhumai. All rights reserved.
//
import Foundation
class CalculatorBrain {
private enum Op: Printable {
case Operand(Double)
case UnaryOperation(String, Double -> Double)
case BinaryOperation(String, (Double, Double) -> Double)
var description: String {
get {
switch self {
case .Operand(let operand):
return "\(operand)"
case .UnaryOperation(let symbol, _):
return symbol
case .BinaryOperation(let symbol, _):
return symbol
}
}
}
}
private var opStack = [Op]()
private var knownOps = [String: Op]()
init() {
func learnOp(op: Op) {
knownOps[op.description] = op
}
learnOp(Op.BinaryOperation("×", *))
knownOps["÷"] = Op.BinaryOperation("÷") { $1 / $0 }
knownOps["+"] = Op.BinaryOperation("+", +)
knownOps["−"] = Op.BinaryOperation("−") { $1 - $0 }
knownOps["√"] = Op.UnaryOperation("√", sqrt)
}
typealias PropertyList = AnyObject
var program: PropertyList { // guaranteed to be a ProperyList
get {
return opStack.map { $0.description }
}
set {
if let opSymbols = newValue as? Array<String> {
var newOpStack = [Op]()
for opSymbol in opSymbols {
if let op = knownOps[opSymbol] {
newOpStack.append(op)
} else if let operand = NSNumberFormatter().numberFromString(opSymbol)?.doubleValue {
newOpStack.append(.Operand(operand))
}
}
opStack = newOpStack
}
}
}
private func evaluate(ops: [Op]) -> (result: Double?, remainingOps: [Op]) {
if !ops.isEmpty {
var remainingOps = ops
let op = remainingOps.removeLast()
switch op {
case .Operand(let operand):
return (operand, remainingOps)
case .UnaryOperation(_, let operation):
let operandEvaluation = evaluate(remainingOps)
if let operand = operandEvaluation.result {
return (operation(operand), operandEvaluation.remainingOps)
}
case .BinaryOperation(_, let operation):
let op1Evaluation = evaluate(remainingOps)
if let operand1 = op1Evaluation.result {
let op2Evaluation = evaluate(op1Evaluation.remainingOps)
if let operand2 = op2Evaluation.result {
return (operation(operand1, operand2), op2Evaluation.remainingOps)
}
}
}
}
return (nil, ops)
}
func evaluate() -> Double? {
let (result, remainder) = evaluate(opStack)
println("\(opStack) = \(result) with \(remainder) left over")
return result;
}
func pushOperand(operand: Double) -> Double? {
opStack.append(Op.Operand(operand))
return evaluate()
}
func performOperation(symbol: String) -> Double? {
if let operation = knownOps[symbol] {
opStack.append(operation)
}
return evaluate()
}
} | mit | cb27f9affbe3216b83876fb3ec23425f | 30.071429 | 105 | 0.516528 | 4.838665 | false | false | false | false |
adamahrens/braintweak | BrainTweak/BrainTweak/ViewControllers/GameViewController.swift | 1 | 3868 | //
// GameViewController.swift
// BrainTweak
//
// Created by Adam Ahrens on 2/20/15.
// Copyright (c) 2015 Appsbyahrens. All rights reserved.
//
import UIKit
class GameViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var correctButton: UIButton!
@IBOutlet weak var incorrectButton: UIButton!
@IBOutlet weak var tableViewBottomSpace: NSLayoutConstraint!
var gameBrain: GameBrain?
var scoreKeeper: ScoreKeeper?
var currentMathProblem = 0
var answeredQuestions = Dictionary<Int, String>()
override func viewDidLoad() {
super.viewDidLoad()
title = "Game"
// Setup the ScoreKeeper
scoreKeeper = ScoreKeeper(maxScore: Double(gameBrain!.size()))
}
//MARK: UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return gameBrain!.size()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MathCell", forIndexPath: indexPath) as! MathCell
cell.mathProblem.text = gameBrain!.mathProblemDisplay(indexPath.row)
if (answeredQuestions[indexPath.row] != nil) {
if (answeredQuestions[indexPath.row] == "true") {
let greenColor = UIColor(red: 4.0/255.0, green: 175.0/255.0, blue: 77.0/255.0, alpha: 1.0)
cell.backgroundColor = greenColor
cell.contentView.backgroundColor = greenColor
cell.mathProblem.backgroundColor = greenColor
} else {
let redColor = UIColor(red: 255.0/255.0, green: 61.0/255.0, blue: 50.0/255.0, alpha: 1.0)
cell.backgroundColor = redColor
cell.contentView.backgroundColor = redColor
cell.mathProblem.backgroundColor = redColor
}
}
return cell
}
//MARK: IBActions
@IBAction func wrongPressed(sender: UIButton) {
userAnsweredQuestionWith(false)
}
@IBAction func submitPressed(sender: UIButton) {
userAnsweredQuestionWith(true)
}
private func userAnsweredQuestionWith(answer: Bool) {
var usersAnswerIsCorrect = "false"
if gameBrain!.isMathProblemCorrect(currentMathProblem) == answer {
scoreKeeper!.answeredCorrectly()
usersAnswerIsCorrect = "true"
}
// Update score
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: scoreKeeper!.scoreDisplay(), style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
answeredQuestions[currentMathProblem] = usersAnswerIsCorrect
currentMathProblem += 1
tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: currentMathProblem - 1, inSection: 0)], withRowAnimation: .Automatic)
// Answered all the questions. Remove the buttons
if currentMathProblem == gameBrain!.size() {
disableButtons()
}
// Scroll the answered problem off screen so the User can
// focus on the next
if currentMathProblem != gameBrain!.size() {
tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: currentMathProblem, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: true)
}
}
private func disableButtons() {
correctButton.enabled = false
incorrectButton.enabled = false
UIView.animateWithDuration(0.35, animations: {
self.tableViewBottomSpace.constant = 0
self.correctButton.hidden = true
self.incorrectButton.hidden = true
self.view.layoutIfNeeded()
})
}
}
| mit | b036417287c3b278eeb0f1f70884fc10 | 36.192308 | 164 | 0.645036 | 4.96534 | false | false | false | false |
zapdroid/RXWeather | Pods/RxSwift/RxSwift/Observables/Implementations/Catch.swift | 1 | 4282 | //
// Catch.swift
// RxSwift
//
// Created by Krunoslav Zaher on 4/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
// catch with callback
final class CatchSinkProxy<O: ObserverType>: ObserverType {
typealias E = O.E
typealias Parent = CatchSink<O>
private let _parent: Parent
init(parent: Parent) {
_parent = parent
}
func on(_ event: Event<E>) {
_parent.forwardOn(event)
switch event {
case .next:
break
case .error, .completed:
_parent.dispose()
}
}
}
final class CatchSink<O: ObserverType>: Sink<O>, ObserverType {
typealias E = O.E
typealias Parent = Catch<E>
private let _parent: Parent
private let _subscription = SerialDisposable()
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let d1 = SingleAssignmentDisposable()
_subscription.disposable = d1
d1.setDisposable(_parent._source.subscribe(self))
return _subscription
}
func on(_ event: Event<E>) {
switch event {
case .next:
forwardOn(event)
case .completed:
forwardOn(event)
dispose()
case let .error(error):
do {
let catchSequence = try _parent._handler(error)
let observer = CatchSinkProxy(parent: self)
_subscription.disposable = catchSequence.subscribe(observer)
} catch let e {
forwardOn(.error(e))
dispose()
}
}
}
}
final class Catch<Element>: Producer<Element> {
typealias Handler = (Swift.Error) throws -> Observable<Element>
fileprivate let _source: Observable<Element>
fileprivate let _handler: Handler
init(source: Observable<Element>, handler: @escaping Handler) {
_source = source
_handler = handler
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = CatchSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
// catch enumerable
final class CatchSequenceSink<S: Sequence, O: ObserverType>
: TailRecursiveSink<S, O>
, ObserverType where S.Iterator.Element: ObservableConvertibleType, S.Iterator.Element.E == O.E {
typealias Element = O.E
typealias Parent = CatchSequence<S>
private var _lastError: Swift.Error?
override init(observer: O, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
switch event {
case .next:
forwardOn(event)
case let .error(error):
_lastError = error
schedule(.moveNext)
case .completed:
forwardOn(event)
dispose()
}
}
override func subscribeToNext(_ source: Observable<E>) -> Disposable {
return source.subscribe(self)
}
override func done() {
if let lastError = _lastError {
forwardOn(.error(lastError))
} else {
forwardOn(.completed)
}
dispose()
}
override func extract(_ observable: Observable<Element>) -> SequenceGenerator? {
if let onError = observable as? CatchSequence<S> {
return (onError.sources.makeIterator(), nil)
} else {
return nil
}
}
}
final class CatchSequence<S: Sequence>: Producer<S.Iterator.Element.E> where S.Iterator.Element: ObservableConvertibleType {
typealias Element = S.Iterator.Element.E
let sources: S
init(sources: S) {
self.sources = sources
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = CatchSequenceSink<S, O>(observer: observer, cancel: cancel)
let subscription = sink.run((sources.makeIterator(), nil))
return (sink: sink, subscription: subscription)
}
}
| mit | d60d59015ac086cd76b8ee657d96bb59 | 26.267516 | 144 | 0.602897 | 4.445483 | false | false | false | false |
apple/swift-driver | Sources/SwiftDriver/ExplicitModuleBuilds/InterModuleDependencies/InterModuleDependencyGraph.swift | 1 | 10439 | //===--------------- InterModuleDependencyGraph.swift ---------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import class Foundation.JSONEncoder
/// A map from a module identifier to its info
public typealias ModuleInfoMap = [ModuleDependencyId: ModuleInfo]
public enum ModuleDependencyId: Hashable {
case swift(String)
case swiftPlaceholder(String)
case swiftPrebuiltExternal(String)
case clang(String)
public var moduleName: String {
switch self {
case .swift(let name): return name
case .swiftPlaceholder(let name): return name
case .swiftPrebuiltExternal(let name): return name
case .clang(let name): return name
}
}
}
extension ModuleDependencyId: Codable {
enum CodingKeys: CodingKey {
case swift
case swiftPlaceholder
case swiftPrebuiltExternal
case clang
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
do {
let moduleName = try container.decode(String.self, forKey: .swift)
self = .swift(moduleName)
} catch {
do {
let moduleName = try container.decode(String.self, forKey: .swiftPlaceholder)
self = .swiftPlaceholder(moduleName)
} catch {
do {
let moduleName = try container.decode(String.self, forKey: .swiftPrebuiltExternal)
self = .swiftPrebuiltExternal(moduleName)
} catch {
let moduleName = try container.decode(String.self, forKey: .clang)
self = .clang(moduleName)
}
}
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .swift(let moduleName):
try container.encode(moduleName, forKey: .swift)
case .swiftPlaceholder(let moduleName):
try container.encode(moduleName, forKey: .swiftPlaceholder)
case .swiftPrebuiltExternal(let moduleName):
try container.encode(moduleName, forKey: .swiftPrebuiltExternal)
case .clang(let moduleName):
try container.encode(moduleName, forKey: .clang)
}
}
}
/// Bridging header
public struct BridgingHeader: Codable {
var path: TextualVirtualPath
var sourceFiles: [TextualVirtualPath]
var moduleDependencies: [String]
}
/// Details specific to Swift modules.
public struct SwiftModuleDetails: Codable {
/// The module interface from which this module was built, if any.
public var moduleInterfacePath: TextualVirtualPath?
/// The paths of potentially ready-to-use compiled modules for the interface.
public var compiledModuleCandidates: [TextualVirtualPath]?
/// The bridging header, if any.
public var bridgingHeaderPath: TextualVirtualPath?
/// The source files referenced by the bridging header.
public var bridgingSourceFiles: [TextualVirtualPath]? = []
/// Options to the compile command
public var commandLine: [String]? = []
/// The context hash for this module that encodes the producing interface's path,
/// target triple, etc. This field is optional because it is absent for the ModuleInfo
/// corresponding to the main module being built.
public var contextHash: String?
/// To build a PCM to be used by this Swift module, we need to append these
/// arguments to the generic PCM build arguments reported from the dependency
/// graph.
public var extraPcmArgs: [String]
/// A flag to indicate whether or not this module is a framework.
public var isFramework: Bool?
}
/// Details specific to Swift placeholder dependencies.
public struct SwiftPlaceholderModuleDetails: Codable {
/// The path to the .swiftModuleDoc file.
var moduleDocPath: TextualVirtualPath?
/// The path to the .swiftSourceInfo file.
var moduleSourceInfoPath: TextualVirtualPath?
}
/// Details specific to Swift externally-pre-built modules.
public struct SwiftPrebuiltExternalModuleDetails: Codable {
/// The path to the already-compiled module that must be used instead of
/// generating a job to build this module.
public var compiledModulePath: TextualVirtualPath
/// The path to the .swiftModuleDoc file.
public var moduleDocPath: TextualVirtualPath?
/// The path to the .swiftSourceInfo file.
public var moduleSourceInfoPath: TextualVirtualPath?
/// A flag to indicate whether or not this module is a framework.
public var isFramework: Bool?
public init(compiledModulePath: TextualVirtualPath,
moduleDocPath: TextualVirtualPath? = nil,
moduleSourceInfoPath: TextualVirtualPath? = nil,
isFramework: Bool = false) throws {
self.compiledModulePath = compiledModulePath
self.moduleDocPath = moduleDocPath
self.moduleSourceInfoPath = moduleSourceInfoPath
self.isFramework = isFramework
}
}
/// Details specific to Clang modules.
public struct ClangModuleDetails: Codable {
/// The path to the module map used to build this module.
public var moduleMapPath: TextualVirtualPath
/// clang-generated context hash
public var contextHash: String
/// Options to the compile command
public var commandLine: [String] = []
/// Set of PCM Arguments of depending modules which
/// are covered by the directDependencies info of this module
public var capturedPCMArgs: Set<[String]>?
public init(moduleMapPath: TextualVirtualPath,
contextHash: String,
commandLine: [String],
capturedPCMArgs: Set<[String]>?) {
self.moduleMapPath = moduleMapPath
self.contextHash = contextHash
self.commandLine = commandLine
self.capturedPCMArgs = capturedPCMArgs
}
}
public struct ModuleInfo: Codable {
/// The path for the module.
public var modulePath: TextualVirtualPath
/// The source files used to build this module.
public var sourceFiles: [String]?
/// The set of direct module dependencies of this module.
public var directDependencies: [ModuleDependencyId]?
/// Specific details of a particular kind of module.
public var details: Details
/// Specific details of a particular kind of module.
public enum Details {
/// Swift modules may be built from a module interface, and may have
/// a bridging header.
case swift(SwiftModuleDetails)
/// Swift placeholder modules carry additional details that specify their
/// module doc path and source info paths.
case swiftPlaceholder(SwiftPlaceholderModuleDetails)
/// Swift externally-prebuilt modules must communicate the path to pre-built binary artifacts
case swiftPrebuiltExternal(SwiftPrebuiltExternalModuleDetails)
/// Clang modules are built from a module map file.
case clang(ClangModuleDetails)
}
public init(modulePath: TextualVirtualPath,
sourceFiles: [String]?,
directDependencies: [ModuleDependencyId]?,
details: Details) {
self.modulePath = modulePath
self.sourceFiles = sourceFiles
self.directDependencies = directDependencies
self.details = details
}
}
extension ModuleInfo.Details: Codable {
enum CodingKeys: CodingKey {
case swift
case swiftPlaceholder
case swiftPrebuiltExternal
case clang
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
do {
let details = try container.decode(SwiftModuleDetails.self, forKey: .swift)
self = .swift(details)
} catch {
do {
let details = try container.decode(SwiftPlaceholderModuleDetails.self,
forKey: .swiftPlaceholder)
self = .swiftPlaceholder(details)
} catch {
do {
let details = try container.decode(SwiftPrebuiltExternalModuleDetails.self,
forKey: .swiftPrebuiltExternal)
self = .swiftPrebuiltExternal(details)
} catch {
let details = try container.decode(ClangModuleDetails.self, forKey: .clang)
self = .clang(details)
}
}
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .swift(let details):
try container.encode(details, forKey: .swift)
case .swiftPlaceholder(let details):
try container.encode(details, forKey: .swiftPlaceholder)
case .swiftPrebuiltExternal(let details):
try container.encode(details, forKey: .swiftPrebuiltExternal)
case .clang(let details):
try container.encode(details, forKey: .clang)
}
}
}
/// Describes the complete set of dependencies for a Swift module, including
/// all of the Swift and C modules and source files it depends on.
public struct InterModuleDependencyGraph: Codable {
/// The name of the main module.
public var mainModuleName: String
/// The complete set of modules discovered
public var modules: ModuleInfoMap = [:]
/// Information about the main module.
public var mainModule: ModuleInfo { modules[.swift(mainModuleName)]! }
}
internal extension InterModuleDependencyGraph {
func toJSONString() throws -> String {
let encoder = JSONEncoder()
#if os(Linux) || os(Android)
encoder.outputFormatting = [.prettyPrinted]
#else
if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) {
encoder.outputFormatting = [.prettyPrinted, .withoutEscapingSlashes]
}
#endif
let data = try encoder.encode(self)
return String(data: data, encoding: .utf8)!
}
}
public struct InterModuleDependencyImports: Codable {
public var imports: [String]
public init(imports: [String], moduleAliases: [String: String]? = nil) {
var realImports = [String]()
if let aliases = moduleAliases {
for elem in imports {
if let realName = aliases[elem] {
realImports.append(realName)
} else {
realImports.append(elem)
}
}
}
if !realImports.isEmpty {
self.imports = realImports
} else {
self.imports = imports
}
}
}
| apache-2.0 | 1ca19079a3d1e57701ba73dc93ca25c9 | 32.351438 | 97 | 0.692691 | 4.647818 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureApp/Sources/FeatureAppUI/CoreReducer+Wallet.swift | 1 | 6156 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import Combine
import ComposableArchitecture
import DIKit
import ERC20Kit
import FeatureAppDomain
import FeatureAuthenticationDomain
import FeatureAuthenticationUI
import FeatureSettingsDomain
import Localization
import PlatformKit
import PlatformUIKit
import RemoteNotificationsKit
import ToolKit
import UIKit
import WalletPayloadKit
/// Used for canceling publishers
enum WalletCancelations {
struct FetchId: Hashable {}
struct DecryptId: Hashable {}
struct AuthenticationId: Hashable {}
struct InitializationId: Hashable {}
struct UpgradeId: Hashable {}
struct CreateId: Hashable {}
struct RestoreId: Hashable {}
struct RestoreFailedId: Hashable {}
struct AssetInitializationId: Hashable {}
struct SecondPasswordId: Hashable {}
struct ForegroundInitCheckId: Hashable {}
}
public enum WalletAction: Equatable {
case fetch(password: String)
case walletFetched(Result<WalletFetchedContext, WalletError>)
case walletBootstrap(WalletFetchedContext)
case walletSetup
}
extension Reducer where State == CoreAppState, Action == CoreAppAction, Environment == CoreAppEnvironment {
/// Returns a combined reducer that handles all the wallet related actions
func walletReducer() -> Self {
combined(
with: Reducer { state, action, environment in
switch action {
case .wallet(.fetch(let password)):
return environment.walletService.fetch(password)
.receive(on: environment.mainQueue)
.catchToEffect()
.cancellable(id: WalletCancelations.FetchId(), cancelInFlight: true)
.map { CoreAppAction.wallet(.walletFetched($0)) }
case .wallet(.walletFetched(.success(let context))):
// the cancellations are here because we still call the legacy actions
// and we need to cancel those operation - (remove after JS removal)
return .concatenate(
.cancel(id: WalletCancelations.FetchId()),
.cancel(id: WalletCancelations.AuthenticationId()),
.cancel(id: WalletCancelations.DecryptId()),
Effect(value: .wallet(.walletBootstrap(context))),
Effect(value: .wallet(.walletSetup))
)
case .wallet(.walletBootstrap(let context)):
// set `guid/sharedKey` (need to refactor this after JS removal)
environment.blockchainSettings.set(guid: context.guid)
environment.blockchainSettings.set(sharedKey: context.sharedKey)
// `passwordPartHash` is set after Pin creation
clearPinIfNeeded(
for: context.passwordPartHash,
appSettings: environment.blockchainSettings
)
return .merge(
// reset KYC verification if decrypted wallet under recovery context
Effect(value: .resetVerificationStatusIfNeeded(
guid: context.guid,
sharedKey: context.sharedKey
))
)
case .wallet(.walletSetup):
// decide if we need to reset password or not (we need to reset password after metadata recovery)
// if needed, go to reset password screen, if not, go to PIN screen
if let context = state.onboarding?.walletRecoveryContext,
context == .metadataRecovery
{
environment.loadingViewPresenter.hide()
return Effect(value: .onboarding(.handleMetadataRecoveryAfterAuthentication))
}
// decide if we need to set a pin or not
guard environment.blockchainSettings.isPinSet else {
guard state.onboarding?.welcomeState != nil else {
return Effect(value: .setupPin)
}
return .merge(
Effect(value: .onboarding(.welcomeScreen(.dismiss()))),
Effect(value: .setupPin)
)
}
return Effect(value: .prepareForLoggedIn)
case .wallet(.walletFetched(.failure(.initialization(.needsSecondPassword)))):
// we don't support double encrypted password wallets
environment.loadingViewPresenter.hide()
return Effect(
value: .onboarding(.informSecondPasswordDetected)
)
case .wallet(.walletFetched(.failure(let error))):
// hide loader if any
environment.loadingViewPresenter.hide()
// show alert
let buttons: CoreAlertAction.Buttons = .init(
primary: .default(
TextState(verbatim: LocalizationConstants.ErrorAlert.button),
action: .send(.alert(.dismiss))
),
secondary: nil
)
let alertAction = CoreAlertAction.show(
title: LocalizationConstants.Errors.error,
message: error.errorDescription ?? LocalizationConstants.Errors.genericError,
buttons: buttons
)
return .merge(
Effect(value: .alert(alertAction)),
.cancel(id: WalletCancelations.FetchId()),
Effect(value: .onboarding(.handleWalletDecryptionError))
)
default:
return .none
}
}
)
}
}
| lgpl-3.0 | 589a57fab10f757780c3cb94e2c1088a | 43.280576 | 117 | 0.550284 | 6.112214 | false | false | false | false |
Yoloabdo/CS-193P | SmashTag/SmashTag/TweetDetailsTableViewController.swift | 1 | 8902 | //
// TweetDetailsTableViewController.swift
// SmashTag
//
// Created by abdelrahman mohamed on 3/5/16.
// Copyright © 2016 Abdulrhman dev. All rights reserved.
//
import UIKit
class TweetDetailsTableViewController: UITableViewController {
var tweet: Tweet?{
didSet{
title = tweet?.user.screenName
if let media = tweet?.media where media.count > 0 {
tableDetails.append(tweetStruct(title: "Media",
data: [tweetItem.media(media)]))
noMedia = false
}
if let urls = tweet?.urls where urls.count > 0 {
tableDetails.append(tweetStruct(title: "URLs",
data: urls.map { tweetItem.Keyword($0.keyword) }))
}
if let hashtags = tweet?.hashtags where hashtags.count > 0{
tableDetails.append(tweetStruct(title: "Hashtags",
data: hashtags.map { tweetItem.Keyword($0.keyword) }))
}
if let users = tweet?.userMentions {
//Showing the user who posted the tweet.
var userItems = [tweetItem.Keyword("@" + tweet!.user.screenName)]
if users.count > 0 {
userItems += users.map { tweetItem.Keyword($0.keyword) }
}
tableDetails.append(tweetStruct(title: "Users", data: userItems))
}
}
}
var noMedia = true
var tableDetails:[tweetStruct] = []
var colliModel: [MediaItem]?
enum tweetItem: CustomStringConvertible{
case Keyword(String)
case media([MediaItem])
var description: String {
switch self {
case .Keyword(let keyword): return keyword
case .media(_): return "Media"
}
}
}
struct tweetStruct: CustomStringConvertible {
var title: String
var data: [tweetItem]
var description: String { return "\(title): \(data)" }
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return tableDetails.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 && !noMedia{
return 180
}
return 44
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return tableDetails[section].data.count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return tableDetails[section].title
}
struct StoryBoard {
static let KeywordCellReuseIdentifier = "textCell"
static let imageCellReuseIdentifier = "imageCell"
static let collictionReuseCellIdentfier = "collictionCell"
static let zoomedImageIdentfier = "imageViewZoomed"
static let searchAgainIdentfier = "SearchTag"
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let rowDetail = tableDetails[indexPath.section].data[indexPath.row]
switch rowDetail {
case .Keyword(let keyWord):
let cell = tableView.dequeueReusableCellWithIdentifier(
StoryBoard.KeywordCellReuseIdentifier,
forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = keyWord
return cell
case .media(let med):
let cell = tableView.dequeueReusableCellWithIdentifier(
StoryBoard.collictionReuseCellIdentfier,
forIndexPath: indexPath) as! collictionCell
colliModel = med
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
return cell
}
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
guard let tableViewCell = cell as? collictionCell else { return }
tableViewCell.setCollectionViewDataSourceDelegate(self, forRow: indexPath.row)
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let cell = tableView.cellForRowAtIndexPath(indexPath){
guard let label = cell.textLabel?.text else {return }
if label.hasPrefix("http") {
UIApplication.sharedApplication().openURL(NSURL(string: label)!)
}else {
performSegueWithIdentifier(StoryBoard.searchAgainIdentfier, sender: cell)
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identfier = segue.identifier {
switch identfier {
case StoryBoard.zoomedImageIdentfier:
let sender = sender as? MediaCollectionViewCell
let ivc = segue.destinationViewController as! ImageViewController
ivc.image = sender!.imageView?.image
case StoryBoard.searchAgainIdentfier:
if let ttvc = segue.destinationViewController as? TweetTableViewController {
let sender = sender as? UITableViewCell
guard let label = sender?.textLabel?.text else{
return
}
ttvc.searchText = label
}
default:
break
}
}
}
}
// MARK: -UICollictionView: extinsion in order to view images in the colliction view cell.
extension TweetDetailsTableViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return colliModel!.count
}
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StoryBoard.imageCellReuseIdentifier,
forIndexPath: indexPath) as! MediaCollectionViewCell
if Reachability.isConnectedToNetwork(){
let request = NSURLRequest(URL: colliModel![indexPath.row].url)
let urlSession = NSURLSession.sharedSession()
cell.dataTask = urlSession.dataTaskWithRequest(request) { (data, response, error) -> Void in
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
if let _ = error {
assertionFailure("error request.")
}
if let data = data {
let image = UIImage(data: data)
if let imageCell = cell.imageView {
imageCell.image = image
cell.loadingImage.stopAnimating()
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
})
}
cell.dataTask?.resume()
}else{
let alert = UIAlertController(title: "Connection failed", message: "check your internet connection", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Try again", style: .Default, handler: { _ in
self.reloadInputViews()
}))
presentViewController(alert, animated: true, completion: nil)
}
return cell
}
func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
if let cell = cell as? MediaCollectionViewCell {
cell.dataTask?.cancel()
cell.dataTask = nil
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
}
} | mit | e47f3edd554f69822de03d5e7a6833a2 | 35.040486 | 151 | 0.585777 | 5.906437 | false | false | false | false |
kosicki123/WWDC | WWDC/DownloadVideosBatch.swift | 5 | 5541 | //
// DownloadVideosBatch.swift
// WWDC
//
// Created by Andreas Neusüß on 11.06.15.
// Copyright (c) 2015 Guilherme Rambo. All rights reserved.
//
import Cocoa
/*private let _SharedVideoStore = VideoStore()
private let _BackgroundSessionIdentifier = "WWDC Video Downloader"
class VideoStore : NSObject, NSURLSessionDownloadDelegate {
private let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(_BackgroundSessionIdentifier)
private var backgroundSession: NSURLSession!
private var downloadTasks: [String : NSURLSessionDownloadTask] = [:]
private let defaults = NSUserDefaults.standardUserDefaults()
class func SharedStore() -> VideoStore
{
return _SharedVideoStore;
}*/
private let _sharedDownloader = DownloadVideosBatch()
class DownloadVideosBatch: NSObject {
var sessions = [Session]()
var currentlyDownloadedSession : String = ""
private var downloadStartedHndl: AnyObject?
private var downloadFinishedHndl: AnyObject?
private var downloadChangedHndl: AnyObject?
private var downloadCancelledHndl: AnyObject?
private var downloadPausedHndl: AnyObject?
private var downloadResumedHndl: AnyObject?
class func SharedDownloader() -> DownloadVideosBatch {
return _sharedDownloader
}
override init() {
super.init()
addNotifications()
}
func startDownloading() {
if self.sessions.count == 0 {
println("ALL VIDEOS DOWNLOADED")
currentlyDownloadedSession = ""
return
}
if let firstSession = sessions.first, let url = firstSession.hd_url {
self.currentlyDownloadedSession = firstSession.title
VideoStore.SharedStore().download(url)
}
}
func addNotifications() {
let nc = NSNotificationCenter.defaultCenter()
self.downloadStartedHndl = nc.addObserverForName(VideoStoreNotificationDownloadStarted, object: nil, queue: NSOperationQueue.mainQueue()) { note in
let url = note.object as! String?
if url != nil {
println("Start downloading session '\(self.currentlyDownloadedSession)'")
}
}
self.downloadFinishedHndl = nc.addObserverForName(VideoStoreNotificationDownloadFinished, object: nil, queue: NSOperationQueue.mainQueue()) { note in
if let object = note.object as? String {
let url = object as String
println("Finished downloading session '\(self.currentlyDownloadedSession)'")
self.sessions.removeAtIndex(0)
_sharedDownloader.startDownloading()
}
}
self.downloadChangedHndl = nc.addObserverForName(VideoStoreNotificationDownloadProgressChanged, object: nil, queue: NSOperationQueue.mainQueue()) { note in
if let info = note.userInfo {
if let object = note.object as? String {
let url = object as String
if let expected = info["totalBytesExpectedToWrite"] as? Int,
let written = info["totalBytesWritten"] as? Int
{
let progress = Double(written) / Double(expected)
println("Downloading \(self.currentlyDownloadedSession): \(progress*100.0)%")
}
}
}
}
self.downloadCancelledHndl = nc.addObserverForName(VideoStoreNotificationDownloadCancelled, object: nil, queue: NSOperationQueue.mainQueue()) { note in
if let object = note.object as? String {
let url = object as String
println("Download of session \(self.currentlyDownloadedSession) was cancelled.")
}
}
self.downloadPausedHndl = nc.addObserverForName(VideoStoreNotificationDownloadPaused, object: nil, queue: NSOperationQueue.mainQueue()) { note in
if let object = note.object as? String {
let url = object as String
println("Download of session \(self.currentlyDownloadedSession) was paused.")
}
}
self.downloadResumedHndl = nc.addObserverForName(VideoStoreNotificationDownloadResumed, object: nil, queue: NSOperationQueue.mainQueue()) { note in
if let object = note.object as? String {
let url = object as String
println("Download of session \(self.currentlyDownloadedSession) was resumed.")
}
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self.downloadStartedHndl!)
NSNotificationCenter.defaultCenter().removeObserver(self.downloadFinishedHndl!)
NSNotificationCenter.defaultCenter().removeObserver(self.downloadChangedHndl!)
NSNotificationCenter.defaultCenter().removeObserver(self.downloadCancelledHndl!)
NSNotificationCenter.defaultCenter().removeObserver(self.downloadPausedHndl!)
NSNotificationCenter.defaultCenter().removeObserver(self.downloadResumedHndl!)
}
}
| bsd-2-clause | fae6290143a9b11c9577316be93dd0d8 | 44.401639 | 171 | 0.607691 | 5.842827 | false | false | false | false |
YifengBai/YuDou | YuDou/YuDou/Classes/Main/View/PageTitleView.swift | 1 | 5804 | //
// PageTitleView.swift
// YuDou
//
// Created by Bemagine on 2017/1/4.
// Copyright © 2017年 bemagine. All rights reserved.
//
import UIKit
protocol PageTitleViewDelegate : class{
func pageTitleView(_ titleView: PageTitleView, selectedIndex index: Int)
}
// MARK: - 定义常量
private let kScrollLineH : CGFloat = 2
private let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85)
private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0)
class PageTitleView: UIView {
/// 标题数组
fileprivate var titles: [String]!
fileprivate lazy var titleLables : [UILabel] = [UILabel]()
/// scrollView
fileprivate lazy var scrollView : UIScrollView = {
let sv = UIScrollView()
sv.showsHorizontalScrollIndicator = false
sv.scrollsToTop = false
sv.bounces = false
return sv
}()
/// 滚动指示条
fileprivate lazy var scrollLine : UIView = {
let view = UIView()
view.backgroundColor = UIColor.orange
return view
}()
/// 当前点击的index
var curSelectedIndex : Int = 0
/// 代理
weak var delegate : PageTitleViewDelegate?
init(frame: CGRect, titles: [String]) {
self.titles = titles
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - 设置UI
extension PageTitleView {
// 设置UI
fileprivate func setupUI() {
// 添加
addSubview(scrollView)
scrollView.frame = bounds
// 添加title对应的label
addTitleLabels()
// 添加line
addScrollLine()
}
/// 添加labels
private func addTitleLabels() {
let labelW : CGFloat = frame.width / CGFloat(titles.count)
let labelH : CGFloat = frame.height
let labelY : CGFloat = 0
for (index, title) in titles.enumerated() {
let labelX = CGFloat(index) * labelW
let label = UILabel(frame: CGRect(x: labelX, y: labelY, width: labelW, height: labelH))
label.text = title
label.tag = index
label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
label.textAlignment = .center
scrollView.addSubview(label)
titleLables.append(label)
// 添加事件
label.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.titleClickAction(_:)))
label.addGestureRecognizer(tapGesture)
}
}
/// 添加底部滚动线
private func addScrollLine() {
guard let label = titleLables.first else {
return
}
label.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
scrollLine.frame = CGRect(x: label.frame.origin.x + label.frame.width * 0.1, y: frame.height - kScrollLineH, width: label.frame.width * 0.8, height: kScrollLineH)
scrollView.addSubview(scrollLine)
}
}
// MARK: - 事件方法
extension PageTitleView {
/// label的点击事件
@objc fileprivate func titleClickAction(_ tapGes : UITapGestureRecognizer) {
// 获取当前label
guard let curLabel = tapGes.view as? UILabel else { return }
// 如果是点击同一个label,直接返回
if curLabel.tag == curSelectedIndex { return }
// 获取之前的label
let previousLabel = titleLables[curSelectedIndex]
// 切换文字颜色
previousLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
curLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
// 保存新的curSelextedIndex
curSelectedIndex = curLabel.tag
// 改变scrollLine位置
UIView.animate(withDuration: 0.3) {
self.scrollLine.frame.origin.x = curLabel.frame.origin.x + curLabel.frame.width * 0.1
}
// 通知代理
delegate?.pageTitleView(self, selectedIndex: curSelectedIndex)
}
}
// MARK: - 对外暴露的方法
extension PageTitleView {
func setTitleWithProgress(_ progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
// 1.取出当前label及目标label
let sourceLabel = titleLables[sourceIndex]
let targetLabel = titleLables[targetIndex]
// 2.处理滑块的逻辑
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveX = moveTotalX * progress
scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX + sourceLabel.frame.width * 0.1
// 3.颜色的渐变(复杂)
// 3.1.取出变化的范围
let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2)
// 3.2.变化sourceLabel
sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress)
// 3.2.变化targetLabel
targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress)
// 4.记录最新的index
curSelectedIndex = targetIndex
}
}
| mit | e1d87c5432f255a032a9fb70ed55ee58 | 28.068421 | 174 | 0.590621 | 4.64508 | false | false | false | false |
JaSpa/swift | stdlib/public/SDK/os/os_log.swift | 1 | 2848 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import os
@_exported import os.log
import _SwiftOSOverlayShims
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public func os_log(
_ message: StaticString,
dso: UnsafeRawPointer? = #dsohandle,
log: OSLog = .default,
type: OSLogType = .default,
_ args: CVarArg...)
{
guard log.isEnabled(type: type) else { return }
let ra = _swift_os_log_return_address()
message.withUTF8Buffer { (buf: UnsafeBufferPointer<UInt8>) in
// Since dladdr is in libc, it is safe to unsafeBitCast
// the cstring argument type.
let str = unsafeBitCast(buf.baseAddress!, to: UnsafePointer<Int8>.self)
withVaList(args) { valist in
_swift_os_log(dso, ra, log, type, str, valist)
}
}
}
extension OSLogType {
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public static let `default` = __OS_LOG_TYPE_DEFAULT
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public static let info = __OS_LOG_TYPE_INFO
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public static let debug = __OS_LOG_TYPE_DEBUG
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public static let error = __OS_LOG_TYPE_ERROR
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public static let fault = __OS_LOG_TYPE_FAULT
}
extension OSLog {
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public static let disabled = _swift_os_log_disabled()
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public static let `default` = _swift_os_log_default()
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public convenience init(subsystem: String, category: String) {
self.init(__subsystem: subsystem, category: category)
}
}
@available(*, unavailable, renamed: "OSLogType.default")
public var OS_LOG_TYPE_DEFAULT: OSLogType {
fatalError()
}
@available(*, unavailable, renamed: "OSLogType.info")
public var OS_LOG_TYPE_INFO: OSLogType {
fatalError()
}
@available(*, unavailable, renamed: "OSLogType.debug")
public var OS_LOG_TYPE_DEBUG: OSLogType {
fatalError()
}
@available(*, unavailable, renamed: "OSLogType.error")
public var OS_LOG_TYPE_ERROR: OSLogType {
fatalError()
}
@available(*, unavailable, renamed: "OSLogType.fault")
public var OS_LOG_TYPE_FAULT: OSLogType {
fatalError()
}
| apache-2.0 | 161d7028084313ef9d474e9609cee43c | 30.296703 | 80 | 0.651334 | 3.46894 | false | false | false | false |
SteveBarnegren/SwiftChess | SwiftChess/SwiftChessTests/Board Raters/BoardRaterCenterDominanceTests.swift | 1 | 2357 | //
// BoardRaterCenterDominanceTests.swift
// Example
//
// Created by Steve Barnegren on 13/12/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import XCTest
@testable import SwiftChess
class BoardRaterCenterDominanceTests: XCTestCase {
var boardRater: BoardRaterCenterDominance!
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
boardRater = BoardRaterCenterDominance(configuration: AIConfiguration(difficulty: .hard))
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testPiecesWithCenterVisibilityResultsInHigherValueThanPiecesWithoutCenterVisibility() {
let centerVisibleBoard = ASCIIBoard(pieces: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - Q" +
"- - - - - - - R" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
let centerVisibleRating = boardRater.ratingFor(board: centerVisibleBoard.board, color: .white)
let centerObstructedBoard = ASCIIBoard(pieces: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - P -" +
"- - - - - - - Q" )
let centerObstructedRating = boardRater.ratingFor(board: centerObstructedBoard.board, color: .white)
XCTAssertGreaterThan(centerVisibleRating, centerObstructedRating)
}
}
| mit | 83c4aace09f28da2febadc2c32b31cff | 44.307692 | 111 | 0.391766 | 5.294382 | false | true | false | false |
wikimedia/apps-ios-wikipedia | Wikipedia/Code/ImageDimmingExampleViewController.swift | 1 | 698 | import UIKit
import WMF
class ImageDimmingExampleViewController: UIViewController {
@IBOutlet weak var exampleImage: UIImageView!
fileprivate var theme = Theme.standard
override func viewDidLoad() {
super.viewDidLoad()
apply(theme: self.theme)
}
}
extension ImageDimmingExampleViewController: Themeable {
public func apply(theme: Theme) {
self.theme = theme
exampleImage.accessibilityIgnoresInvertColors = true
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.paperBackground
exampleImage.alpha = theme.imageOpacity
}
}
| mit | e7bf238856d6c5b47ca373da530578c4 | 22.266667 | 60 | 0.643266 | 5.584 | false | false | false | false |
DMeechan/Rick-and-Morty-Soundboard | Rick and Morty Soundboard/Rick and Morty Soundboard/StyleManager.swift | 1 | 3925 | //
// Style.swift
// Rick and Morty Soundboard
//
// Created by Daniel Meechan on 15/08/2017.
// Copyright © 2017 Rogue Studios. All rights reserved.
//
import Foundation
import ChameleonFramework
typealias Style = StyleManager
struct StyleManager {
// Core colours
static var primaryColor = UIColor()
static var secondaryColor = UIColor()
// Tracks View
static var trackTextColor = UIColor()
static var trackBorderColor = UIColor()
static var trackIconColor = UIColor()
static var trackFont = UIFont()
static var settingsIconColor = UIColor()
// Settings View
static var settingsCellBackgroundColor = UIColor()
static var settingsCellTextColor = UIColor()
static var settingsFont = UIFont()
// Both views
// Tint is used for just overlaying an image; colour is used for actulal background colour
static var wallpaperTintColor = UIColor()
static var wallpaperColor = UIColor()
static func setupTheme() {
setThemeWhite()
// Chameleon.setGlobalThemeUsingPrimaryColor(primaryColor, withSecondaryColor: secondaryColor, andContentStyle: UIContentStyle.contrast)
}
init() {
Style.setupTheme()
}
static func setThemeWhite() {
primaryColor = FlatWhite()
secondaryColor = FlatBlack()
DataManager.shared.settings.updateValue("Snowball White", forKey: "theme")
setTheme()
}
static func setThemeBlue() {
// Meeseek blue: #64C7EE
primaryColor = UIColor(red:0.39, green:0.78, blue:0.93, alpha:1.0)
secondaryColor = UIColor.white
DataManager.shared.settings.updateValue("Meeseek Blue", forKey: "theme")
setTheme()
}
static func setThemeGreen() {
// Pickle Rick:
// - light green: #649923 <- in use
// - dark green: #4D7F1E
// - darker green: #376306
primaryColor = UIColor(red:0.39, green:0.60, blue:0.14, alpha:1.0)
secondaryColor = UIColor.white
// primaryColor = FlatMint()
// secondaryColor = FlatForestGreenDark()
DataManager.shared.settings.updateValue("Pickle Rick Green", forKey: "theme")
setTheme()
}
static func setThemePink() {
// Noob Noob: #DD7290
primaryColor = UIColor(red:0.87, green:0.45, blue:0.56, alpha:1.0)
secondaryColor = UIColor.white
DataManager.shared.settings.updateValue("Noob-Noob Pink", forKey: "theme")
setTheme()
}
static func setThemeOrange() {
// Squanchy: #D6A01F
primaryColor = UIColor(red:0.84, green:0.63, blue:0.12, alpha:1.0)
secondaryColor = UIColor.white
DataManager.shared.settings.updateValue("Squanchy Orange", forKey: "theme")
setTheme()
}
static func setTheme() {
setTheme(primary: primaryColor, secondary: secondaryColor)
}
static let themes = [
"Snowball White", "Meeseek Blue", "Pickle Rick Green", "Noob-Noob Pink", "Squanchy Orange"
]
static func setTheme(colour: String) {
DataManager.shared.settings.updateValue(colour, forKey: "theme")
switch (colour) {
case "Snowball White": setThemeWhite()
case "Meeseek Blue": setThemeBlue()
case "Pickle Rick Green": setThemeGreen()
case "Noob-Noob Pink": setThemePink()
case "Squanchy Orange": setThemeOrange()
default: break
}
}
static func setTheme(primary: UIColor, secondary: UIColor) {
// Tracks View
trackTextColor = primary
trackBorderColor = primary
trackIconColor = primary
settingsIconColor = primary
trackFont = UIFont.systemFont(ofSize: 14, weight: UIFontWeightMedium)
// Settings View
settingsCellBackgroundColor = primary.withAlphaComponent(0.7)
settingsCellTextColor = secondary
settingsFont = UIFont.systemFont(ofSize: 18, weight: UIFontWeightThin)
// Both views
wallpaperTintColor = secondary
wallpaperColor = UIColor.white
}
}
| apache-2.0 | b7de40659ee1545b1883ccaf591a7567 | 23.993631 | 140 | 0.670234 | 4.279171 | false | false | false | false |
wikimedia/apps-ios-wikipedia | Wikipedia/Code/DescriptionWelcomePageViewController.swift | 1 | 9227 | import Foundation
import UIKit
enum DescriptionWelcomePageType {
case intro
case exploration
}
public protocol DescriptionWelcomeNavigationDelegate: class{
func showNextWelcomePage(_ sender: AnyObject)
}
class DescriptionWelcomePageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, DescriptionWelcomeNavigationDelegate, Themeable {
private var theme = Theme.standard
func apply(theme: Theme) {
self.theme = theme
for pageController in pageControllers {
if let pageController = pageController as? Themeable {
pageController.apply(theme: theme)
}
}
guard viewIfLoaded != nil else {
return
}
skipButton.setTitleColor(UIColor(0xA2A9B1), for: .normal)
nextButton.setTitleColor(theme.colors.link, for: .normal)
nextButton.setTitleColor(theme.colors.disabledText, for: .disabled)
nextButton.setTitleColor(theme.colors.link, for: .highlighted)
}
@objc var completionBlock: (() -> Void)?
func showNextWelcomePage(_ sender: AnyObject){
guard let sender = sender as? UIViewController, let index = pageControllers.firstIndex(of: sender), index != pageControllers.count - 1 else {
dismiss(animated: true, completion:completionBlock)
return
}
view.isUserInteractionEnabled = false
let nextIndex = index + 1
let direction:UIPageViewController.NavigationDirection = UIApplication.shared.wmf_isRTL ? .reverse : .forward
let nextVC = pageControllers[nextIndex]
hideButtons(for: nextVC)
setViewControllers([nextVC], direction: direction, animated: true, completion: {(Bool) in
self.view.isUserInteractionEnabled = true
})
}
private func containerControllerForWelcomePageType(_ type: DescriptionWelcomePageType) -> DescriptionWelcomeContainerViewController {
let controller = DescriptionWelcomeContainerViewController.wmf_viewControllerFromDescriptionWelcomeStoryboard()
controller.welcomeNavigationDelegate = self
controller.pageType = type
return controller
}
private lazy var pageControllers: [UIViewController] = {
var controllers:[UIViewController] = []
controllers.append(containerControllerForWelcomePageType(.intro))
controllers.append(containerControllerForWelcomePageType(.exploration))
return controllers
}()
private lazy var pageControl: UIPageControl? = {
return view.wmf_firstSubviewOfType(UIPageControl.self)
}()
let nextButton = UIButton()
let skipButton = UIButton()
let buttonHeight: CGFloat = 40.0
let buttonSidePadding: CGFloat = 10.0
let buttonCenterXOffset: CGFloat = 88.0
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
delegate = self
let direction:UIPageViewController.NavigationDirection = UIApplication.shared.wmf_isRTL ? .forward : .reverse
setViewControllers([pageControllers.first!], direction: direction, animated: true, completion: nil)
configureAndAddNextButton()
configureAndAddSkipButton()
if let scrollView = view.wmf_firstSubviewOfType(UIScrollView.self) {
scrollView.clipsToBounds = false
}
apply(theme: theme)
}
private func configureAndAddNextButton(){
nextButton.translatesAutoresizingMaskIntoConstraints = false
nextButton.addTarget(self, action: #selector(nextButtonTapped), for: .touchUpInside)
nextButton.isUserInteractionEnabled = true
nextButton.setContentCompressionResistancePriority(.required, for: .horizontal)
nextButton.titleLabel?.numberOfLines = 1
nextButton.setTitle(CommonStrings.nextTitle, for: .normal)
view.addSubview(nextButton)
nextButton.heightAnchor.constraint(equalToConstant: buttonHeight).isActive = true
view.addConstraint(NSLayoutConstraint(item: nextButton, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0))
let leading = NSLayoutConstraint(item: nextButton, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: buttonCenterXOffset)
leading.priority = .defaultHigh
let trailing = NSLayoutConstraint(item: nextButton, attribute: .trailing, relatedBy: .lessThanOrEqual, toItem: view, attribute: .trailing, multiplier: 1, constant: buttonSidePadding)
trailing.priority = .required
view.addConstraints([leading, trailing])
}
private func configureAndAddSkipButton(){
skipButton.translatesAutoresizingMaskIntoConstraints = false
skipButton.addTarget(self, action: #selector(skipButtonTapped), for: .touchUpInside)
skipButton.isUserInteractionEnabled = true
skipButton.setContentCompressionResistancePriority(.required, for: .horizontal)
skipButton.titleLabel?.numberOfLines = 1
skipButton.setTitle(CommonStrings.skipTitle, for: .normal)
view.addSubview(skipButton)
skipButton.heightAnchor.constraint(equalToConstant: buttonHeight).isActive = true
view.addConstraint(NSLayoutConstraint(item: skipButton, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0))
let leading = NSLayoutConstraint(item: skipButton, attribute: .leading, relatedBy: .greaterThanOrEqual, toItem: view, attribute: .leading, multiplier: 1, constant: buttonSidePadding)
leading.priority = .required
let trailing = NSLayoutConstraint(item: skipButton, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: -buttonCenterXOffset)
trailing.priority = .defaultHigh
view.addConstraints([leading, trailing])
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
skipButton.titleLabel?.font = UIFont.wmf_font(.semiboldFootnote, compatibleWithTraitCollection: traitCollection)
nextButton.titleLabel?.font = UIFont.wmf_font(.semiboldFootnote, compatibleWithTraitCollection: traitCollection)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let pageControl = pageControl {
pageControl.isUserInteractionEnabled = false
pageControl.pageIndicatorTintColor = theme.colors.pageIndicator
pageControl.currentPageIndicatorTintColor = theme.colors.pageIndicatorCurrent
}
}
@objc func nextButtonTapped(_ sender: UIButton) {
if let currentVC = viewControllers?.first {
showNextWelcomePage(currentVC)
}
}
@objc @IBAction func skipButtonTapped(_ sender: UIButton) {
dismiss(animated: true, completion:completionBlock)
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return pageControllers.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
guard let viewControllers = viewControllers, let currentVC = viewControllers.first, let presentationIndex = pageControllers.firstIndex(of: currentVC) else {
return 0
}
return presentationIndex
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let index = pageControllers.firstIndex(of: viewController) else {
return nil
}
return index >= pageControllers.count - 1 ? nil : pageControllers[index + 1]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let index = pageControllers.firstIndex(of: viewController) else {
return nil
}
return index == 0 ? nil : pageControllers[index - 1]
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool){
if completed {
hideButtons(for: pageControllers[presentationIndex(for: pageViewController)])
}
}
func hideButtons(for vc: UIViewController){
let isLastPage = pageControllers.firstIndex(of: vc) == pageControllers.count - 1
let newAlpha:CGFloat = isLastPage ? 0.0 : 1.0
let alphaChanged = pageControl?.alpha != newAlpha
nextButton.isEnabled = !isLastPage // Gray out the next button when transitioning to last page (per design)
guard alphaChanged else { return }
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveLinear, animations: {
self.nextButton.alpha = newAlpha
self.skipButton.alpha = newAlpha
self.pageControl?.alpha = newAlpha
}, completion: nil)
}
}
| mit | fcdd5babb35606ce5b153562a9eab88f | 46.076531 | 190 | 0.704021 | 5.629652 | false | false | false | false |
vapor-tools/vapor-jsonapi | Sources/VaporJsonApi/Resources/JsonApiResourceController.swift | 1 | 20192 | //
// JsonApiResourceController.swift
// VaporJsonApi
//
// Created by Koray Koska on 30/04/2017.
//
//
import Vapor
import HTTP
import FluentProvider
import URI
public protocol JsonApiResourceController {
associatedtype Resource: JsonApiResourceModel
func getResources(_ req: Request) throws -> ResponseRepresentable
}
public extension JsonApiResourceController {
public var resourceType: JsonApiResourceType {
return Resource.resourceType
}
/**
* The `getResources` method is responsible for get requests to the resource collection.
*
* Example: `/articles` for the article resource.
*
* - parameter req: The `Request` which fired this method.
*/
func getResources(_ req: Request) throws -> ResponseRepresentable {
guard req.fulfillsJsonApiAcceptResponsibilities() else {
throw JsonApiNotAcceptableError(mediaType: req.acceptHeaderValue() ?? "*No Accept header*")
}
let query = req.query?.converted(to: JSON.self)
let page = try pageForQuery(query: query)
let pagination = JsonApiPagedPaginator(pageCount: page.pageCount, pageSize: page.pageNumber)
let resources = try Resource.makeQuery().limit(pagination.pageCount, offset: pagination.pageOffset).all()
let jsonDocument = try document(forResources: resources, baseUrl: req.uri)
return JsonApiResponse(status: .ok, document: jsonDocument)
}
/**
* The `getResource` method is responsible for get requests to a specific resource.
*
* The id represented as a String is expected to be the first and only route parameter for this request.
*
* Example: `/articles/5` for the article resource.
*
* - parameter req: The `Request` which fired this method.
*/
func getResource(_ req: Request) throws -> ResponseRepresentable {
let id = try req.parameters.next(String.self)
guard req.fulfillsJsonApiAcceptResponsibilities() else {
throw JsonApiNotAcceptableError(mediaType: req.acceptHeaderValue() ?? "*No Accept header*")
}
// let query = req.jsonApiQuery()
guard let resource = try Resource.find(id) else {
throw JsonApiRecordNotFoundError(id: id)
}
let resourceObject = try resource.makeResourceObject(resourceModel: resource, baseUrl: req.uri)
let data = JsonApiData(resourceObject: resourceObject)
let document = JsonApiDocument(data: data)
return JsonApiResponse(status: .ok, document: document)
}
/**
* The `getRelatedResource` method is responsible for get requests to a relationship of a specific resource.
*
* The id represented as a String is expected to be the first route parameter for this request.
*
* The relationshipType represented as a String which is the relationship name as defined in
* the JsonApiResourceModel is expected to be the second and last parameter for this request.
*
* Example: `/articles/5/author` for the author resource of the article with id `5`.
*
* - parameter req: The `Request` which fired this method.
*/
func getRelatedResource(_ req: Request) throws -> ResponseRepresentable {
let id = try req.parameters.next(String.self)
let relationshipType = try req.parameters.next(String.self)
guard req.fulfillsJsonApiAcceptResponsibilities() else {
throw JsonApiNotAcceptableError(mediaType: req.acceptHeaderValue() ?? "*No Accept header*")
}
guard let resource = try Resource.find(id) else {
throw JsonApiRecordNotFoundError(id: id)
}
let query = req.query?.converted(to: JSON.self)
if let parentModel = try resource.parentRelationships()[relationshipType] {
if let parent = try parentModel.getter() {
let resourceObject = try parent.makeResourceObject(resourceModel: parent, baseUrl: req.uri)
let data = JsonApiData(resourceObject: resourceObject)
let document = JsonApiDocument(data: data)
return JsonApiResponse(status: .ok, document: document)
} else {
let document = JsonApiDocument()
return JsonApiResponse(status: .ok, document: document)
}
} else if let childrenCollection = try resource.childrenRelationships()[relationshipType] {
let page = try pageForQuery(query: query)
let pageNumber = page.pageNumber
let pageCount = page.pageCount
let paginator = JsonApiPagedPaginator(pageCount: pageCount, pageSize: pageNumber)
let resources = try childrenCollection.getter(paginator)
let jsonDocument = try document(forResources: resources, baseUrl: req.uri)
return JsonApiResponse(status: .ok, document: jsonDocument)
} else if let siblingsCollection = try resource.siblingsRelationships()[relationshipType] {
let page = try pageForQuery(query: query)
let pageNumber = page.pageNumber
let pageCount = page.pageCount
let paginator = JsonApiPagedPaginator(pageCount: pageCount, pageSize: pageNumber)
let resources = try siblingsCollection.getter(paginator)
let jsonDocument = try document(forResources: resources, baseUrl: req.uri)
return JsonApiResponse(status: .ok, document: jsonDocument)
}
throw JsonApiRelationshipNotFoundError(relationship: relationshipType)
}
/**
* The `getRelationships` method is responsible for get requests to a resource linkage object for a resource.
*
* The id represented as a String is expected to be the first route parameter for this request.
*
* The relationshipType represented as a String which is the relationship name as defined in
* the JsonApiResourceModel is expected to be the second and last parameter for this request.
*
* Example: `/articles/5/relationships/author` for the author resource linkage of the article with id `5`.
*
* - parameter req: The `Request` which fired this method.
*/
func getRelationships(_ req: Request) throws -> ResponseRepresentable {
let id = try req.parameters.next(String.self)
let relationshipType = try req.parameters.next(String.self)
guard req.fulfillsJsonApiAcceptResponsibilities() else {
throw JsonApiNotAcceptableError(mediaType: req.acceptHeaderValue() ?? "*No Accept header*")
}
guard let resource = try Resource.find(id) else {
throw JsonApiRecordNotFoundError(id: id)
}
let query = req.query?.converted(to: JSON.self)
if let parentModel = try resource.parentRelationships()[relationshipType] {
if let parent = try parentModel.getter() {
let resourceIdentifierObject = try parent.makeResourceIdentifierObject(resourceModel: parent)
let data = JsonApiData(resourceIdentifierObject: resourceIdentifierObject)
let document = JsonApiDocument(data: data)
return JsonApiResponse(status: .ok, document: document)
} else {
let document = JsonApiDocument()
return JsonApiResponse(status: .ok, document: document)
}
} else if let childrenCollection = try resource.childrenRelationships()[relationshipType] {
let page = try pageForQuery(query: query)
let pageNumber = page.pageNumber
let pageCount = page.pageCount
let paginator = JsonApiPagedPaginator(pageCount: pageCount, pageSize: pageNumber)
let resources = try childrenCollection.getter(paginator)
let jsonDocument = try resourceLinkageDocument(forResources: resources, baseUrl: req.uri)
return JsonApiResponse(status: .ok, document: jsonDocument)
} else if let siblingsCollection = try resource.siblingsRelationships()[relationshipType] {
let page = try pageForQuery(query: query)
let pageNumber = page.pageNumber
let pageCount = page.pageCount
let paginator = JsonApiPagedPaginator(pageCount: pageCount, pageSize: pageNumber)
let resources = try siblingsCollection.getter(paginator)
let jsonDocument = try resourceLinkageDocument(forResources: resources, baseUrl: req.uri)
return JsonApiResponse(status: .ok, document: jsonDocument)
}
throw JsonApiRelationshipNotFoundError(relationship: relationshipType)
}
/**
* The `postResource` method is responsible for post requests to a specific resource.
*
* Example: `/articles` for creating an article resource.
*
* - parameter req: The `Request` which fired this method.
*/
func postResource(_ req: Request) throws -> ResponseRepresentable {
guard req.fulfillsJsonApiAcceptResponsibilities() else {
throw JsonApiNotAcceptableError(mediaType: req.acceptHeaderValue() ?? "*No Accept header*")
}
guard req.fulfillsJsonApiContentTypeResponsibilities() else {
throw JsonApiUnsupportedMediaTypeError(mediaType: req.contentTypeHeaderValue() ?? "*No Content-Type header*")
}
let bodyData = req.jsonApiJson?["data"]
guard let type = bodyData?["type"]?.string else {
throw JsonApiParameterMissingError(parameter: "type")
}
guard type == Resource.resourceType.parse() else {
throw JsonApiTypeConflictError(type: type)
}
var resource: Resource
if let json = bodyData?["attributes"] {
resource = try Resource(row: json.converted())
} else {
throw JsonApiAttributesRequiredError()
}
// TODO: Check jsonapi document for correct to-many relationship handling
if let relationships = bodyData?["relationships"]?.object {
for r in relationships {
// Get relationships
let parents = try resource.parentRelationships()
let children = try resource.childrenRelationships()
let siblings = try resource.siblingsRelationships()
if let parent = parents[r.key] {
guard let id = r.value.object?["id"]?.string, let type = r.value.object?["type"]?.string else {
throw JsonApiBadRequestError(title: "Bad Request", detail: "The relationship \(r.key) must have a type and id value.")
}
guard let p = try parent.findInModel(id) else {
throw JsonApiRecordNotFoundError(id: id)
}
// Check type
guard type == parent.resourceType.parse() else {
throw JsonApiTypeConflictError(type: type)
}
guard let setter = parent.setter else {
throw JsonApiRelationshipNotAllowedError(relationship: type)
}
try setter(p)
} else if let _ = children[r.key] {
// throw JsonApiBadRequestError(title: "Setting to-many relationships not allowed", detail: "You set to-many relationships in the same step as creating a resource right now. You tried to set \(r.key) for this resource.")
} else if let _ = siblings[r.key] {
// throw JsonApiBadRequestError(title: "Setting to-many relationships not allowed", detail: "You set to-many relationships in the same step as creating a resource right now. You tried to set \(r.key) for this resource.")
} else {
throw JsonApiRelationshipNotAllowedError(relationship: r.key)
}
}
}
try resource.save()
// Return newly saved object as jsonapi resource
let resourceObject = try resource.makeResourceObject(resourceModel: resource, baseUrl: req.uri)
let data = JsonApiData(resourceObject: resourceObject)
let document = JsonApiDocument(data: data)
return JsonApiResponse(status: .created, document: document)
}
/**
* The `patchResource` method is responsible for patch requests to a specific resource.
*
* The id represented as a String is expected to be the first and only route parameter for this request.
*
* Example: `/articles/1` for editing an article resource.
*
* - parameter req: The `Request` which fired this method.
*/
func patchResource(_ req: Request) throws -> ResponseRepresentable {
let id = try req.parameters.next(String.self)
guard req.fulfillsJsonApiAcceptResponsibilities() else {
throw JsonApiNotAcceptableError(mediaType: req.acceptHeaderValue() ?? "*No Accept header*")
}
guard req.fulfillsJsonApiContentTypeResponsibilities() else {
throw JsonApiUnsupportedMediaTypeError(mediaType: req.contentTypeHeaderValue() ?? "*No Content-Type header*")
}
let bodyData = req.jsonApiJson?["data"]
// Check type
guard let type = bodyData?["type"]?.string else {
throw JsonApiParameterMissingError(parameter: "type")
}
guard type == Resource.resourceType.parse() else {
throw JsonApiTypeConflictError(type: type)
}
// Check id
guard let bodyId = bodyData?["id"]?.string else {
throw JsonApiMissingKeyError()
}
guard bodyId == id else {
throw JsonApiKeyNotIncludedInURLError(key: bodyId)
}
// Check resource
guard var resource = try Resource.find(id) else {
throw JsonApiRecordNotFoundError(id: id)
}
if let json = bodyData?["attributes"] {
try resource.update(json: json)
}
if let relationships = bodyData?["relationships"]?.object {
for r in relationships {
// Get relationships
let parents = try resource.parentRelationships()
let children = try resource.childrenRelationships()
let siblings = try resource.siblingsRelationships()
if let parent = parents[r.key] {
guard let id = r.value.object?["id"]?.string, let type = r.value.object?["type"]?.string else {
throw JsonApiBadRequestError(title: "Bad Request", detail: "The relationship \(r.key) must have a type and id value.")
}
guard let p = try parent.findInModel(id) else {
throw JsonApiRecordNotFoundError(id: id)
}
// Check type
guard type == parent.resourceType.parse() else {
throw JsonApiTypeConflictError(type: type)
}
guard let setter = parent.setter else {
throw JsonApiRelationshipNotAllowedError(relationship: type)
}
try setter(p)
} else if let child = children[r.key] {
guard let childs = r.value.array else {
throw JsonApiBadRequestError(title: "Bad relationship object", detail: "A to-many relationship must be provided as an array in the relationships object.")
}
var resources: [JsonApiResourceModel] = []
for c in childs {
guard let id = c.object?["id"]?.string, let type = c.object?["type"]?.string else {
throw JsonApiBadRequestError(title: "Bad Request", detail: "The relationship \(r.key) must have a type and id value.")
}
guard let cc = try child.findInModel(id) else {
throw JsonApiRecordNotFoundError(id: id)
}
// Check type
guard type == child.resourceType.parse() else {
throw JsonApiTypeConflictError(type: type)
}
resources.append(cc)
}
// Check replacer
guard let replacer = child.replacer else {
throw JsonApiToManySetReplacementForbiddenError()
}
try replacer(resources)
} else if let sibling = siblings[r.key] {
guard let siblings = r.value.array else {
throw JsonApiBadRequestError(title: "Bad relationship object", detail: "A to-many relationship must be provided as an array in the relationships object.")
}
var resources: [JsonApiResourceModel] = []
for s in siblings {
guard let id = s.object?["id"]?.string, let type = s.object?["type"]?.string else {
throw JsonApiBadRequestError(title: "Bad Request", detail: "The relationship \(r.key) must have a type and id value.")
}
guard let ss = try sibling.findInModel(id) else {
throw JsonApiRecordNotFoundError(id: id)
}
// Check type
guard type == sibling.resourceType.parse() else {
throw JsonApiTypeConflictError(type: type)
}
resources.append(ss)
}
// Check replacer
guard let replacer = sibling.replacer else {
throw JsonApiToManySetReplacementForbiddenError()
}
try replacer(resources)
} else {
throw JsonApiRelationshipNotAllowedError(relationship: r.key)
}
}
}
try resource.save()
// Return newly saved object as jsonapi resource
let resourceObject = try resource.makeResourceObject(resourceModel: resource, baseUrl: req.uri)
let data = JsonApiData(resourceObject: resourceObject)
let document = JsonApiDocument(data: data)
return JsonApiResponse(status: .ok, document: document)
}
}
fileprivate extension JsonApiResourceController {
fileprivate func pageForQuery(query: JSON?) throws -> (pageCount: Int, pageNumber: Int) {
let pageCount = query?["page"]?["size"]?.string?.int ?? JsonApiConfig.defaultPageSize
if pageCount > JsonApiConfig.maximumPageSize {
throw JsonApiInvalidPageValueError(page: "page[size]", value: query?["page"]?["size"]?.string ?? "*Nothing*")
}
let pageNumber = query?["page"]?["number"]?.string?.int ?? 1
if pageNumber < 1 {
throw JsonApiInvalidPageValueError(page: "page[number]", value: query?["page"]?["number"]?.string ?? "*Nothing*")
}
return (pageCount: pageCount, pageNumber: pageNumber)
}
fileprivate func document(forResources resources: [JsonApiResourceModel], baseUrl: URI) throws -> JsonApiDocument {
var resourceObjects = [JsonApiResourceObject]()
for r in resources {
resourceObjects.append(try r.makeResourceObject(resourceModel: r, baseUrl: baseUrl))
}
let data = JsonApiData(resourceObjects: resourceObjects)
return JsonApiDocument(data: data)
}
fileprivate func resourceLinkageDocument(forResources resources: [JsonApiResourceModel], baseUrl: URI) throws -> JsonApiDocument {
var resourceIdentifierObjects = [JsonApiResourceIdentifierObject]()
for r in resources {
resourceIdentifierObjects.append(try r.makeResourceIdentifierObject(resourceModel: r))
}
let data = JsonApiData(resourceIdentifierObjects: resourceIdentifierObjects)
return JsonApiDocument(data: data)
}
}
| mit | 10f788c09945c0e2d866dd85a9347b9f | 42.517241 | 240 | 0.614947 | 5.173456 | false | false | false | false |
valitovaza/NewsAP | NewsAP/NewsFeed/NewsEventHandler.swift | 1 | 6234 | protocol NewsEventHandlerProtocol: NewsRefresher {
func viewDidLoad()
func viewDidAppear()
func select(at index: Int, section: Int)
func openActions(for index: Int, section: Int)
func openActions(forFavorite index: Int)
func segmentSelected(_ index: Int)
func openSettings()
}
protocol NewsRefresher {
func refresh()
}
protocol ActionsInteractorProtocol: class {
func favorite(_ article: Article)
func isArticleAlreadyfavorited(_ article: Article) -> Bool
func getSettingsActions() -> [NotificationSettingsActions]
func processSettingsAction(_ action: NotificationSettingsActions)
}
enum NewsState {
case Loading
case News
case Error
}
enum NewsSegment {
case All
case Favorite
}
class NewsInteractor: NewsEventHandlerProtocol, ActionsInteractorProtocol {
var presenter: NewsPresenterProtocol!
var loader: NewsLoaderProtocol!
var router: NewsRouterProtocol!
var sourceHolder: SourceHolderProtocol!
var store: ArticleDataStoreProtocol!
var newsSaver: FavoriteNewsCacheProtocol!
var notificationController: LocalNotificationControllerProtocol!
var settingsHolder: SettingsHolderProtocol!
func viewDidLoad() {
checkTopSegment()
}
private func checkTopSegment() {
if newsSaver.favorites.count > 0 {
presenter.showTopSegment()
}else{
presenter.hideTopSegment()
}
}
private var isFirstAppeareanceExecutionDone = false
func viewDidAppear() {
if !isFirstAppeareanceExecutionDone {
isFirstAppeareanceExecutionDone = true
executeOnDidAppear()
}
}
private func executeOnDidAppear() {
if let sources = selectedSources() {
loadArticles(with: sources)
}else{
router.openSources()
}
}
private func selectedSources() -> [Source]? {
if let sources = sourceHolder.sources, sources.count > 0 {
return sources
}
return nil
}
private var loadingSources: [Source] = []
private func loadArticles(with sources: [Source]) {
store.clear()
loadingSources = sources
presenter.present(state: .Loading)
loadNewsFromFirstLoadingSource()
}
private func handleLoadResponse(_ articles: [Article], sourceName: String) {
if articles.count > 0 {
store.add(articles, for: sourceName)
}
presentState(articles.count)
loadNewsFromFirstLoadingSource()
}
private func presentState(_ fetchedCount: Int) {
if fetchedCount > 0 {
presentNews()
}else if loadingSources.count == 0 && store.count() == 0 {
presenter.present(state: .Error)
}
}
private func presentNews() {
if case .Reload = store.lastChanges() {
presenter.present(state: .News)
}else{
presenter.addArticles(change: store.lastChanges())
}
}
private func loadNewsFromFirstLoadingSource() {
guard loadingSources.count > 0 else {return}
let source = loadingSources.removeFirst()
loader.load(source.id)
{[weak self] (articles) in
self?.handleLoadResponse(articles, sourceName: source.name)
}
}
func refresh() {
if let sources = selectedSources() {
loadArticles(with: sources)
}
}
func select(at index: Int, section: Int) {
let article = store.article(for: index, in: section)
router.openArticle(article.url)
}
func openActions(for index: Int, section: Int) {
let article = store.article(for: index, in: section)
router.openActions(for: article)
}
func openActions(forFavorite index: Int) {
let article = newsSaver.favorites[index]
router.openActions(for: article)
}
func favorite(_ article: Article) {
updateFaveCache(article)
checkTopSegment()
presenter.reloadFavorite()
}
private func updateFaveCache(_ article: Article) {
if isArticleAlreadyfavorited(article) {
removeArticleFromCache(article)
}else{
addArticleToCache(article)
}
}
private func removeArticleFromCache(_ article: Article) {
newsSaver.delete(article)
notificationController.removeNotification(for: article)
}
private func addArticleToCache(_ article: Article) {
newsSaver.save(article)
if settingsHolder.isNotificationsEnabled() {
notificationController.addNotification(for: article)
}
}
func isArticleAlreadyfavorited(_ article: Article) -> Bool {
return newsSaver.favorites.contains(article)
}
func segmentSelected(_ index: Int) {
if index == 0 {
presenter.switchSegment(.All)
}else{
presenter.switchSegment(.Favorite)
}
}
func openSettings() {
router.openSettings()
}
func getSettingsActions() -> [NotificationSettingsActions] {
let lastAction = settingsHolder.isNotificationsEnabled() ? NotificationSettingsActions.Off : NotificationSettingsActions.On
return [NotificationSettingsActions.AM10,
NotificationSettingsActions.PM3,
NotificationSettingsActions.PM6,
NotificationSettingsActions.PM7,
NotificationSettingsActions.PM8,
NotificationSettingsActions.PM9,
NotificationSettingsActions.PM10,
lastAction]
}
func processSettingsAction(_ action: NotificationSettingsActions) {
if action == .Off {
notificationController.removeAllNotifications()
settingsHolder.setNotificationsEnabled(false)
}else{
processPositiveAction(action)
}
}
private func processPositiveAction(_ action: NotificationSettingsActions) {
settingsHolder.setNotificationsEnabled(true)
if let time = action.time {
settingsHolder.updateTime(time.hour, time.min)
notificationController.updateNotificationRequest()
}
}
}
| mit | 1a7f4baf877da0975f19dd687fa4bfd1 | 31.300518 | 131 | 0.637953 | 4.967331 | false | false | false | false |
craiggrummitt/ActionSwift3 | ActionSwift3/text/TextField.swift | 1 | 3396 | //
// TextField.swift
// ActionSwift
//
// Created by Craig on 24/07/2015.
// Copyright (c) 2015 Interactive Coconut. All rights reserved.
//
import SpriteKit
/** Set up your text field here. Beyond basic formatting (i.e. textColor), apply formatting using the `defaultTextFormat` property, passing in a TextFormat object. You also have background color, border color properties.
*/
open class TextField: InteractiveObject {
internal var textFieldNode = SKMultilineLabel(text: "", labelWidth: 100, pos: CGPoint(x: 0, y: 0))
open var _textFormat:TextFormat = TextFormat()
fileprivate var isDirty:Boolean = false
override public init() {
super.init()
textFieldNode.dontUpdate = true
self.node.addChild(textFieldNode)
textFieldNode.position.x = 0
textFieldNode.position.y = Stage.size.height
textFieldNode.owner = self
}
open var defaultTextFormat:TextFormat {
get {return _textFormat}
set(newValue) {
_textFormat = newValue
textFieldNode.alignment = newValue.align
textFieldNode.fontName = newValue.font
textFieldNode.fontSize = newValue.size
textFieldNode.fontColor = newValue.color
textFieldNode.leading = newValue.leading
isDirty = true
}
}
open var textColor:UIColor {
get {return textFieldNode.fontColor}
set(newValue) {
defaultTextFormat.color = newValue
textFieldNode.fontColor = newValue
isDirty = true
}
}
open var text:String {
get {return textFieldNode.text}
set(newValue) {
textFieldNode.text = newValue
isDirty = true
}
}
open var background:Bool {
get {return textFieldNode.shouldShowBackground}
set(newValue) {
textFieldNode.shouldShowBackground = newValue
isDirty = true
}
}
/** Background color - will only be active if `background` is set to true */
open var backgroundColor:UIColor {
get {return textFieldNode.backgroundColor}
set(newValue) {
textFieldNode.backgroundColor = newValue
isDirty = true
}
}
open var border:Bool {
get {return textFieldNode.shouldShowBorder}
set(newValue) {
textFieldNode.shouldShowBorder = newValue
isDirty = true
}
}
/** Border color - will only be active if `background` is set to true */
open var borderColor:UIColor {
get {return textFieldNode.borderColor}
set(newValue) {
textFieldNode.borderColor = newValue
isDirty = true
}
}
override internal func update(_ currentTime:CFTimeInterval) {
super.update(currentTime)
if (isDirty) {
print("Updating textField \(width), \(height)")
textFieldNode.update(forceUpdate:true)
textFieldNode.position.x = (width / 2)
isDirty = false
}
}
open var length:Int {
return text.count
}
override open var height:CGFloat {
return textFieldNode.height
}
override open var width:CGFloat {
get {return textFieldNode.width}
set(newValue) {
textFieldNode.labelWidth = newValue
isDirty = true
}
}
}
| mit | 3838244da61dd184dfc60f14526d9454 | 30.444444 | 220 | 0.612191 | 4.810198 | false | false | false | false |
velvetroom/columbus | Source/View/Home/VHomeReadyBarListCellStop.swift | 1 | 1329 | import UIKit
final class VHomeReadyBarListCellStop:VHomeReadyBarListCell
{
override init(frame:CGRect)
{
super.init(frame:frame)
factoryViews()
}
required init?(coder:NSCoder)
{
return nil
}
override func config(model:MHomePlanItemProtocol)
{
super.config(model:model)
guard
let modelStop:MHomePlanItemStop = model as? MHomePlanItemStop
else
{
return
}
icon.image = modelStop.icon.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
hover()
}
override var isSelected:Bool
{
didSet
{
hover()
}
}
override var isHighlighted:Bool
{
didSet
{
hover()
}
}
//MARK: private
private func hover()
{
if isSelected || isHighlighted
{
backgroundColor = UIColor.colourSuccess
labelTitle.textColor = UIColor.white
icon.tintColor = UIColor.white
}
else
{
backgroundColor = UIColor.white
labelTitle.textColor = UIColor.colourBackgroundDark
icon.tintColor = UIColor(white:0, alpha:0.2)
}
}
}
| mit | 181a0e697092a1d513b444923b884280 | 18.835821 | 90 | 0.521445 | 5.27381 | false | false | false | false |
steelwheels/Coconut | CoconutData/Source/Graphics/CNRect.swift | 1 | 5181 | /**
* @file CNRect.swift
* @brief Extend CGRect class
* @par Copyright
* Copyright (C) 2016-2021 Steel Wheels Project
*/
import CoreGraphics
import Foundation
public extension CGRect
{
static let ClassName = "rect"
static func fromValue(value val: CNValue) -> CGRect? {
if let dict = val.toDictionary() {
return fromValue(value: dict)
} else {
return nil
}
}
static func fromValue(value val: Dictionary<String, CNValue>) -> CGRect? {
if let xval = val["x"], let yval = val["y"], let wval = val["width"], let hval = val["height"] {
if let xnum = xval.toNumber(), let ynum = yval.toNumber(), let wnum = wval.toNumber(), let hnum = hval.toNumber() {
let x : CGFloat = CGFloat(xnum.floatValue)
let y : CGFloat = CGFloat(ynum.floatValue)
let width : CGFloat = CGFloat(wnum.floatValue)
let height : CGFloat = CGFloat(hnum.floatValue)
return CGRect(x: x, y: y, width: width, height: height)
}
}
return nil
}
func toValue() -> Dictionary<String, CNValue> {
let x = NSNumber(floatLiteral: Double(self.origin.x))
let y = NSNumber(floatLiteral: Double(self.origin.y))
let width = NSNumber(floatLiteral: Double(self.size.width))
let height = NSNumber(floatLiteral: Double(self.size.height))
let result: Dictionary<String, CNValue> = [
"class" : .stringValue(CGRect.ClassName),
"x" : .numberValue(x),
"y" : .numberValue(y),
"width" : .numberValue(width),
"height" : .numberValue(height)
]
return result
}
var center: CGPoint { get {
let x = self.origin.x + (self.size.width / 2)
let y = self.origin.y + (self.size.height / 2)
return CGPoint(x: x, y:y)
}}
var upperLeftPoint: CGPoint { get {
let result: CGPoint
#if os(OSX)
result = CGPoint(x: self.origin.x, y: self.origin.y + self.size.height)
#else
result = self.origin
#endif
return result
}}
var upperRightPoint: CGPoint { get {
let result: CGPoint
#if os(OSX)
result = CGPoint(x: self.origin.x + self.size.width, y: self.origin.y + self.size.height)
#else
result = CGPoint(x: self.origin.x + self.size.width, y: self.origin.y)
#endif
return result
}}
var lowerLeftPoint: CGPoint { get {
let result: CGPoint
#if os(OSX)
result = self.origin
#else
result = CGPoint(x: self.origin.x, y: self.origin.y + self.size.height)
#endif
return result
}}
var lowerRightPoint: CGPoint { get {
let result: CGPoint
#if os(OSX)
result = CGPoint(x: self.origin.x + self.size.width, y: self.origin.y)
#else
result = CGPoint(x: self.origin.x + self.size.width, y: self.origin.y + self.size.height)
#endif
return result
}}
func centeringIn(bounds bnds: CGRect) -> CGRect {
let dx = (bnds.size.width - self.size.width ) / 2.0
let dy = (bnds.size.height - self.size.height) / 2.0
let neworigin = CGPoint(x: bnds.origin.x + dx, y: bnds.origin.y + dy)
return CGRect(origin: neworigin, size: self.size)
}
func resize(size s:CGSize) -> CGRect {
return CGRect(origin: self.origin, size: s)
}
func move(dx x: CGFloat, dy y: CGFloat) -> CGRect {
let neworigin = self.origin.moving(dx: x, dy: y)
return CGRect(origin: neworigin, size: self.size)
}
func splitByHorizontally() -> (CGRect, CGRect) {
let width = self.size.width
let height = self.size.height / 2.0
let origin0 = self.origin
let origin1 = CGPoint(x: origin0.x, y: origin0.y + height)
let size = CGSize(width: width, height: height)
return (CGRect(origin: origin0, size: size), CGRect(origin: origin1, size: size))
}
func splitByVertically() -> (CGRect, CGRect) {
let width = self.size.width / 2.0
let height = self.size.height
let origin0 = self.origin
let origin1 = CGPoint(x: origin0.x + width, y: origin0.y)
let size = CGSize(width: width, height: height)
return (CGRect(origin: origin0, size: size), CGRect(origin: origin1, size: size))
}
static func insideRect(rect rct: CGRect, spacing space: CGFloat) -> CGRect {
let margin = space * 2.0
if rct.size.width < margin || rct.size.height < margin {
return rct
} else {
let x = rct.origin.x + space
let y = rct.origin.y + space
let width = rct.size.width - margin
let height = rct.size.height - margin
return CGRect(x: x, y: y, width: width, height: height)
}
}
static func outsideRect(rect rct: CGRect, spacing space: CGFloat) -> CGRect {
let margin = space * 2.0
let x = max(rct.origin.x - space, 0.0)
let y = max(rct.origin.y - space, 0.0)
let width = rct.size.width + margin
let height = rct.size.height + margin
return CGRect(x: x, y: y, width: width, height: height)
}
static func pointsToRect(fromPoint fp:CGPoint, toPoint tp:CGPoint) -> CGRect {
var x, y, width, height: CGFloat
if fp.x >= tp.x {
x = tp.x
width = fp.x - tp.x
} else {
x = fp.x
width = tp.x - fp.x
}
if fp.y >= tp.y {
y = tp.y
height = fp.y - tp.y
} else {
y = fp.y
height = tp.y - fp.y
}
return CGRect(x: x, y: y, width: width, height: height)
}
var description: String {
let ostr = origin.description
let sstr = size.description
return "{origin:\(ostr) size:\(sstr)}"
}
}
| lgpl-2.1 | 8e0cb9cbf1ca9fed16faedea33c9aa8d | 28.271186 | 118 | 0.643698 | 2.87036 | false | false | false | false |
Reblood/iOS-Reblood | Reblood/Reblood/ProfileTableViewController.swift | 1 | 2912 | //
// ProfileTableViewController.swift
// Reblood
//
// Created by Zulwiyoza Putra on 3/4/17.
// Copyright © 2017 Kibar. All rights reserved.
//
import UIKit
class ProfileViewController: UIViewController {
var user = User()
@IBOutlet weak var userProfileImage: UIImageView!
@IBOutlet weak var userProfileName: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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.
}
*/
}
| mit | 8f7e148b7890a2bf73e343cd7fbc0e47 | 30.301075 | 136 | 0.663346 | 5.264014 | false | false | false | false |
catloafsoft/AudioKit | AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Low Shelf Filter.xcplaygroundpage/Contents.swift | 1 | 968 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Low Shelf Filter
//:
import XCPlayground
import AudioKit
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("mixloop", ofType: "wav")
var player = AKAudioPlayer(file!)
player.looping = true
var lowShelfFilter = AKLowShelfFilter(player)
//: Set the parameters of the Low-Shelf Filter here
lowShelfFilter.cutoffFrequency = 800 // Hz
lowShelfFilter.gain = -100 // dB
AudioKit.output = lowShelfFilter
AudioKit.start()
player.play()
//: Toggle processing on every loop
AKPlaygroundLoop(every: 3.428) { () -> () in
if lowShelfFilter.isBypassed {
lowShelfFilter.start()
} else {
lowShelfFilter.bypass()
}
lowShelfFilter.isBypassed ? "Bypassed" : "Processing" // Open Quicklook for this
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| mit | c9e7d2eb5e6381fba7f0ae72af3f1664 | 25.162162 | 84 | 0.700413 | 3.796078 | false | false | false | false |
googlemaps/last-mile-fleet-solution-samples | ios_driverapp_samples/LMFSDriverSampleApp/Models/Task.swift | 1 | 3629 | /*
* Copyright 2022 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import Foundation
/// Swift equivalent of google.type.LatLng.
struct LatLng: Hashable, Codable {
let latitude: Double
let longitude: Double
}
/// Swift equivalent of maps.fleetengine.delivery.v1.LocationInfo.
struct LocationInfo: Hashable, Codable {
let point: LatLng
}
/// Swift equivalent of maps.fleetengine.delivery.v1.Task.
struct Task: Hashable, Codable, Identifiable {
enum CodingKeys: String, CodingKey {
case name, type, state, trackingId, deliveryVehicleId, plannedLocation, taskDuration
}
let name: String
let type: TaskType
let state: TaskState
let trackingId: String
let deliveryVehicleId: String?
let plannedLocation: LocationInfo
let taskDuration: Duration
var id: String {
return trackingId
}
init(from decoder: Decoder) throws {
let deliveryVehicleIdKey = CodingUserInfoKey(rawValue: "deliveryVehicleId")!
let defaultDeliveryVehicleId = String(describing: decoder.userInfo[deliveryVehicleIdKey])
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decode(String.self, forKey: .name)
self.type = try container.decode(TaskType.self, forKey: .type)
self.state = try container.decode(TaskState.self, forKey: .state)
self.trackingId = try container.decode(String.self, forKey: .trackingId)
self.deliveryVehicleId =
try container.decodeIfPresent(String.self, forKey: .deliveryVehicleId)
?? defaultDeliveryVehicleId
self.plannedLocation = try container.decode(LocationInfo.self, forKey: .plannedLocation)
self.taskDuration = Duration(
fromJSONString: try container.decode(String.self, forKey: .taskDuration))
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.name, forKey: .name)
try container.encode(self.type, forKey: .type)
try container.encode(self.state, forKey: .state)
try container.encode(self.trackingId, forKey: .trackingId)
try container.encode(self.deliveryVehicleId, forKey: .deliveryVehicleId)
try container.encode(self.plannedLocation, forKey: .plannedLocation)
try container.encode(self.taskDuration.JSONString, forKey: .taskDuration)
}
enum TaskType: String, CaseIterable, Codable {
case unspecified = "TYPE_UNSPECIFIED"
case pickup = "PICKUP"
case delivery = "DELIVERY"
case scheduled_stop = "SCHEDULED_STOP"
case unavailable = "UNAVAILABLE"
}
enum TaskState: String, CaseIterable, Codable {
case state_unspecified = "STATE_UNSPECIFIED"
case open = "OPEN"
case closed = "CLOSED"
}
struct Duration: Hashable, Codable {
let seconds: Int64
let nanos: Int32
init(fromJSONString: String) {
let components = fromJSONString.split(separator: "s")
self.seconds = Int64(components[0]) ?? 0
self.nanos = components.count > 1 ? Int32(components[1])! : 0
}
var JSONString: String {
return "\(seconds)s\((nanos != 0) ? String(nanos) : "")"
}
}
}
| apache-2.0 | 45cd3754fe3aa1c4d3cd6c86517a2858 | 34.23301 | 93 | 0.72582 | 4.082115 | false | false | false | false |
TG908/iOS | TUM Campus App/GradeTableViewCell.swift | 1 | 1242 | //
// GradeTableViewCell.swift
// TUM Campus App
//
// Created by Florian Gareis on 04.02.17.
// Copyright © 2017 LS1 TUM. All rights reserved.
//
import UIKit
class GradeTableViewCell: CardTableViewCell {
var grade: Grade? {
didSet {
if let grade = grade {
titleLabel.text = grade.name
resultLabel.text = "Restult: " + grade.result
let date = "Date: \(grade.date.string(using: "dd.MM.yyyy"))"
let semester = "Semester: \(grade.semester)"
let ects = "ECTS: \(grade.ects)"
let examiner = "Examiner: \(grade.examiner)"
let mode = "Mode: \(grade.mode)"
detailsLabel.text = date + ", " + semester + ", " + ects
secondDetailsLabel.text = examiner + ", " + mode
}
}
}
@IBOutlet weak var titleLabel: UILabel! {
didSet {
titleLabel.textColor = Constants.tumBlue
}
}
@IBOutlet weak var resultLabel: UILabel! {
didSet {
resultLabel.textColor = Constants.tumBlue
}
}
@IBOutlet weak var detailsLabel: UILabel!
@IBOutlet weak var secondDetailsLabel: UILabel!
}
| gpl-3.0 | 64c3d4a2980970a6758d8715a8cc39bb | 28.547619 | 76 | 0.542305 | 4.235495 | false | false | false | false |
fuku2014/quizpencil | Quiz.swift | 1 | 1375 | /**
Quiz
RealmオブジェクトのQuizModelクラス
- Author: fuku
- Copyright: Copyright (c) 2016 fuku. All rights reserved.
- Date: 2016/6/18
- Version: 2.0
*/
import RealmSwift
class Quiz: Object {
dynamic private var id: String = NSUUID().UUIDString
dynamic var name: String = ""
dynamic var context: String = ""
dynamic var ncmbId: String = ""
dynamic var category: String = ""
dynamic var isDownload: Bool = false
dynamic var isUpload: Bool = false
let questions = List<Question>()
/**
primaryKey
*/
override static func primaryKey() -> String? {
return "id"
}
/**
save
データを保存する
*/
func save() {
let realm = try! Realm()
try! realm.write {
realm.add(self)
}
}
/**
update
データを更新する
- returns: callback function
*/
func update(callback : (() -> Void)) {
let realm = try! Realm()
try! realm.write {
callback()
}
}
/**
remove
データを削除する
- returns: callback function
*/
func remove(callback : (() -> Void)) {
let realm = try! Realm()
try! realm.write {
realm.delete(self)
callback()
}
}
}
| apache-2.0 | af986cc75332dcabd8a05b20adfac7a5 | 17.671429 | 59 | 0.507269 | 4.16242 | false | false | false | false |
wyp767363905/TestKitchen_1606 | TestKitchen/TestKitchen/classes/cookbook/homePage/controller/CookbookViewController.swift | 1 | 8815 | //
// CookbookViewController.swift
// TestKitchen
//
// Created by qianfeng on 16/8/15.
// Copyright © 2016年 1606. All rights reserved.
//
import UIKit
class CookbookViewController: KTCHomeViewController {
//滚动视图
var scrollView: UIScrollView?
//食材首页的推荐视图
private var recommendView: CBRecommendView?
//首页的食材视图
private var foodView: CBMaterialView?
//首页的分类视图
private var categoryView: CBMaterialView?
//导航的标题视图
private var segCtrl: KTCSegmentCtrl?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//导航
createMyNav()
//初始化视图
createHomePageView()
//下载推荐的数据
downloadeRecommendData()
//下载食材的数据
downloadFoodData()
//下载分类的数据
downloaderCategoryData()
}
//下载分类的数据
func downloaderCategoryData(){
let params = ["methodName":"CategoryIndex"]
let downloader = KTCDownloader()
downloader.delegate = self
downloader.type = .Category
downloader.postWithUrl(kHostUrl, params: params)
}
//下载食材的数据
func downloadFoodData(){
let dict = ["methodName":"MaterialSubtype"]
let downloader = KTCDownloader()
downloader.delegate = self
downloader.type = .FoodMaterial
downloader.postWithUrl(kHostUrl, params: dict)
}
//初始化视图
func createHomePageView(){
automaticallyAdjustsScrollViewInsets = false
//1.创建一个滚动视图
scrollView = UIScrollView()
scrollView?.pagingEnabled = true
scrollView?.showsHorizontalScrollIndicator = false
//设置代理
scrollView?.delegate = self
view.addSubview(scrollView!)
//约束
scrollView?.snp_makeConstraints {
[weak self]
(make) in
make.edges.equalTo(self!.view).inset(UIEdgeInsetsMake(64, 0, 49, 0))
}
//2.创建容器视图
let containerView = UIView.createView()
scrollView?.addSubview(containerView)
//约束
containerView.snp_makeConstraints {
[weak self]
(make) in
make.edges.equalTo(self!.scrollView!)
make.height.equalTo(self!.scrollView!)
}
//3.添加子视图
//3.1推荐
recommendView = CBRecommendView()
containerView.addSubview(recommendView!)
//约束
recommendView?.snp_makeConstraints(closure: {
(make) in
make.top.bottom.equalTo(containerView)
make.width.equalTo(kScreenWidth)
make.left.equalTo(containerView)
})
//3.2.食材
foodView = CBMaterialView()
containerView.addSubview(foodView!)
//约束
foodView?.snp_makeConstraints(closure: { (make) in
make.top.bottom.equalTo(containerView)
make.width.equalTo(kScreenWidth)
make.left.equalTo((recommendView?.snp_right)!)
})
//3.3.分类
categoryView = CBMaterialView()
containerView.addSubview(categoryView!)
//约束
categoryView?.snp_makeConstraints(closure: { (make) in
make.top.bottom.equalTo(containerView)
make.width.equalTo(kScreenWidth)
make.left.equalTo((foodView?.snp_right)!)
})
containerView.snp_makeConstraints { (make) in
make.right.equalTo(categoryView!)
}
}
//下载推荐的数据
func downloadeRecommendData() {
let dict = ["methodName":"SceneHome"]
let downloader = KTCDownloader()
downloader.delegate = self
downloader.type = .Recommend
downloader.postWithUrl(kHostUrl, params: dict)
}
//创建导航
func createMyNav() {
//标题位置
segCtrl = KTCSegmentCtrl(frame: CGRectMake(80, 0, kScreenWidth-80*2, 44), titleNames: ["推荐","食材","分类"])
segCtrl?.delegate = self
navigationItem.titleView = segCtrl
//扫一扫
addNavBtn("saoyisao", target: self, action: #selector(scanAction), isLeft: true)
//搜索
addNavBtn("search", target: self, action: #selector(searchAction), isLeft: false)
}
//扫一扫
func scanAction() {
}
//搜索
func searchAction() {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: 首页推荐部分的方法
//食材课程分集显示
func gotoFoodCoursePage(link: String){
//第一个#
let startRange = NSString(string: link).rangeOfString("#")
//第二个#
let endRang = NSString(string: link).rangeOfString("#", options: NSStringCompareOptions.BackwardsSearch, range: NSMakeRange(0, link.characters.count), locale: nil)
let id = NSString(string: link).substringWithRange(NSMakeRange(startRange.location+1, endRang.location-startRange.location-1))
//跳转界面
let foodCourseCtrl = FoodCourseViewController()
foodCourseCtrl.serialId = id
navigationController?.pushViewController(foodCourseCtrl, animated: true)
}
//显示首页推荐的数据
func showRecommendData(model: CBRecommendModel){
recommendView?.model = model
//点击事件
recommendView?.clickClosure = {
[weak self]
(title: String?, link: String) in
if link.hasPrefix("app://food_course_series") == true {
//食材课程分集显示
self!.gotoFoodCoursePage(link)
}
}
}
//MARK: 首页食材
//MARK: 首页分类
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
//MARK: KTCDownloader代理
extension CookbookViewController : KTCDownloaderDelegate{
func downloader(downloader: KTCDownloader, didFailWithError error: NSError) {
print(error)
}
func downloader(downloader: KTCDownloader, didFinishWithData data: NSData?) {
if let jsonData = data {
if downloader.type == .Recommend {
//推荐
let model = CBRecommendModel.parseModel(jsonData)
//显示数据
dispatch_async(dispatch_get_main_queue(), {
[weak self] in
self!.showRecommendData(model)
})
}else if downloader.type == .FoodMaterial {
//食材
let model = CBMaterialModel.parseModelWithData(jsonData)
dispatch_async(dispatch_get_main_queue(), {
[weak self] in
self!.foodView?.model = model
})
}else if downloader.type == .Category {
//分类
let model = CBMaterialModel.parseModelWithData(jsonData)
dispatch_async(dispatch_get_main_queue(), {
[weak self] in
self!.categoryView?.model = model
})
}
}
}
}
extension CookbookViewController : KTCSegmentCtrlDelegate {
func didSelectSegCtrl(segCtrl: KTCSegmentCtrl, atIndex index: Int) {
scrollView?.contentOffset = CGPointMake(kScreenWidth*CGFloat(index), 0)
}
}
extension CookbookViewController : UIScrollViewDelegate {
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let index = Int(scrollView.contentOffset.x/scrollView.bounds.size.width)
//修改标题选中的按钮
segCtrl?.selectIndex = index
}
}
| mit | bee79727dbffadd25879c5ec1f01545e | 25.443038 | 171 | 0.553494 | 5.199751 | false | false | false | false |
atl009/WordPress-iOS | WordPress/Classes/ViewRelated/Blog/SharingButtonsViewController.swift | 1 | 35131 | import UIKit
import CocoaLumberjack
import WordPressShared
/// Manages which sharing button are displayed, their order, and other settings
/// related to sharing.
///
@objc class SharingButtonsViewController: UITableViewController {
let buttonSectionIndex = 0
let moreSectionIndex = 1
let blog: Blog
var buttons = [SharingButton]()
var sections = [SharingButtonsSection]()
var buttonsSection: SharingButtonsSection {
return sections[buttonSectionIndex]
}
var moreSection: SharingButtonsSection {
return sections[moreSectionIndex]
}
var twitterSection: SharingButtonsSection {
return sections.last!
}
let buttonStyles = [
"icon-text": NSLocalizedString("Icon & Text", comment: "Title of a button style"),
"icon": NSLocalizedString("Icon Only", comment: "Title of a button style"),
"text": NSLocalizedString("Text Only", comment: "Title of a button style"),
"official": NSLocalizedString("Official Buttons", comment: "Title of a button style")
]
let buttonStyleTitle = NSLocalizedString("Button Style", comment: "Title for a list of different button styles.")
let labelTitle = NSLocalizedString("Label", comment: "Noun. Title for the setting to edit the sharing label text.")
let twitterUsernameTitle = NSLocalizedString("Twitter Username", comment: "Title for the setting to edit the twitter username used when sharing to twitter.")
let twitterServiceID = "twitter"
let managedObjectContext = ContextManager.sharedInstance().newMainContextChildContext()
// MARK: - LifeCycle Methods
init(blog: Blog) {
self.blog = blog
super.init(style: .grouped)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = NSLocalizedString("Manage", comment: "Verb. Title of the screen for managing sharing buttons and settings related to sharing.")
let service = SharingService(managedObjectContext: managedObjectContext)
buttons = service.allSharingButtonsForBlog(self.blog)
configureTableView()
setupSections()
syncSharingButtons()
syncSharingSettings()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.saveButtonChanges(true)
}
// MARK: - Sections Setup and Config
/// Configures the table view. The table view is set to edit mode to allow
/// rows in the buttons and more sections to be reordered.
///
func configureTableView() {
tableView.register(SettingTableViewCell.self, forCellReuseIdentifier: SharingCellIdentifiers.SettingsCellIdentifier)
tableView.register(SwitchTableViewCell.self, forCellReuseIdentifier: SharingCellIdentifiers.SortableSwitchCellIdentifier)
tableView.register(SwitchTableViewCell.self, forCellReuseIdentifier: SharingCellIdentifiers.SwitchCellIdentifier)
WPStyleGuide.configureColors(for: view, andTableView: tableView)
tableView.setEditing(true, animated: false)
tableView.allowsSelectionDuringEditing = true
}
/// Sets up the sections for the table view and configures their starting state.
///
func setupSections() {
sections.append(setupButtonSection()) // buttons section should be section idx 0
sections.append(setupMoreSection()) // more section should be section idx 1
sections.append(setupShareLabelSection())
sections.append(setupButtonStyleSection())
if blog.isHostedAtWPcom {
sections.append(setupReblogAndLikeSection())
sections.append(setupCommentLikeSection())
}
sections.append(setupTwitterNameSection())
configureTwitterNameSection()
configureButtonRows()
configureMoreRows()
}
/// Sets up the buttons section. This section is sortable.
///
func setupButtonSection() -> SharingButtonsSection {
let section = SharingButtonsSection()
section.canSort = true
section.headerText = NSLocalizedString("Sharing Buttons", comment: "Title of a list of buttons used for sharing content to other services.")
return section
}
/// Sets up the more section. This section is sortable.
///
func setupMoreSection() -> SharingButtonsSection {
let section = SharingButtonsSection()
section.canSort = true
section.headerText = NSLocalizedString("\"More\" Button", comment: "Title of a list of buttons used for sharing content to other services. These buttons appear when the user taps a `More` button.")
section.footerText = NSLocalizedString("A \"more\" button contains a dropdown which displays sharing buttons", comment: "A short description of what the 'More' button is and how it works.")
return section
}
/// Sets up the label section.
///
func setupShareLabelSection() -> SharingButtonsSection {
let section = SharingButtonsSection()
let row = SharingSettingRow()
row.action = { [unowned self] in
self.handleEditLabel()
}
row.configureCell = {[unowned self] (cell: UITableViewCell) in
cell.editingAccessoryType = .disclosureIndicator
cell.textLabel?.text = self.labelTitle
cell.detailTextLabel!.text = self.blog.settings!.sharingLabel
}
section.rows = [row]
return section
}
/// Sets up the button style section
///
func setupButtonStyleSection() -> SharingButtonsSection {
let section = SharingButtonsSection()
let row = SharingSettingRow()
row.action = { [unowned self] in
self.handleEditButtonStyle()
}
row.configureCell = {[unowned self] (cell: UITableViewCell) in
cell.editingAccessoryType = .disclosureIndicator
cell.textLabel?.text = self.buttonStyleTitle
cell.detailTextLabel!.text = self.buttonStyles[self.blog.settings!.sharingButtonStyle]
}
section.rows = [row]
return section
}
/// Sets up the reblog and the likes section
///
func setupReblogAndLikeSection() -> SharingButtonsSection {
var rows = [SharingButtonsRow]()
let section = SharingButtonsSection()
section.headerText = NSLocalizedString("Reblog & Like", comment: "Title for a list of ssettings for editing a blog's Reblog and Like settings.")
// Reblog button row
var row = SharingSwitchRow()
row.configureCell = {[unowned self] (cell: UITableViewCell) in
cell.editingAccessoryView = cell.accessoryView
cell.editingAccessoryType = cell.accessoryType
if let switchCell = cell as? SwitchTableViewCell {
switchCell.textLabel?.text = NSLocalizedString("Show Reblog button", comment: "Title for the `show reblog button` setting")
switchCell.on = !self.blog.settings!.sharingDisabledReblogs
switchCell.onChange = { newValue in
self.blog.settings!.sharingDisabledReblogs = !newValue
self.saveBlogSettingsChanges(false)
let properties = [
"checked": NSNumber(value: newValue)
]
WPAppAnalytics.track(.sharingButtonShowReblogChanged, withProperties: properties, with: self.blog)
}
}
}
rows.append(row)
// Like button row
row = SharingSwitchRow()
row.configureCell = {[unowned self] (cell: UITableViewCell) in
cell.editingAccessoryView = cell.accessoryView
cell.editingAccessoryType = cell.accessoryType
if let switchCell = cell as? SwitchTableViewCell {
switchCell.textLabel?.text = NSLocalizedString("Show Like button", comment: "Title for the `show like button` setting")
switchCell.on = !self.blog.settings!.sharingDisabledLikes
switchCell.onChange = { newValue in
self.blog.settings!.sharingDisabledLikes = !newValue
self.saveBlogSettingsChanges(false)
}
}
}
rows.append(row)
section.rows = rows
return section
}
/// Sets up the section for comment likes
///
func setupCommentLikeSection() -> SharingButtonsSection {
let section = SharingButtonsSection()
section.footerText = NSLocalizedString("Allow all comments to be Liked by you and your readers", comment: "A short description of the comment like sharing setting.")
let row = SharingSwitchRow()
row.configureCell = {[unowned self] (cell: UITableViewCell) in
cell.editingAccessoryView = cell.accessoryView
cell.editingAccessoryType = cell.accessoryType
if let switchCell = cell as? SwitchTableViewCell {
switchCell.textLabel?.text = NSLocalizedString("Comment Likes", comment: "Title for the `comment likes` setting")
switchCell.on = self.blog.settings!.sharingCommentLikesEnabled
switchCell.onChange = { newValue in
self.blog.settings!.sharingCommentLikesEnabled = newValue
self.saveBlogSettingsChanges(false)
}
}
}
section.rows = [row]
return section
}
/// Sets up the twitter names section. The contents of the section are displayed
/// or not displayed depending on if the Twitter button is enabled.
///
func setupTwitterNameSection() -> SharingButtonsSection {
return SharingButtonsSection()
}
/// Configures the twiter name section. When the twitter button is disabled,
/// the section header is empty, and there are no rows. When the twitter button
/// is enabled. the section header and the row is shown.
///
func configureTwitterNameSection() {
if !shouldShowTwitterSection() {
twitterSection.footerText = " "
twitterSection.rows.removeAll()
return
}
twitterSection.footerText = NSLocalizedString("This will be included in tweets when people share using the Twitter button.", comment: "A description of the twitter sharing setting.")
let row = SharingSettingRow()
row.action = { [unowned self] in
self.handleEditTwitterName()
}
row.configureCell = {[unowned self] (cell: UITableViewCell) in
cell.editingAccessoryType = .disclosureIndicator
cell.textLabel?.text = self.twitterUsernameTitle
var name = self.blog.settings!.sharingTwitterName
if name.count > 0 {
name = "@\(name)"
}
cell.detailTextLabel?.text = name
}
twitterSection.rows = [row]
}
/// Creates a sortable row for the specified button.
///
/// - Parameter button: The sharing button that the row will represent.
///
/// - Returns: A SortableSharingSwitchRow.
///
func sortableRowForButton(_ button: SharingButton) -> SortableSharingSwitchRow {
let row = SortableSharingSwitchRow(buttonID: button.buttonID)
row.configureCell = {[unowned self] (cell: UITableViewCell) in
cell.imageView?.image = self.iconForSharingButton(button)
cell.imageView?.tintColor = WPStyleGuide.greyLighten20()
cell.editingAccessoryView = nil
cell.editingAccessoryType = .none
cell.textLabel?.text = button.name
}
return row
}
/// Creates a switch row for the specified button in the sharing buttons section.
///
/// - Parameter button: The sharing button that the row will represent.
///
/// - Returns: A SortableSharingSwitchRow.
///
func switchRowForButtonSectionButton(_ button: SharingButton) -> SortableSharingSwitchRow {
let row = SortableSharingSwitchRow(buttonID: button.buttonID)
row.configureCell = {[unowned self] (cell: UITableViewCell) in
if let switchCell = cell as? SwitchTableViewCell {
self.configureSortableSwitchCellAppearance(switchCell, button: button)
switchCell.on = button.enabled && button.visible
switchCell.onChange = { newValue in
button.enabled = newValue
if button.enabled {
button.visibility = button.enabled ? SharingButton.visible : nil
}
self.refreshMoreSection()
}
}
}
return row
}
/// Creates a switch row for the specified button in the more buttons section.
///
/// - Parameter button: The sharing button that the row will represent.
///
/// - Returns: A SortableSharingSwitchRow.
///
func switchRowForMoreSectionButton(_ button: SharingButton) -> SortableSharingSwitchRow {
let row = SortableSharingSwitchRow(buttonID: button.buttonID)
row.configureCell = {[unowned self] (cell: UITableViewCell) in
if let switchCell = cell as? SwitchTableViewCell {
self.configureSortableSwitchCellAppearance(switchCell, button: button)
switchCell.on = button.enabled && !button.visible
switchCell.onChange = { newValue in
button.enabled = newValue
if button.enabled {
button.visibility = button.enabled ? SharingButton.hidden : nil
}
self.refreshButtonsSection()
}
}
}
return row
}
/// Configures common appearance properties for the button switch cells.
///
/// - Parameters:
/// - cell: The SwitchTableViewCell cell to configure
/// - button: The sharing button that the row will represent.
///
func configureSortableSwitchCellAppearance(_ cell: SwitchTableViewCell, button: SharingButton) {
cell.editingAccessoryView = cell.accessoryView
cell.editingAccessoryType = cell.accessoryType
cell.imageView?.image = self.iconForSharingButton(button)
cell.imageView?.tintColor = WPStyleGuide.greyLighten20()
cell.textLabel?.text = button.name
}
/// Configures the rows for the button section. When the section is editing,
/// all buttons are shown with switch cells. When the section is not editing,
/// only enabled and visible buttons are shown and the rows are sortable.
///
func configureButtonRows() {
var rows = [SharingButtonsRow]()
let row = SharingSwitchRow()
row.configureCell = {[unowned self] (cell: UITableViewCell) in
if let switchCell = cell as? SwitchTableViewCell {
cell.editingAccessoryView = cell.accessoryView
cell.editingAccessoryType = cell.accessoryType
switchCell.textLabel?.text = NSLocalizedString("Edit sharing buttons", comment: "Title for the edit sharing buttons section")
switchCell.on = self.buttonsSection.editing
switchCell.onChange = { newValue in
self.buttonsSection.editing = !self.buttonsSection.editing
self.updateButtonOrderAfterEditing()
self.saveButtonChanges(true)
}
}
}
rows.append(row)
if !buttonsSection.editing {
let buttonsToShow = buttons.filter { (button) -> Bool in
return button.enabled && button.visible
}
for button in buttonsToShow {
rows.append(sortableRowForButton(button))
}
} else {
for button in buttons {
rows.append(switchRowForButtonSectionButton(button))
}
}
buttonsSection.rows = rows
}
/// Configures the rows for the more section. When the section is editing,
/// all buttons are shown with switch cells. When the section is not editing,
/// only enabled and hidden buttons are shown and the rows are sortable.
///
func configureMoreRows() {
var rows = [SharingButtonsRow]()
let row = SharingSwitchRow()
row.configureCell = {[unowned self] (cell: UITableViewCell) in
if let switchCell = cell as? SwitchTableViewCell {
cell.editingAccessoryView = cell.accessoryView
cell.editingAccessoryType = cell.accessoryType
switchCell.textLabel?.text = NSLocalizedString("Edit \"More\" button", comment: "Title for the edit more button section")
switchCell.on = self.moreSection.editing
switchCell.onChange = { newValue in
self.updateButtonOrderAfterEditing()
self.moreSection.editing = !self.moreSection.editing
self.saveButtonChanges(true)
}
}
}
rows.append(row)
if !moreSection.editing {
let buttonsToShow = buttons.filter { (button) -> Bool in
return button.enabled && !button.visible
}
for button in buttonsToShow {
rows.append(sortableRowForButton(button))
}
} else {
for button in buttons {
rows.append(switchRowForMoreSectionButton(button))
}
}
moreSection.rows = rows
}
/// Refreshes the rows for but button section (also the twitter section if
/// needed) and reloads the section.
///
func refreshButtonsSection() {
configureButtonRows()
configureTwitterNameSection()
let indexes: IndexSet = [buttonSectionIndex, sections.count - 1]
tableView.reloadSections(indexes, with: .automatic)
}
/// Refreshes the rows for but more section (also the twitter section if
/// needed) and reloads the section.
///
func refreshMoreSection() {
configureMoreRows()
configureTwitterNameSection()
let indexes: IndexSet = [moreSectionIndex, sections.count - 1]
tableView.reloadSections(indexes, with: .automatic)
}
/// Provides the icon that represents the sharing button's service.
///
/// - Parameter button: The sharing button for the icon.
///
/// - Returns: The UIImage for the icon
///
func iconForSharingButton(_ button: SharingButton) -> UIImage {
return WPStyleGuide.iconForService(button.buttonID as NSString)
}
// MARK: - Instance Methods
/// Whether the twitter section should be present or not.
///
/// - Returns: true if the twitter section should be shown. False otherwise.
///
func shouldShowTwitterSection() -> Bool {
for button in buttons {
if button.buttonID == twitterServiceID {
return button.enabled
}
}
return false
}
/// Saves changes to blog settings back to the blog and optionally refreshes
/// the tableview.
///
/// - Parameter refresh: True if the tableview should be reloaded.
///
func saveBlogSettingsChanges(_ refresh: Bool) {
if refresh {
tableView.reloadData()
}
let context = ContextManager.sharedInstance().mainContext
let service = BlogService(managedObjectContext: context)
let dotComID = blog.dotComID
service.updateSettings(
for: self.blog,
success: {
WPAppAnalytics.track(.sharingButtonSettingsChanged, withBlogID: dotComID)
},
failure: { [weak self] (error: Error) in
let error = error as NSError
DDLogError(error.description)
self?.showErrorSyncingMessage(error)
})
}
/// Syncs sharing buttons from the user's blog and reloads the button sections
/// when finished. Fails silently if there is an error.
///
func syncSharingButtons() {
let service = SharingService(managedObjectContext: managedObjectContext)
service.syncSharingButtonsForBlog(self.blog,
success: { [weak self] in
self?.reloadButtons()
},
failure: { (error: NSError?) in
DDLogError((error?.description)!)
})
}
/// Sync sharing settings from the user's blog and reloads the setting sections
/// when finished. Fails silently if there is an error.
///
func syncSharingSettings() {
let service = BlogService(managedObjectContext: managedObjectContext)
service.syncSettings(for: blog, success: { [weak self] in
self?.reloadSettingsSections()
},
failure: { (error: Error) in
let error = error as NSError
DDLogError(error.description)
})
}
/// Reloads the sections for different button settings.
///
func reloadSettingsSections() {
let settingsSections = NSMutableIndexSet()
for i in 0..<sections.count {
if i <= buttonSectionIndex {
continue
}
settingsSections.add(i)
}
tableView.reloadSections(settingsSections as IndexSet, with: .automatic)
}
// MARK: - Update And Save Buttons
/// Updates rows after editing.
///
func updateButtonOrderAfterEditing() {
let buttonsForButtonSection = buttons.filter { (btn) -> Bool in
return btn.enabled && btn.visible
}
let buttonsForMoreSection = buttons.filter { (btn) -> Bool in
return btn.enabled && !btn.visible
}
let remainingButtons = buttons.filter { (btn) -> Bool in
return !btn.enabled
}
var order = 0
for button in buttonsForButtonSection {
button.order = NSNumber(value: order)
order += 1
}
for button in buttonsForMoreSection {
button.order = NSNumber(value: order)
order += 1
}
for button in remainingButtons {
// we'll update the order for the remaining buttons but this is not
// respected by the REST API and changes after syncing.
button.order = NSNumber(value: order)
order += 1
}
}
/// Saves changes to sharing buttons to core data, reloads the buttons, then
/// pushes the changes up to the blog, optionally refreshing when done.
///
/// - Parameter refreshAfterSync: If true buttons are reloaded when the sync completes.
///
func saveButtonChanges(_ refreshAfterSync: Bool) {
let context = ContextManager.sharedInstance().mainContext
ContextManager.sharedInstance().save(context) { [weak self] in
self?.reloadButtons()
self?.syncButtonChangesToBlog(refreshAfterSync)
}
}
/// Retrives a fresh copy of the SharingButtons from core data, updating the
/// `buttons` property and refreshes the button section and the more section.
///
func reloadButtons() {
let service = SharingService(managedObjectContext: managedObjectContext)
buttons = service.allSharingButtonsForBlog(blog)
refreshButtonsSection()
refreshMoreSection()
}
/// Saves changes to the sharing buttons back to the blog.
///
/// - Parameter refresh: True if the tableview sections should be reloaded.
///
func syncButtonChangesToBlog(_ refresh: Bool) {
let service = SharingService(managedObjectContext: managedObjectContext)
service.updateSharingButtonsForBlog(blog,
sharingButtons: buttons,
success: {[weak self] in
if refresh {
self?.reloadButtons()
}
},
failure: { [weak self] (error: NSError?) in
DDLogError((error?.description)!)
self?.showErrorSyncingMessage(error)
})
}
/// Shows an alert. The localized description of the specified NSError is
/// included in the alert.
///
/// - Parameter error: An NSError object.
///
func showErrorSyncingMessage(_ error: NSError?) {
let title = NSLocalizedString("Could Not Save Changes", comment: "Title of an prompt letting the user know there was a problem saving.")
var message = NSLocalizedString("There was a problem saving changes to sharing management.", comment: "A short error message shown in a prompt.")
if let error = error {
message.append(error.localizedDescription)
}
let controller = UIAlertController(title: title, message: message, preferredStyle: .alert)
controller.addCancelActionWithTitle(NSLocalizedString("OK", comment: "A button title."), handler: nil)
controller.presentFromRootViewController()
}
// MARK: - Actions
/// Called when the user taps the label row. Shows a controller to change the
/// edit label text.
///
func handleEditLabel() {
let text = blog.settings!.sharingLabel
let placeholder = NSLocalizedString("Type a label", comment: "A placeholder for the sharing label.")
let hint = NSLocalizedString("Change the text of the sharing buttons' label. This text won't appear until you add at least one sharing button.", comment: "Instructions for editing the sharing label.")
let controller = SettingsTextViewController(text: text, placeholder: placeholder, hint: hint)
controller.title = labelTitle
controller.onValueChanged = {[unowned self] (value) in
guard value != self.blog.settings!.sharingLabel else {
return
}
self.blog.settings!.sharingLabel = value
self.saveBlogSettingsChanges(true)
}
navigationController?.pushViewController(controller, animated: true)
}
/// Called when the user taps the button style row. Shows a controller to
/// choose from available button styles.
///
func handleEditButtonStyle() {
var titles = [String]()
var values = [String]()
_ = buttonStyles.map({ (k: String, v: String) in
titles.append(v)
values.append(k)
})
let currentValue = blog.settings!.sharingButtonStyle
let dict: [String: AnyObject] = [
SettingsSelectionDefaultValueKey: values[0] as AnyObject,
SettingsSelectionTitleKey: buttonStyleTitle as AnyObject,
SettingsSelectionTitlesKey: titles as AnyObject,
SettingsSelectionValuesKey: values as AnyObject,
SettingsSelectionCurrentValueKey: currentValue as AnyObject
]
let controller = SettingsSelectionViewController(dictionary: dict)
controller?.onItemSelected = { [unowned self] (selected) in
if let str = selected as? String {
if self.blog.settings!.sharingButtonStyle == str {
return
}
self.blog.settings!.sharingButtonStyle = str
self.saveBlogSettingsChanges(true)
}
}
navigationController?.pushViewController(controller!, animated: true)
}
/// Called when the user taps the twitter name row. Shows a controller to change
/// the twitter name text.
///
func handleEditTwitterName() {
let text = blog.settings!.sharingTwitterName
let placeholder = NSLocalizedString("Username", comment: "A placeholder for the twitter username")
let hint = NSLocalizedString("This will be included in tweets when people share using the Twitter button.", comment: "Information about the twitter sharing feature.")
let controller = SettingsTextViewController(text: text, placeholder: placeholder, hint: hint)
controller.title = twitterUsernameTitle
controller.onValueChanged = {[unowned self] (value) in
if value == self.blog.settings!.sharingTwitterName {
return
}
// Remove the @ sign if it was entered.
var str = NSString(string: value)
str = str.replacingOccurrences(of: "@", with: "") as NSString
self.blog.settings!.sharingTwitterName = str as String
self.saveBlogSettingsChanges(true)
}
navigationController?.pushViewController(controller, animated: true)
}
// MARK: - TableView Delegate Methods
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].rows.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = sections[indexPath.section].rows[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: row.cellIdentifier)!
row.configureCell?(cell)
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section].headerText
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
WPStyleGuide.configureTableViewSectionHeader(view)
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return sections[section].footerText
}
override func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
WPStyleGuide.configureTableViewSectionFooter(view)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let row = sections[indexPath.section].rows[indexPath.row]
if row.cellIdentifier != SharingCellIdentifiers.SettingsCellIdentifier {
tableView.deselectRow(at: indexPath, animated: true)
}
row.action?()
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Since we want to be able to order particular rows, let's only allow editing for those specific rows.
// Note: We have to allow editing because UITableView will only give us the ordering accessory while editing is toggled.
let section = sections[indexPath.section]
return section.canSort && !section.editing && indexPath.row > 0
}
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
let section = sections[indexPath.section]
return section.canSort && !section.editing && indexPath.row > 0
}
// The table view is in editing mode, but no cells should show the delete button,
// only the move icon.
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return .none
}
override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
// The first row in the section is static containing the on/off toggle.
override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
let row = proposedDestinationIndexPath.row > 0 ? proposedDestinationIndexPath.row : 1
return IndexPath(row: row, section: sourceIndexPath.section)
}
// Updates the order of the moved button.
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let sourceSection = sections[sourceIndexPath.section]
let diff = destinationIndexPath.row - sourceIndexPath.row
let movedRow = sourceSection.rows[sourceIndexPath.row] as! SortableSharingSwitchRow
let movedButton = buttons.filter { (button) -> Bool in
return button.buttonID == movedRow.buttonID
}
let theButton = movedButton.first!
let oldIndex = buttons.index(of: theButton)!
let newIndex = oldIndex + diff
let buttonsArr = NSMutableArray(array: buttons)
buttonsArr.removeObject(at: oldIndex)
buttonsArr.insert(theButton, at: newIndex)
// Update the order for all buttons
for (index, button) in buttonsArr.enumerated() {
let sharingButton = button as! SharingButton
sharingButton.order = NSNumber(value: index)
}
self.saveButtonChanges(false)
WPAppAnalytics.track(.sharingButtonOrderChanged, with: blog)
}
// MARK: - View Model Assets
typealias SharingButtonsRowAction = () -> Void
typealias SharingButtonsCellConfig = (UITableViewCell) -> Void
struct SharingCellIdentifiers {
static let SettingsCellIdentifier = "SettingsTableViewCellIdentifier"
static let SortableSwitchCellIdentifier = "SortableSwitchTableViewCellIdentifier"
static let SwitchCellIdentifier = "SwitchTableViewCellIdentifier"
}
/// Represents a section in the sharinging management table view.
///
class SharingButtonsSection {
var rows: [SharingButtonsRow] = [SharingButtonsRow]()
var headerText: String?
var footerText: String?
var editing = false
var canSort = false
}
/// Represents a row in the sharing management table view.
///
class SharingButtonsRow {
var cellIdentifier = ""
var action: SharingButtonsRowAction?
var configureCell: SharingButtonsCellConfig?
}
/// A sortable switch row. By convention this is only used for sortable button rows
///
class SortableSharingSwitchRow: SharingButtonsRow {
var buttonID: String
init(buttonID: String) {
self.buttonID = buttonID
super.init()
cellIdentifier = SharingCellIdentifiers.SortableSwitchCellIdentifier
}
}
/// An unsortable switch row.
///
class SharingSwitchRow: SharingButtonsRow {
override init() {
super.init()
cellIdentifier = SharingCellIdentifiers.SwitchCellIdentifier
}
}
/// A row for sharing settings that do not need a switch control in its cell.
///
class SharingSettingRow: SharingButtonsRow {
override init() {
super.init()
cellIdentifier = SharingCellIdentifiers.SettingsCellIdentifier
}
}
}
| gpl-2.0 | f446aeee9f4f316add9cbc13af81597e | 35.824948 | 208 | 0.640602 | 5.330956 | false | false | false | false |
hooman/swift | test/decl/var/property_wrappers.swift | 1 | 58826 | // RUN: %target-typecheck-verify-swift -swift-version 5
// ---------------------------------------------------------------------------
// Property wrapper type definitions
// ---------------------------------------------------------------------------
@propertyWrapper
struct Wrapper<T> {
private var _stored: T
init(stored: T) {
self._stored = stored
}
var wrappedValue: T {
get { _stored }
set { _stored = newValue }
}
}
@propertyWrapper
struct WrapperWithInitialValue<T> {
var wrappedValue: T
init(wrappedValue initialValue: T) {
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperWithDefaultInit<T> {
private var stored: T?
var wrappedValue: T {
get { stored! }
set { stored = newValue }
}
init() {
self.stored = nil
}
}
@propertyWrapper
struct WrapperAcceptingAutoclosure<T> {
private let fn: () -> T
var wrappedValue: T {
return fn()
}
init(wrappedValue fn: @autoclosure @escaping () -> T) {
self.fn = fn
}
init(body fn: @escaping () -> T) {
self.fn = fn
}
}
@propertyWrapper
struct MissingValue<T> { }
// expected-error@-1{{property wrapper type 'MissingValue' does not contain a non-static property named 'wrappedValue'}} {{educational-notes=property-wrapper-requirements}}{{25-25=var wrappedValue: <#Value#>}}
@propertyWrapper
struct StaticValue {
static var wrappedValue: Int = 17
}
// expected-error@-3{{property wrapper type 'StaticValue' does not contain a non-static property named 'wrappedValue'}}{{21-21=var wrappedValue: <#Value#>}}
// expected-error@+1{{'@propertyWrapper' attribute cannot be applied to this declaration}}
@propertyWrapper
protocol CannotBeAWrapper {
associatedtype Value
var wrappedValue: Value { get set }
}
@propertyWrapper
struct NonVisibleValueWrapper<Value> {
private var wrappedValue: Value // expected-error{{private property 'wrappedValue' cannot have more restrictive access than its enclosing property wrapper type 'NonVisibleValueWrapper' (which is internal)}} {{educational-notes=property-wrapper-requirements}}
}
@propertyWrapper
struct NonVisibleInitWrapper<Value> {
var wrappedValue: Value
private init(wrappedValue initialValue: Value) { // expected-error{{private initializer 'init(wrappedValue:)' cannot have more restrictive access than its enclosing property wrapper type 'NonVisibleInitWrapper' (which is internal)}}
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct InitialValueTypeMismatch<Value> {
var wrappedValue: Value // expected-note{{'wrappedValue' declared here}}
init(wrappedValue initialValue: Value?) { // expected-error{{'init(wrappedValue:)' parameter type ('Value?') must be the same as its 'wrappedValue' property type ('Value') or an @autoclosure thereof}} {{educational-notes=property-wrapper-requirements}}
self.wrappedValue = initialValue!
}
}
@propertyWrapper
struct MultipleInitialValues<Value> {
var wrappedValue: Value? = nil // expected-note 2{{'wrappedValue' declared here}}
init(wrappedValue initialValue: Int) { // expected-error{{'init(wrappedValue:)' parameter type ('Int') must be the same as its 'wrappedValue' property type ('Value?') or an @autoclosure thereof}}
}
init(wrappedValue initialValue: Double) { // expected-error{{'init(wrappedValue:)' parameter type ('Double') must be the same as its 'wrappedValue' property type ('Value?') or an @autoclosure thereof}}
}
}
@propertyWrapper
struct InitialValueFailable<Value> {
var wrappedValue: Value
init?(wrappedValue initialValue: Value) { // expected-error{{property wrapper initializer 'init(wrappedValue:)' cannot be failable}} {{educational-notes=property-wrapper-requirements}}
return nil
}
}
@propertyWrapper
struct InitialValueFailableIUO<Value> {
var wrappedValue: Value
init!(wrappedValue initialValue: Value) { // expected-error{{property wrapper initializer 'init(wrappedValue:)' cannot be failable}}
return nil
}
}
// ---------------------------------------------------------------------------
// Property wrapper type definitions
// ---------------------------------------------------------------------------
@propertyWrapper
struct _lowercaseWrapper<T> {
var wrappedValue: T
}
@propertyWrapper
struct _UppercaseWrapper<T> {
var wrappedValue: T
}
// ---------------------------------------------------------------------------
// Local property wrappers
// ---------------------------------------------------------------------------
func testLocalContext() {
@WrapperWithInitialValue
var x = 17
x = 42
let _: Int = x
let _: WrapperWithInitialValue = _x
@WrapperWithInitialValue(wrappedValue: 17)
var initialValue
let _: Int = initialValue
let _: WrapperWithInitialValue = _initialValue
@Clamping(min: 0, max: 100)
var percent = 50
let _: Int = percent
let _: Clamping = _percent
@WrapperA @WrapperB
var composed = "hello"
let _: WrapperA<WrapperB> = _composed
@WrapperWithStorageRef
var hasProjection = 10
let _: Wrapper = $hasProjection
@WrapperWithInitialValue
var uninitialized: Int { // expected-error {{non-member observing properties require an initializer}}
didSet {}
}
}
// ---------------------------------------------------------------------------
// Limitations on where property wrappers can be used
// ---------------------------------------------------------------------------
enum SomeEnum {
case foo
@Wrapper(stored: 17)
var bar: Int // expected-error{{property 'bar' declared inside an enum cannot have a wrapper}}
// expected-error@-1{{enums must not contain stored properties}}
@Wrapper(stored: 17)
static var x: Int
}
protocol SomeProtocol {
@Wrapper(stored: 17)
var bar: Int // expected-error{{property 'bar' declared inside a protocol cannot have a wrapper}}
// expected-error@-1{{property in protocol must have explicit { get } or { get set } specifier}}
@Wrapper(stored: 17)
static var x: Int // expected-error{{property 'x' declared inside a protocol cannot have a wrapper}}
// expected-error@-1{{property in protocol must have explicit { get } or { get set } specifier}}
}
struct HasWrapper { }
extension HasWrapper {
@Wrapper(stored: 17)
var inExt: Int // expected-error{{property 'inExt' declared inside an extension cannot have a wrapper}}
// expected-error@-1{{extensions must not contain stored properties}}
@Wrapper(stored: 17)
static var x: Int
}
class ClassWithWrappers {
@Wrapper(stored: 17)
var x: Int
}
class Superclass {
var x: Int = 0
}
class SubclassOfClassWithWrappers: ClassWithWrappers {
override var x: Int {
get { return super.x }
set { super.x = newValue }
}
}
class SubclassWithWrapper: Superclass {
@Wrapper(stored: 17)
override var x: Int { get { return 0 } set { } } // expected-error{{property 'x' with attached wrapper cannot override another property}}
}
class C { }
struct BadCombinations {
@WrapperWithInitialValue
lazy var x: C = C() // expected-error{{property 'x' with a wrapper cannot also be lazy}}
@Wrapper
weak var y: C? // expected-error{{property 'y' with a wrapper cannot also be weak}}
@Wrapper
unowned var z: C // expected-error{{property 'z' with a wrapper cannot also be unowned}}
}
struct MultipleWrappers {
// FIXME: The diagnostics here aren't great. The problem is that we're
// attempting to splice a 'wrappedValue:' argument into the call to Wrapper's
// init, but it doesn't have a matching init. We're then attempting to access
// the nested 'wrappedValue', but Wrapper's 'wrappedValue' is Int.
@Wrapper(stored: 17) // expected-error{{cannot convert value of type 'Int' to expected argument type 'WrapperWithInitialValue<Int>'}}
@WrapperWithInitialValue // expected-error{{extra argument 'wrappedValue' in call}}
var x: Int = 17
@WrapperWithInitialValue // expected-error 2{{property wrapper can only apply to a single variable}}
var (y, z) = (1, 2)
}
// ---------------------------------------------------------------------------
// Initialization
// ---------------------------------------------------------------------------
struct Initialization {
@Wrapper(stored: 17)
var x: Int
@Wrapper(stored: 17)
var x2: Double
@Wrapper(stored: 17)
var x3 = 42 // expected-error {{extra argument 'wrappedValue' in call}}
@Wrapper(stored: 17)
var x4
@WrapperWithInitialValue
var y = true
@WrapperWithInitialValue<Int>
var y2 = true // expected-error{{cannot convert value of type 'Bool' to specified type 'Int'}}
mutating func checkTypes(s: String) {
x2 = s // expected-error{{cannot assign value of type 'String' to type 'Double'}}
x4 = s // expected-error{{cannot assign value of type 'String' to type 'Int'}}
y = s // expected-error{{cannot assign value of type 'String' to type 'Bool'}}
}
}
@propertyWrapper
struct Clamping<V: Comparable> {
var value: V
let min: V
let max: V
init(wrappedValue initialValue: V, min: V, max: V) {
value = initialValue
self.min = min
self.max = max
assert(value >= min && value <= max)
}
var wrappedValue: V {
get { return value }
set {
if newValue < min {
value = min
} else if newValue > max {
value = max
} else {
value = newValue
}
}
}
}
struct Color {
@Clamping(min: 0, max: 255) var red: Int = 127
@Clamping(min: 0, max: 255) var green: Int = 127
@Clamping(min: 0, max: 255) var blue: Int = 127
@Clamping(min: 0, max: 255) var alpha: Int = 255
}
func testColor() {
_ = Color(green: 17)
}
// ---------------------------------------------------------------------------
// Wrapper type formation
// ---------------------------------------------------------------------------
@propertyWrapper
struct IntWrapper {
var wrappedValue: Int
}
@propertyWrapper
struct WrapperForHashable<T: Hashable> { // expected-note{{where 'T' = 'NotHashable'}}
var wrappedValue: T
}
@propertyWrapper
struct WrapperWithTwoParams<T, U> {
var wrappedValue: (T, U)
}
struct NotHashable { }
struct UseWrappersWithDifferentForm {
@IntWrapper
var x: Int
@WrapperForHashable // expected-error {{generic struct 'WrapperForHashable' requires that 'NotHashable' conform to 'Hashable'}}
var y: NotHashable
@WrapperForHashable
var yOkay: Int
@WrapperWithTwoParams
var zOkay: (Int, Float)
@HasNestedWrapper.NestedWrapper // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify}}
var w: Int
@HasNestedWrapper<Double>.NestedWrapper
var wOkay: Int
@HasNestedWrapper.ConcreteNestedWrapper
var wOkay2: Int
}
@propertyWrapper
struct Function<T, U> { // expected-note{{'U' declared as parameter to type 'Function'}}
var wrappedValue: (T) -> U?
}
struct TestFunction {
@Function var f: (Int) -> Float?
// FIXME: This diagnostic should be more specific
@Function var f2: (Int) -> Float // expected-error {{property type '(Int) -> Float' does not match 'wrappedValue' type '(Int) -> U?'}}
// expected-error@-1 {{generic parameter 'U' could not be inferred}}
// expected-note@-2 {{explicitly specify}}
func test() {
let _: Int = _f // expected-error{{cannot convert value of type 'Function<Int, Float>' to specified type 'Int'}}
}
}
// ---------------------------------------------------------------------------
// Nested wrappers
// ---------------------------------------------------------------------------
struct HasNestedWrapper<T> { // expected-note {{'T' declared as parameter to type 'HasNestedWrapper'}}
@propertyWrapper
struct NestedWrapper<U> {
var wrappedValue: U
init(wrappedValue initialValue: U) {
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct ConcreteNestedWrapper {
var wrappedValue: T
init(wrappedValue initialValue: T) {
self.wrappedValue = initialValue
}
}
@NestedWrapper
var y: [T] = []
}
struct UsesNestedWrapper<V> {
@HasNestedWrapper<V>.NestedWrapper
var y: [V]
}
// ---------------------------------------------------------------------------
// Referencing the backing store
// ---------------------------------------------------------------------------
struct BackingStore<T> {
@Wrapper
var x: T
@WrapperWithInitialValue
private var y = true // expected-note{{'y' declared here}}
func getXStorage() -> Wrapper<T> {
return _x
}
func getYStorage() -> WrapperWithInitialValue<Bool> {
return self._y
}
}
func testBackingStore<T>(bs: BackingStore<T>) {
_ = bs.x
_ = bs.y // expected-error{{'y' is inaccessible due to 'private' protection level}}
}
// ---------------------------------------------------------------------------
// Explicitly-specified accessors
// ---------------------------------------------------------------------------
struct WrapperWithAccessors {
@Wrapper // expected-error{{property wrapper cannot be applied to a computed property}}
var x: Int {
return 17
}
}
struct UseWillSetDidSet {
@Wrapper
var x: Int {
willSet {
print(newValue)
}
}
@Wrapper
var y: Int {
didSet {
print(oldValue)
}
}
@Wrapper
var z: Int {
willSet {
print(newValue)
}
didSet {
print(oldValue)
}
}
}
struct DidSetUsesSelf {
@Wrapper
var x: Int {
didSet {
print(self)
}
}
}
// ---------------------------------------------------------------------------
// Mutating/nonmutating
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperWithNonMutatingSetter<Value> {
class Box {
var wrappedValue: Value
init(wrappedValue: Value) {
self.wrappedValue = wrappedValue
}
}
var box: Box
init(wrappedValue initialValue: Value) {
self.box = Box(wrappedValue: initialValue)
}
var wrappedValue: Value {
get { return box.wrappedValue }
nonmutating set { box.wrappedValue = newValue }
}
}
@propertyWrapper
struct WrapperWithMutatingGetter<Value> {
var readCount = 0
var writeCount = 0
var stored: Value
init(wrappedValue initialValue: Value) {
self.stored = initialValue
}
var wrappedValue: Value {
mutating get {
readCount += 1
return stored
}
set {
writeCount += 1
stored = newValue
}
}
}
@propertyWrapper
class ClassWrapper<Value> {
var wrappedValue: Value
init(wrappedValue initialValue: Value) {
self.wrappedValue = initialValue
}
}
struct UseMutatingnessWrappers {
@WrapperWithNonMutatingSetter
var x = true
@WrapperWithMutatingGetter
var y = 17
@WrapperWithNonMutatingSetter // expected-error{{property wrapper can only be applied to a 'var'}}
let z = 3.14159 // expected-note 2{{change 'let' to 'var' to make it mutable}}
@ClassWrapper
var w = "Hello"
}
func testMutatingness() {
var mutable = UseMutatingnessWrappers()
_ = mutable.x
mutable.x = false
_ = mutable.y
mutable.y = 42
_ = mutable.z
mutable.z = 2.71828 // expected-error{{cannot assign to property: 'z' is a 'let' constant}}
_ = mutable.w
mutable.w = "Goodbye"
let nonmutable = UseMutatingnessWrappers() // expected-note 2{{change 'let' to 'var' to make it mutable}}
// Okay due to nonmutating setter
_ = nonmutable.x
nonmutable.x = false
_ = nonmutable.y // expected-error{{cannot use mutating getter on immutable value: 'nonmutable' is a 'let' constant}}
nonmutable.y = 42 // expected-error{{cannot use mutating getter on immutable value: 'nonmutable' is a 'let' constant}}
_ = nonmutable.z
nonmutable.z = 2.71828 // expected-error{{cannot assign to property: 'z' is a 'let' constant}}
// Okay due to implicitly nonmutating setter
_ = nonmutable.w
nonmutable.w = "World"
}
// ---------------------------------------------------------------------------
// Access control
// ---------------------------------------------------------------------------
struct HasPrivateWrapper<T> {
@propertyWrapper
private struct PrivateWrapper<U> { // expected-note{{type declared here}}
var wrappedValue: U
init(wrappedValue initialValue: U) {
self.wrappedValue = initialValue
}
}
@PrivateWrapper
var y: [T] = []
// expected-error@-1{{property must be declared private because its property wrapper type uses a private type}}
// Okay to reference private entities from a private property
@PrivateWrapper
private var z: [T]
}
public struct HasUsableFromInlineWrapper<T> {
@propertyWrapper
struct InternalWrapper<U> { // expected-note{{type declared here}}
var wrappedValue: U
init(wrappedValue initialValue: U) {
self.wrappedValue = initialValue
}
}
@InternalWrapper
@usableFromInline
var y: [T] = []
// expected-error@-1{{property wrapper type referenced from a '@usableFromInline' property must be '@usableFromInline' or public}}
}
@propertyWrapper
class Box<Value> {
private(set) var wrappedValue: Value
init(wrappedValue initialValue: Value) {
self.wrappedValue = initialValue
}
}
struct UseBox {
@Box
var x = 17 // expected-note{{'_x' declared here}}
}
func testBox(ub: UseBox) {
_ = ub.x
ub.x = 5 // expected-error{{cannot assign to property: 'x' is a get-only property}}
var mutableUB = ub
mutableUB = ub
}
func backingVarIsPrivate(ub: UseBox) {
_ = ub._x // expected-error{{'_x' is inaccessible due to 'private' protection level}}
}
// ---------------------------------------------------------------------------
// Memberwise initializers
// ---------------------------------------------------------------------------
struct MemberwiseInits<T> {
@Wrapper
var x: Bool
@WrapperWithInitialValue
var y: T
}
func testMemberwiseInits() {
// expected-error@+1{{type '(Wrapper<Bool>, Double) -> MemberwiseInits<Double>'}}
let _: Int = MemberwiseInits<Double>.init
_ = MemberwiseInits(x: Wrapper(stored: true), y: 17)
}
struct DefaultedMemberwiseInits {
@Wrapper(stored: true)
var x: Bool
@WrapperWithInitialValue
var y: Int = 17
@WrapperWithInitialValue(wrappedValue: 17)
var z: Int
@WrapperWithDefaultInit
var w: Int
@WrapperWithDefaultInit
var optViaDefaultInit: Int?
@WrapperWithInitialValue
var optViaInitialValue: Int?
}
struct CannotDefaultMemberwiseOptionalInit { // expected-note{{'init(x:)' declared here}}
@Wrapper
var x: Int?
}
func testDefaultedMemberwiseInits() {
_ = DefaultedMemberwiseInits()
_ = DefaultedMemberwiseInits(
x: Wrapper(stored: false),
y: 42,
z: WrapperWithInitialValue(wrappedValue: 42))
_ = DefaultedMemberwiseInits(y: 42)
_ = DefaultedMemberwiseInits(x: Wrapper(stored: false))
_ = DefaultedMemberwiseInits(z: WrapperWithInitialValue(wrappedValue: 42))
_ = DefaultedMemberwiseInits(w: WrapperWithDefaultInit())
_ = DefaultedMemberwiseInits(optViaDefaultInit: WrapperWithDefaultInit())
_ = DefaultedMemberwiseInits(optViaInitialValue: nil)
_ = DefaultedMemberwiseInits(optViaInitialValue: 42)
_ = CannotDefaultMemberwiseOptionalInit() // expected-error{{missing argument for parameter 'x' in call}}
_ = CannotDefaultMemberwiseOptionalInit(x: Wrapper(stored: nil))
}
// ---------------------------------------------------------------------------
// Default initializers
// ---------------------------------------------------------------------------
struct DefaultInitializerStruct {
@Wrapper(stored: true)
var x
@WrapperWithInitialValue
var y: Int = 10
}
struct NoDefaultInitializerStruct { // expected-note{{'init(x:)' declared here}}
@Wrapper
var x: Bool
}
class DefaultInitializerClass {
@Wrapper(stored: true)
var x
@WrapperWithInitialValue
final var y: Int = 10
}
class NoDefaultInitializerClass { // expected-error{{class 'NoDefaultInitializerClass' has no initializers}}
@Wrapper
final var x: Bool // expected-note{{stored property 'x' without initial value prevents synthesized initializers}}
}
func testDefaultInitializers() {
_ = DefaultInitializerStruct()
_ = DefaultInitializerClass()
_ = NoDefaultInitializerStruct() // expected-error{{missing argument for parameter 'x' in call}}
}
struct DefaultedPrivateMemberwiseLets {
@Wrapper(stored: true)
private var x: Bool
@WrapperWithInitialValue
var y: Int = 17
@WrapperWithInitialValue(wrappedValue: 17)
private var z: Int
}
func testDefaultedPrivateMemberwiseLets() {
_ = DefaultedPrivateMemberwiseLets()
_ = DefaultedPrivateMemberwiseLets(y: 42)
_ = DefaultedPrivateMemberwiseLets(x: Wrapper(stored: false)) // expected-error{{argument passed to call that takes no arguments}}
}
// ---------------------------------------------------------------------------
// Storage references
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperWithStorageRef<T> {
var wrappedValue: T
var projectedValue: Wrapper<T> {
return Wrapper(stored: wrappedValue)
}
}
extension Wrapper {
var wrapperOnlyAPI: Int { return 17 }
}
struct TestStorageRef {
@WrapperWithStorageRef var x: Int // expected-note{{'_x' declared here}}
init(x: Int) {
self._x = WrapperWithStorageRef(wrappedValue: x)
}
mutating func test() {
let _: Wrapper = $x
let i = $x.wrapperOnlyAPI
let _: Int = i
// x is mutable, $x is not
x = 17
$x = Wrapper(stored: 42) // expected-error{{cannot assign to property: '$x' is immutable}}
}
}
func testStorageRef(tsr: TestStorageRef) {
let _: Wrapper = tsr.$x
_ = tsr._x // expected-error{{'_x' is inaccessible due to 'private' protection level}}
}
struct TestStorageRefPrivate {
@WrapperWithStorageRef private(set) var x: Int
init() {
self._x = WrapperWithStorageRef(wrappedValue: 5)
}
}
func testStorageRefPrivate() {
var tsr = TestStorageRefPrivate()
let a = tsr.$x // okay, getter is internal
tsr.$x = a // expected-error{{cannot assign to property: '$x' is immutable}}
}
// rdar://problem/50873275 - crash when using wrapper with projectedValue in
// generic type.
@propertyWrapper
struct InitialValueWrapperWithStorageRef<T> {
var wrappedValue: T
init(wrappedValue initialValue: T) {
wrappedValue = initialValue
}
var projectedValue: Wrapper<T> {
return Wrapper(stored: wrappedValue)
}
}
struct TestGenericStorageRef<T> {
struct Inner { }
@InitialValueWrapperWithStorageRef var inner: Inner = Inner()
}
// Wiring up the _projectedValueProperty attribute.
struct TestProjectionValuePropertyAttr {
@_projectedValueProperty(wrapperA)
@WrapperWithStorageRef var a: String
var wrapperA: Wrapper<String> {
Wrapper(stored: "blah")
}
@_projectedValueProperty(wrapperB) // expected-error{{could not find projection value property 'wrapperB'}}
@WrapperWithStorageRef var b: String
}
// ---------------------------------------------------------------------------
// Misc. semantic issues
// ---------------------------------------------------------------------------
@propertyWrapper
struct BrokenLazy { }
// expected-error@-1{{property wrapper type 'BrokenLazy' does not contain a non-static property named 'wrappedValue'}}
struct S {
@BrokenLazy
var wrappedValue: Int
}
@propertyWrapper
struct DynamicSelfStruct {
var wrappedValue: Self { self } // okay
var projectedValue: Self { self } // okay
}
@propertyWrapper
class DynamicSelf {
var wrappedValue: Self { self } // expected-error {{property wrapper wrapped value cannot have dynamic Self type}}
var projectedValue: Self? { self } // expected-error {{property wrapper projected value cannot have dynamic Self type}}
}
struct UseDynamicSelfWrapper {
@DynamicSelf() var value
}
// ---------------------------------------------------------------------------
// Invalid redeclaration
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperWithProjectedValue<T> {
var wrappedValue: T
var projectedValue: T { return wrappedValue }
}
class TestInvalidRedeclaration1 {
@WrapperWithProjectedValue var i = 17
// expected-note@-1 {{'i' previously declared here}}
// expected-note@-2 {{'$i' synthesized for property wrapper projected value}}
// expected-note@-3 {{'_i' synthesized for property wrapper backing storage}}
@WrapperWithProjectedValue var i = 39
// expected-error@-1 {{invalid redeclaration of 'i'}}
// expected-error@-2 {{invalid redeclaration of synthesized property '$i'}}
// expected-error@-3 {{invalid redeclaration of synthesized property '_i'}}
}
// SR-12839
struct TestInvalidRedeclaration2 {
var _foo1 = 123 // expected-error {{invalid redeclaration of synthesized property '_foo1'}}
@WrapperWithInitialValue var foo1 = 123 // expected-note {{'_foo1' synthesized for property wrapper backing storage}}
}
struct TestInvalidRedeclaration3 {
@WrapperWithInitialValue var foo1 = 123 // expected-note {{'_foo1' synthesized for property wrapper backing storage}}
var _foo1 = 123 // expected-error {{invalid redeclaration of synthesized property '_foo1'}}
}
// Diagnose when wrapped property uses the name we use for lazy variable storage property.
struct TestInvalidRedeclaration4 {
@WrapperWithProjectedValue var __lazy_storage_$_foo: Int
// expected-error@-1 {{invalid redeclaration of synthesized property '$__lazy_storage_$_foo'}}
// expected-note@-2 {{'$__lazy_storage_$_foo' synthesized for property wrapper projected value}}
lazy var foo = 1
}
// ---------------------------------------------------------------------------
// Closures in initializers
// ---------------------------------------------------------------------------
struct UsesExplicitClosures {
@WrapperAcceptingAutoclosure(body: { 42 })
var x: Int
@WrapperAcceptingAutoclosure(body: { return 42 })
var y: Int
}
// ---------------------------------------------------------------------------
// Enclosing instance diagnostics
// ---------------------------------------------------------------------------
@propertyWrapper
struct Observable<Value> {
private var stored: Value
init(wrappedValue: Value) {
self.stored = wrappedValue
}
@available(*, unavailable, message: "must be in a class")
var wrappedValue: Value { // expected-note{{'wrappedValue' has been explicitly marked unavailable here}}
get { fatalError("called wrappedValue getter") }
set { fatalError("called wrappedValue setter") }
}
static subscript<EnclosingSelf>(
_enclosingInstance observed: EnclosingSelf,
wrapped wrappedKeyPath: ReferenceWritableKeyPath<EnclosingSelf, Value>,
storage storageKeyPath: ReferenceWritableKeyPath<EnclosingSelf, Self>
) -> Value {
get {
observed[keyPath: storageKeyPath].stored
}
set {
observed[keyPath: storageKeyPath].stored = newValue
}
}
}
struct MyObservedValueType {
@Observable // expected-error{{'wrappedValue' is unavailable: must be in a class}}
var observedProperty = 17
}
// ---------------------------------------------------------------------------
// Miscellaneous bugs
// ---------------------------------------------------------------------------
// rdar://problem/50822051 - compiler assertion / hang
@propertyWrapper
struct PD<Value> {
var wrappedValue: Value
init<A>(wrappedValue initialValue: Value, a: A) {
self.wrappedValue = initialValue
}
}
struct TestPD {
@PD(a: "foo") var foo: Int = 42
}
protocol P { }
@propertyWrapper
struct WrapperRequiresP<T: P> {
var wrappedValue: T
var projectedValue: T { return wrappedValue }
}
struct UsesWrapperRequiringP {
// expected-note@-1{{in declaration of}}
@WrapperRequiresP var x.: UsesWrapperRequiringP
// expected-error@-1{{expected member name following '.'}}
// expected-error@-2{{expected declaration}}
// expected-error@-3{{type annotation missing in pattern}}
}
// SR-10899 / rdar://problem/51588022
@propertyWrapper
struct SR_10899_Wrapper {
var wrappedValue: String { "hi" }
}
struct SR_10899_Usage {
@SR_10899_Wrapper var thing: Bool // expected-error{{property type 'Bool' does not match 'wrappedValue' type 'String'}}
}
// SR-11061 / rdar://problem/52593304 assertion with DeclContext mismatches
class SomeValue {
@SomeA(closure: { $0 }) var some: Int = 100
}
@propertyWrapper
struct SomeA<T> {
var wrappedValue: T
let closure: (T) -> (T)
init(wrappedValue initialValue: T, closure: @escaping (T) -> (T)) {
self.wrappedValue = initialValue
self.closure = closure
}
}
// rdar://problem/51989272 - crash when the property wrapper is a generic type
// alias
typealias Alias<T> = WrapperWithInitialValue<T>
struct TestAlias {
@Alias var foo = 17
}
// rdar://problem/52969503 - crash due to invalid source ranges in ill-formed
// code.
@propertyWrapper
struct Wrap52969503<T> {
var wrappedValue: T
init(blah: Int, wrappedValue: T) { }
}
struct Test52969503 {
@Wrap52969503(blah: 5) var foo: Int = 1 // expected-error{{argument 'blah' must precede argument 'wrappedValue'}}
}
//
// ---------------------------------------------------------------------------
// Property wrapper composition
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperA<Value> {
var wrappedValue: Value
init(wrappedValue initialValue: Value) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperB<Value> {
var wrappedValue: Value
init(wrappedValue initialValue: Value) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperC<Value> { // expected-note {{'Value' declared as parameter to type 'WrapperC'}}
var wrappedValue: Value?
init(wrappedValue initialValue: Value?) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperD<Value, X, Y> {
var wrappedValue: Value
}
@propertyWrapper
struct WrapperE<Value> {
var wrappedValue: Value
}
struct TestComposition {
@WrapperA @WrapperB @WrapperC var p1: Int?
@WrapperA @WrapperB @WrapperC var p2 = "Hello"
@WrapperD<WrapperE, Int, String> @WrapperE var p3: Int?
@WrapperD<WrapperC, Int, String> @WrapperC var p4: Int?
@WrapperD<WrapperC, Int, String> @WrapperE var p5: Int // expected-error{{generic parameter 'Value' could not be inferred}}
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}}
// expected-error@-2 {{composed wrapper type 'WrapperE<Int>' does not match type of 'WrapperD<WrapperC<Value>, Int, String>.wrappedValue', which is 'WrapperC<Value>'}}
@Wrapper<String> @Wrapper var value: Int // expected-error{{composed wrapper type 'Wrapper<Int>' does not match type of 'Wrapper<String>.wrappedValue', which is 'String'}}
func triggerErrors(d: Double) { // expected-note 6 {{mark method 'mutating' to make 'self' mutable}} {{2-2=mutating }}
p1 = d // expected-error{{cannot assign value of type 'Double' to type 'Int?'}} {{8-8=Int(}} {{9-9=)}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
p2 = d // expected-error{{cannot assign value of type 'Double' to type 'String?'}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
// TODO(diagnostics): Looks like source range for 'd' here is reported as starting at 10, but it should be 8
p3 = d // expected-error{{cannot assign value of type 'Double' to type 'Int?'}} {{10-10=Int(}} {{11-11=)}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
_p1 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperA<WrapperB<WrapperC<Int>>>'}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
_p2 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperA<WrapperB<WrapperC<String>>>'}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
_p3 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperD<WrapperE<Int?>, Int, String>'}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
}
}
// ---------------------------------------------------------------------------
// Property wrapper composition type inference
// ---------------------------------------------------------------------------
protocol DefaultValue {
static var defaultValue: Self { get }
}
extension Int: DefaultValue {
static var defaultValue: Int { 0 }
}
struct TestCompositionTypeInference {
@propertyWrapper
struct A<Value: DefaultValue> {
var wrappedValue: Value
init(wrappedValue: Value = .defaultValue, key: String) {
self.wrappedValue = wrappedValue
}
}
@propertyWrapper
struct B<Value: DefaultValue>: DefaultValue {
var wrappedValue: Value
init(wrappedValue: Value = .defaultValue) {
self.wrappedValue = wrappedValue
}
static var defaultValue: B<Value> { B() }
}
// All of these are okay
@A(key: "b") @B
var a: Int = 0
@A(key: "b") @B
var b: Int
@A(key: "c") @B @B
var c: Int
}
// ---------------------------------------------------------------------------
// Missing Property Wrapper Unwrap Diagnostics
// ---------------------------------------------------------------------------
@propertyWrapper
struct Foo<T> { // expected-note {{arguments to generic parameter 'T' ('W' and 'Int') are expected to be equal}}
var wrappedValue: T {
get {
fatalError("boom")
}
set {
}
}
var prop: Int = 42
func foo() {}
func bar(x: Int) {}
subscript(q: String) -> Int {
get { return 42 }
set { }
}
subscript(x x: Int) -> Int {
get { return 42 }
set { }
}
subscript(q q: String, a: Int) -> Bool {
get { return false }
set { }
}
}
extension Foo : Equatable where T : Equatable {
static func == (lhs: Foo, rhs: Foo) -> Bool {
lhs.wrappedValue == rhs.wrappedValue
}
}
extension Foo : Hashable where T : Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(wrappedValue)
}
}
@propertyWrapper
struct Bar<T, V> {
var wrappedValue: T
func bar() {}
// TODO(diagnostics): We need to figure out what to do about subscripts.
// The problem standing in our way - keypath application choice
// is always added to results even if it's not applicable.
}
@propertyWrapper
struct Baz<T> {
var wrappedValue: T
func onPropertyWrapper() {}
var projectedValue: V {
return V()
}
}
extension Bar where V == String { // expected-note {{where 'V' = 'Bool'}}
func barWhereVIsString() {}
}
struct V {
func onProjectedValue() {}
}
struct W {
func onWrapped() {}
}
struct MissingPropertyWrapperUnwrap {
@Foo var w: W
@Foo var x: Int
@Bar<Int, Bool> var y: Int
@Bar<Int, String> var z: Int
@Baz var usesProjectedValue: W
func a<T>(_: Foo<T>) {}
func a<T>(named: Foo<T>) {}
func b(_: Foo<Int>) {}
func c(_: V) {}
func d(_: W) {}
func e(_: Foo<W>) {}
subscript<T : Hashable>(takesFoo x: Foo<T>) -> Foo<T> { x }
func baz() {
self.x.foo() // expected-error {{referencing instance method 'foo()' requires wrapper 'Foo<Int>'}}{{10-10=_}}
self.x.prop // expected-error {{referencing property 'prop' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x.bar(x: 42) // expected-error {{referencing instance method 'bar(x:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.y.bar() // expected-error {{referencing instance method 'bar()' requires wrapper 'Bar<Int, Bool>'}}{{10-10=_}}
self.y.barWhereVIsString() // expected-error {{referencing instance method 'barWhereVIsString()' requires wrapper 'Bar<Int, Bool>'}}{{10-10=_}}
// expected-error@-1 {{referencing instance method 'barWhereVIsString()' on 'Bar' requires the types 'Bool' and 'String' be equivalent}}
self.z.barWhereVIsString() // expected-error {{referencing instance method 'barWhereVIsString()' requires wrapper 'Bar<Int, String>'}}{{10-10=_}}
self.usesProjectedValue.onPropertyWrapper() // expected-error {{referencing instance method 'onPropertyWrapper()' requires wrapper 'Baz<W>'}}{{10-10=_}}
self._w.onWrapped() // expected-error {{referencing instance method 'onWrapped()' requires wrapped value of type 'W'}}{{10-11=}}
self.usesProjectedValue.onProjectedValue() // expected-error {{referencing instance method 'onProjectedValue()' requires wrapper 'V'}}{{10-10=$}}
self.$usesProjectedValue.onWrapped() // expected-error {{referencing instance method 'onWrapped()' requires wrapped value of type 'W'}}{{10-11=}}
self._usesProjectedValue.onWrapped() // expected-error {{referencing instance method 'onWrapped()' requires wrapped value of type 'W'}}{{10-11=}}
a(self.w) // expected-error {{cannot convert value 'w' of type 'W' to expected type 'Foo<W>', use wrapper instead}}{{12-12=_}}
b(self.x) // expected-error {{cannot convert value 'x' of type 'Int' to expected type 'Foo<Int>', use wrapper instead}}{{12-12=_}}
b(self.w) // expected-error {{cannot convert value of type 'W' to expected argument type 'Foo<Int>'}}
e(self.w) // expected-error {{cannot convert value 'w' of type 'W' to expected type 'Foo<W>', use wrapper instead}}{{12-12=_}}
b(self._w) // expected-error {{cannot convert value of type 'Foo<W>' to expected argument type 'Foo<Int>'}}
c(self.usesProjectedValue) // expected-error {{cannot convert value 'usesProjectedValue' of type 'W' to expected type 'V', use wrapper instead}}{{12-12=$}}
d(self.$usesProjectedValue) // expected-error {{cannot convert value '$usesProjectedValue' of type 'V' to expected type 'W', use wrapped value instead}}{{12-13=}}
d(self._usesProjectedValue) // expected-error {{cannot convert value '_usesProjectedValue' of type 'Baz<W>' to expected type 'W', use wrapped value instead}}{{12-13=}}
self.x["ultimate question"] // expected-error {{referencing subscript 'subscript(_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x["ultimate question"] = 42 // expected-error {{referencing subscript 'subscript(_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[x: 42] // expected-error {{referencing subscript 'subscript(x:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[x: 42] = 0 // expected-error {{referencing subscript 'subscript(x:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[q: "ultimate question", 42] // expected-error {{referencing subscript 'subscript(q:_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[q: "ultimate question", 42] = true // expected-error {{referencing subscript 'subscript(q:_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
// SR-11476
_ = \Self.[takesFoo: self.x] // expected-error {{cannot convert value 'x' of type 'Int' to expected type 'Foo<Int>', use wrapper instead}}{{31-31=_}}
_ = \Foo<W>.[x: self._x] // expected-error {{cannot convert value '_x' of type 'Foo<Int>' to expected type 'Int', use wrapped value instead}} {{26-27=}}
}
}
struct InvalidPropertyDelegateUse {
// TODO(diagnostics): We need to a tailored diagnostic for extraneous arguments in property delegate initialization
@Foo var x: Int = 42 // expected-error@:21 {{argument passed to call that takes no arguments}}
func test() {
self.x.foo() // expected-error {{value of type 'Int' has no member 'foo'}}
}
}
// SR-11060
class SR_11060_Class {
@SR_11060_Wrapper var property: Int = 1234 // expected-error {{missing argument for parameter 'string' in property wrapper initializer; add 'wrappedValue' and 'string' arguments in '@SR_11060_Wrapper(...)'}}
}
@propertyWrapper
struct SR_11060_Wrapper {
var wrappedValue: Int
init(wrappedValue: Int, string: String) { // expected-note {{'init(wrappedValue:string:)' declared here}}
self.wrappedValue = wrappedValue
}
}
// SR-11138
// Check that all possible compositions of nonmutating/mutating accessors
// on wrappers produce wrapped properties with the correct settability and
// mutatiness in all compositions.
@propertyWrapper
struct NonmutatingGetWrapper<T> {
var wrappedValue: T {
nonmutating get { fatalError() }
}
}
@propertyWrapper
struct MutatingGetWrapper<T> {
var wrappedValue: T {
mutating get { fatalError() }
}
}
@propertyWrapper
struct NonmutatingGetNonmutatingSetWrapper<T> {
var wrappedValue: T {
nonmutating get { fatalError() }
nonmutating set { fatalError() }
}
}
@propertyWrapper
struct MutatingGetNonmutatingSetWrapper<T> {
var wrappedValue: T {
mutating get { fatalError() }
nonmutating set { fatalError() }
}
}
@propertyWrapper
struct NonmutatingGetMutatingSetWrapper<T> {
var wrappedValue: T {
nonmutating get { fatalError() }
mutating set { fatalError() }
}
}
@propertyWrapper
struct MutatingGetMutatingSetWrapper<T> {
var wrappedValue: T {
mutating get { fatalError() }
mutating set { fatalError() }
}
}
struct AllCompositionsStruct {
// Should have nonmutating getter, undefined setter
@NonmutatingGetWrapper @NonmutatingGetWrapper
var ngxs_ngxs: Int
// Should be disallowed
@NonmutatingGetWrapper @MutatingGetWrapper // expected-error{{cannot be composed}}
var ngxs_mgxs: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetWrapper @NonmutatingGetNonmutatingSetWrapper
var ngxs_ngns: Int
// Should be disallowed
@NonmutatingGetWrapper @MutatingGetNonmutatingSetWrapper // expected-error{{cannot be composed}}
var ngxs_mgns: Int
// Should have nonmutating getter, undefined setter
@NonmutatingGetWrapper @NonmutatingGetMutatingSetWrapper
var ngxs_ngms: Int
// Should be disallowed
@NonmutatingGetWrapper @MutatingGetMutatingSetWrapper // expected-error{{cannot be composed}}
var ngxs_mgms: Int
////
// Should have mutating getter, undefined setter
@MutatingGetWrapper @NonmutatingGetWrapper
var mgxs_ngxs: Int
// Should be disallowed
@MutatingGetWrapper @MutatingGetWrapper // expected-error{{cannot be composed}}
var mgxs_mgxs: Int
// Should have mutating getter, mutating setter
@MutatingGetWrapper @NonmutatingGetNonmutatingSetWrapper
var mgxs_ngns: Int
// Should be disallowed
@MutatingGetWrapper @MutatingGetNonmutatingSetWrapper // expected-error{{cannot be composed}}
var mgxs_mgns: Int
// Should have mutating getter, undefined setter
@MutatingGetWrapper @NonmutatingGetMutatingSetWrapper
var mgxs_ngms: Int
// Should be disallowed
@MutatingGetWrapper @MutatingGetMutatingSetWrapper // expected-error{{cannot be composed}}
var mgxs_mgms: Int
////
// Should have nonmutating getter, undefined setter
@NonmutatingGetNonmutatingSetWrapper @NonmutatingGetWrapper
var ngns_ngxs: Int
// Should have nonmutating getter, undefined setter
@NonmutatingGetNonmutatingSetWrapper @MutatingGetWrapper
var ngns_mgxs: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var ngns_ngns: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var ngns_mgns: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var ngns_ngms: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @MutatingGetMutatingSetWrapper
var ngns_mgms: Int
////
// Should have mutating getter, undefined setter
@MutatingGetNonmutatingSetWrapper @NonmutatingGetWrapper
var mgns_ngxs: Int
// Should have mutating getter, undefined setter
@MutatingGetNonmutatingSetWrapper @MutatingGetWrapper
var mgns_mgxs: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var mgns_ngns: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var mgns_mgns: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var mgns_ngms: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @MutatingGetMutatingSetWrapper
var mgns_mgms: Int
////
// Should have nonmutating getter, undefined setter
@NonmutatingGetMutatingSetWrapper @NonmutatingGetWrapper
var ngms_ngxs: Int
// Should have mutating getter, undefined setter
@NonmutatingGetMutatingSetWrapper @MutatingGetWrapper
var ngms_mgxs: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetMutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var ngms_ngns: Int
// Should have mutating getter, nonmutating setter
@NonmutatingGetMutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var ngms_mgns: Int
// Should have nonmutating getter, mutating setter
@NonmutatingGetMutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var ngms_ngms: Int
// Should have mutating getter, mutating setter
@NonmutatingGetMutatingSetWrapper @MutatingGetMutatingSetWrapper
var ngms_mgms: Int
////
// Should have mutating getter, undefined setter
@MutatingGetMutatingSetWrapper @NonmutatingGetWrapper
var mgms_ngxs: Int
// Should have mutating getter, undefined setter
@MutatingGetMutatingSetWrapper @MutatingGetWrapper
var mgms_mgxs: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var mgms_ngns: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var mgms_mgns: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var mgms_ngms: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @MutatingGetMutatingSetWrapper
var mgms_mgms: Int
func readonlyContext(x: Int) { // expected-note *{{}}
_ = ngxs_ngxs
// _ = ngxs_mgxs
_ = ngxs_ngns
// _ = ngxs_mgns
_ = ngxs_ngms
// _ = ngxs_mgms
_ = mgxs_ngxs // expected-error{{}}
// _ = mgxs_mgxs
_ = mgxs_ngns // expected-error{{}}
// _ = mgxs_mgns
_ = mgxs_ngms // expected-error{{}}
// _ = mgxs_mgms
_ = ngns_ngxs
_ = ngns_mgxs
_ = ngns_ngns
_ = ngns_mgns
_ = ngns_ngms
_ = ngns_mgms
_ = mgns_ngxs // expected-error{{}}
_ = mgns_mgxs // expected-error{{}}
_ = mgns_ngns // expected-error{{}}
_ = mgns_mgns // expected-error{{}}
_ = mgns_ngms // expected-error{{}}
_ = mgns_mgms // expected-error{{}}
_ = ngms_ngxs
_ = ngms_mgxs // expected-error{{}}
_ = ngms_ngns
_ = ngms_mgns // expected-error{{}}
_ = ngms_ngms
_ = ngms_mgms // expected-error{{}}
_ = mgms_ngxs // expected-error{{}}
_ = mgms_mgxs // expected-error{{}}
_ = mgms_ngns // expected-error{{}}
_ = mgms_mgns // expected-error{{}}
_ = mgms_ngms // expected-error{{}}
_ = mgms_mgms // expected-error{{}}
////
ngxs_ngxs = x // expected-error{{}}
// ngxs_mgxs = x
ngxs_ngns = x
// ngxs_mgns = x
ngxs_ngms = x // expected-error{{}}
// ngxs_mgms = x
mgxs_ngxs = x // expected-error{{}}
// mgxs_mgxs = x
mgxs_ngns = x // expected-error{{}}
// mgxs_mgns = x
mgxs_ngms = x // expected-error{{}}
// mgxs_mgms = x
ngns_ngxs = x // expected-error{{}}
ngns_mgxs = x // expected-error{{}}
ngns_ngns = x
ngns_mgns = x
ngns_ngms = x
ngns_mgms = x
mgns_ngxs = x // expected-error{{}}
mgns_mgxs = x // expected-error{{}}
mgns_ngns = x // expected-error{{}}
mgns_mgns = x // expected-error{{}}
mgns_ngms = x // expected-error{{}}
mgns_mgms = x // expected-error{{}}
ngms_ngxs = x // expected-error{{}}
ngms_mgxs = x // expected-error{{}}
ngms_ngns = x
// FIXME: This ought to be allowed because it's a pure set, so the mutating
// get should not come into play.
ngms_mgns = x // expected-error{{cannot use mutating getter}}
ngms_ngms = x // expected-error{{}}
ngms_mgms = x // expected-error{{}}
mgms_ngxs = x // expected-error{{}}
mgms_mgxs = x // expected-error{{}}
mgms_ngns = x // expected-error{{}}
mgms_mgns = x // expected-error{{}}
mgms_ngms = x // expected-error{{}}
mgms_mgms = x // expected-error{{}}
}
mutating func mutatingContext(x: Int) {
_ = ngxs_ngxs
// _ = ngxs_mgxs
_ = ngxs_ngns
// _ = ngxs_mgns
_ = ngxs_ngms
// _ = ngxs_mgms
_ = mgxs_ngxs
// _ = mgxs_mgxs
_ = mgxs_ngns
// _ = mgxs_mgns
_ = mgxs_ngms
// _ = mgxs_mgms
_ = ngns_ngxs
_ = ngns_mgxs
_ = ngns_ngns
_ = ngns_mgns
_ = ngns_ngms
_ = ngns_mgms
_ = mgns_ngxs
_ = mgns_mgxs
_ = mgns_ngns
_ = mgns_mgns
_ = mgns_ngms
_ = mgns_mgms
_ = ngms_ngxs
_ = ngms_mgxs
_ = ngms_ngns
_ = ngms_mgns
_ = ngms_ngms
_ = ngms_mgms
_ = mgms_ngxs
_ = mgms_mgxs
_ = mgms_ngns
_ = mgms_mgns
_ = mgms_ngms
_ = mgms_mgms
////
ngxs_ngxs = x // expected-error{{}}
// ngxs_mgxs = x
ngxs_ngns = x
// ngxs_mgns = x
ngxs_ngms = x // expected-error{{}}
// ngxs_mgms = x
mgxs_ngxs = x // expected-error{{}}
// mgxs_mgxs = x
mgxs_ngns = x
// mgxs_mgns = x
mgxs_ngms = x // expected-error{{}}
// mgxs_mgms = x
ngns_ngxs = x // expected-error{{}}
ngns_mgxs = x // expected-error{{}}
ngns_ngns = x
ngns_mgns = x
ngns_ngms = x
ngns_mgms = x
mgns_ngxs = x // expected-error{{}}
mgns_mgxs = x // expected-error{{}}
mgns_ngns = x
mgns_mgns = x
mgns_ngms = x
mgns_mgms = x
ngms_ngxs = x // expected-error{{}}
ngms_mgxs = x // expected-error{{}}
ngms_ngns = x
ngms_mgns = x
ngms_ngms = x
ngms_mgms = x
mgms_ngxs = x // expected-error{{}}
mgms_mgxs = x // expected-error{{}}
mgms_ngns = x
mgms_mgns = x
mgms_ngms = x
mgms_mgms = x
}
}
// rdar://problem/54184846 - crash while trying to retrieve wrapper info on l-value base type
func test_missing_method_with_lvalue_base() {
@propertyWrapper
struct Ref<T> {
var wrappedValue: T
}
struct S<T> where T: RandomAccessCollection, T.Element: Equatable {
@Ref var v: T.Element
init(items: T, v: Ref<T.Element>) {
self.v.binding = v // expected-error {{value of type 'T.Element' has no member 'binding'}}
}
}
}
// SR-11288
// Look into the protocols that the type conforms to
// typealias as propertyWrapper //
@propertyWrapper
struct SR_11288_S0 {
var wrappedValue: Int
}
protocol SR_11288_P1 {
typealias SR_11288_Wrapper1 = SR_11288_S0
}
struct SR_11288_S1: SR_11288_P1 {
@SR_11288_Wrapper1 var answer = 42 // Okay
}
// associatedtype as propertyWrapper //
protocol SR_11288_P2 {
associatedtype SR_11288_Wrapper2 = SR_11288_S0
}
struct SR_11288_S2: SR_11288_P2 {
@SR_11288_Wrapper2 var answer = 42 // expected-error {{unknown attribute 'SR_11288_Wrapper2'}}
}
protocol SR_11288_P3 {
associatedtype SR_11288_Wrapper3
}
struct SR_11288_S3: SR_11288_P3 {
typealias SR_11288_Wrapper3 = SR_11288_S0
@SR_11288_Wrapper3 var answer = 42 // Okay
}
// typealias as propertyWrapper in a constrained protocol extension //
protocol SR_11288_P4 {}
extension SR_11288_P4 where Self: AnyObject { // expected-note {{requirement specified as 'Self' : 'AnyObject' [with Self = SR_11288_S4]}}
typealias SR_11288_Wrapper4 = SR_11288_S0
}
struct SR_11288_S4: SR_11288_P4 {
@SR_11288_Wrapper4 var answer = 42 // expected-error {{'Self.SR_11288_Wrapper4' (aka 'SR_11288_S0') requires that 'SR_11288_S4' be a class type}}
}
class SR_11288_C0: SR_11288_P4 {
@SR_11288_Wrapper4 var answer = 42 // Okay
}
// typealias as propertyWrapper in a generic type //
protocol SR_11288_P5 {
typealias SR_11288_Wrapper5 = SR_11288_S0
}
struct SR_11288_S5<T>: SR_11288_P5 {
@SR_11288_Wrapper5 var answer = 42 // Okay
}
// SR-11393
protocol Copyable: AnyObject {
func copy() -> Self
}
@propertyWrapper
struct CopyOnWrite<Value: Copyable> {
init(wrappedValue: Value) {
self.wrappedValue = wrappedValue
}
var wrappedValue: Value
var projectedValue: Value {
mutating get {
if !isKnownUniquelyReferenced(&wrappedValue) {
wrappedValue = wrappedValue.copy()
}
return wrappedValue
}
set {
wrappedValue = newValue
}
}
}
final class CopyOnWriteTest: Copyable {
let a: Int
init(a: Int) {
self.a = a
}
func copy() -> Self {
Self.init(a: a)
}
}
struct CopyOnWriteDemo1 {
@CopyOnWrite var a = CopyOnWriteTest(a: 3)
func foo() { // expected-note{{mark method 'mutating' to make 'self' mutable}}
_ = $a // expected-error{{cannot use mutating getter on immutable value: 'self' is immutable}}
}
}
@propertyWrapper
struct NonMutatingProjectedValueSetWrapper<Value> {
var wrappedValue: Value
var projectedValue: Value {
get { wrappedValue }
nonmutating set { }
}
}
struct UseNonMutatingProjectedValueSet {
@NonMutatingProjectedValueSetWrapper var x = 17
func test() { // expected-note{{mark method 'mutating' to make 'self' mutable}}
$x = 42 // okay
x = 42 // expected-error{{cannot assign to property: 'self' is immutable}}
}
}
// SR-11478
@propertyWrapper
struct SR_11478_W<Value> {
var wrappedValue: Value
}
class SR_11478_C1 {
@SR_11478_W static var bool1: Bool = true // Ok
@SR_11478_W class var bool2: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
@SR_11478_W class final var bool3: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
}
final class SR_11478_C2 {
@SR_11478_W static var bool1: Bool = true // Ok
@SR_11478_W class var bool2: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
@SR_11478_W class final var bool3: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
}
// SR-11381
@propertyWrapper
struct SR_11381_W<T> {
init(wrappedValue: T) {}
var wrappedValue: T {
fatalError()
}
}
struct SR_11381_S {
@SR_11381_W var foo: Int = nil // expected-error {{'nil' is not compatible with expected argument type 'Int'}}
}
// rdar://problem/53349209 - regression in property wrapper inference
struct Concrete1: P {}
@propertyWrapper struct ConcreteWrapper {
var wrappedValue: Concrete1 { get { fatalError() } }
}
struct TestConcrete1 {
@ConcreteWrapper() var s1
func f() {
// Good:
let _: P = self.s1
// Bad:
self.g(s1: self.s1)
// Ugly:
self.g(s1: self.s1 as P)
}
func g(s1: P) {
// ...
}
}
// SR-11477
// Two initializers that can default initialize the wrapper //
@propertyWrapper
struct SR_11477_W1 { // Okay
let name: String
init() {
self.name = "Init"
}
init(name: String = "DefaultParamInit") {
self.name = name
}
var wrappedValue: Int {
get { return 0 }
}
}
// Two initializers with default arguments that can default initialize the wrapper //
@propertyWrapper
struct SR_11477_W2 { // Okay
let name: String
init(anotherName: String = "DefaultParamInit1") {
self.name = anotherName
}
init(name: String = "DefaultParamInit2") {
self.name = name
}
var wrappedValue: Int {
get { return 0 }
}
}
// Single initializer that can default initialize the wrapper //
@propertyWrapper
struct SR_11477_W3 { // Okay
let name: String
init() {
self.name = "Init"
}
var wrappedValue: Int {
get { return 0 }
}
}
// rdar://problem/56213175 - backward compatibility issue with Swift 5.1,
// which unconditionally skipped protocol members.
protocol ProtocolWithWrapper {
associatedtype Wrapper = Float // expected-note{{associated type 'Wrapper' declared here}}
}
struct UsesProtocolWithWrapper: ProtocolWithWrapper {
@Wrapper var foo: Int // expected-warning{{ignoring associated type 'Wrapper' in favor of module-scoped property wrapper 'Wrapper'; please qualify the reference with 'property_wrappers'}}{{4-4=property_wrappers.}}
}
// rdar://problem/56350060 - [Dynamic key path member lookup] Assertion when subscripting with a key path
func test_rdar56350060() {
@propertyWrapper
@dynamicMemberLookup
struct DynamicWrapper<Value> {
var wrappedValue: Value { fatalError() }
subscript<T>(keyPath keyPath: KeyPath<Value, T>) -> DynamicWrapper<T> {
fatalError()
}
subscript<T>(dynamicMember keyPath: KeyPath<Value, T>) -> DynamicWrapper<T> {
return self[keyPath: keyPath] // Ok
}
}
}
// rdar://problem/57411331 - crash due to incorrectly synthesized "nil" default
// argument.
@propertyWrapper
struct Blah<Value> {
init(blah _: Int) { }
var wrappedValue: Value {
let val: Value? = nil
return val!
}
}
struct UseRdar57411331 {
let x = Rdar57411331(other: 5)
}
struct Rdar57411331 {
@Blah(blah: 17) var something: Int?
var other: Int
}
// SR-11994
@propertyWrapper
open class OpenPropertyWrapperWithPublicInit {
public init(wrappedValue: String) { // Okay
self.wrappedValue = wrappedValue
}
open var wrappedValue: String = "Hello, world"
}
// SR-11654
struct SR_11654_S {}
class SR_11654_C {
@Foo var property: SR_11654_S?
}
func sr_11654_generic_func<T>(_ argument: T?) -> T? {
return argument
}
let sr_11654_c = SR_11654_C()
_ = sr_11654_generic_func(sr_11654_c.property) // Okay
// rdar://problem/59471019 - property wrapper initializer requires empty parens
// for default init
@propertyWrapper
struct DefaultableIntWrapper {
var wrappedValue: Int
init() {
self.wrappedValue = 0
}
}
struct TestDefaultableIntWrapper {
@DefaultableIntWrapper var x
@DefaultableIntWrapper() var y
@DefaultableIntWrapper var z: Int
mutating func test() {
x = y
y = z
}
}
@propertyWrapper
public struct NonVisibleImplicitInit {
// expected-error@-1 {{internal initializer 'init()' cannot have more restrictive access than its enclosing property wrapper type 'NonVisibleImplicitInit' (which is public)}}
public var wrappedValue: Bool {
return false
}
}
@propertyWrapper
struct OptionalWrapper<T> {
init() {}
var wrappedValue: T? { nil }
}
struct UseOptionalWrapper {
@OptionalWrapper var p: Int?? // Okay
}
@propertyWrapper
struct WrapperWithFailableInit<Value> {
var wrappedValue: Value
init(_ base: WrapperWithFailableInit<Value>) { fatalError() }
init?(_ base: WrapperWithFailableInit<Value?>) { fatalError() }
}
struct TestInitError {
// FIXME: bad diagnostics when a wrapper does not support init from wrapped value
// expected-error@+2 {{extraneous argument label 'wrappedValue:' in call}}
// expected-error@+1 {{cannot convert value of type 'Int' to specified type 'WrapperWithFailableInit<Int>'}}
@WrapperWithFailableInit var value: Int = 10
}
| apache-2.0 | e5d7cd0e7a485220a76ae30720594336 | 27.052456 | 260 | 0.649254 | 4.200957 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.