repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dander521/2017 | code_language/Swift/Property.playground/Contents.swift | 1 | 4752 | //: Playground - noun: a place where people can play
import UIKit
// Property
/*
存储属性(Stored Properties)
计算属性(Computed Properties)
属性观察器(Property Observers)
全局变量和局部变量(Global and Local Variables)
类型属性(Type Properties)
*/
struct FixedLengthRange {
var firstValue: Int
let length: Int
}
var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3)
class DataImporter {
/*
DataImporter 是一个负责将外部文件中的数据导入的类。
这个类的初始化会消耗不少时间。
*/
var fileName = "data.txt"
// 这里会提供数据导入功能
}
class DataManager {
lazy var importer = DataImporter()
var data = [String]()
// 这里会提供数据管理功能
}
let manager = DataManager()
manager.data.append("Some data")
manager.data.append("Some more data")
// 计算属性
struct Point {
var x = 0.0, y = 0.0
}
struct Size {
var width = 0.0, height = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set(newCenter) {
origin.x = newCenter.x - (size.width / 2)
origin.y = newCenter.y - (size.height / 2)
}
}
}
var square = Rect(origin: Point(x: 0.0, y: 0.0),
size: Size(width: 10.0, height: 10.0))
let initialSquareCenter = square.center
square.center = Point(x: 15.0, y: 15.0)
// 便捷 setter 声明
struct AlternativeRect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set {
origin.x = newValue.x - (size.width / 2)
origin.y = newValue.y - (size.height / 2)
}
}
}
// ReadOnly
struct Cuboid {
var width = 0.0, height = 0.0, depth = 0.0
var volume: Double {
return width * height * depth
}
}
let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0)
print("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)")
// 属性观察器
class StepCounter {
var totalSteps: Int = 0 {
willSet(newTotalSteps) {
print("About to set totalSteps to \(newTotalSteps)")
}
didSet {
if totalSteps > oldValue {
print("Added \(totalSteps - oldValue) steps")
}
}
}
}
let stepCounter = StepCounter()
stepCounter.totalSteps = 200
// About to set totalSteps to 200
// Added 200 steps
stepCounter.totalSteps = 360
// About to set totalSteps to 360
// Added 160 steps
stepCounter.totalSteps = 896
// About to set totalSteps to 896
// Added 536 steps
// 全局变量和局部变量
// 类型属性
struct SomeStructure {
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int {
return 1
}
}
enum SomeEnumeration {
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int {
return 6
}
}
class SomeClass {
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int {
return 27
}
class var overrideableComputedTypeProperty: Int {
return 107
}
}
print(SomeStructure.storedTypeProperty)
// 输出 "Some value."
SomeStructure.storedTypeProperty = "Another value."
print(SomeStructure.storedTypeProperty)
// 输出 "Another value.”
print(SomeEnumeration.computedTypeProperty)
// 输出 "6"
print(SomeClass.computedTypeProperty)
// 输出 "27"
struct AudioChannel {
static let thresholdLevel = 10
static var maxInputLevelForAllChannels = 0
var currentLevel: Int = 0 {
didSet {
if currentLevel > AudioChannel.thresholdLevel {
// 将当前音量限制在阀值之内
currentLevel = AudioChannel.thresholdLevel
}
if currentLevel > AudioChannel.maxInputLevelForAllChannels {
// 存储当前音量作为新的最大输入音量
AudioChannel.maxInputLevelForAllChannels = currentLevel
}
}
}
}
var leftChannel = AudioChannel()
var rightChannel = AudioChannel()
leftChannel.currentLevel = 7
print(leftChannel.currentLevel)
// 输出 "7"
print(AudioChannel.maxInputLevelForAllChannels)
// 输出 "7"
rightChannel.currentLevel = 11
print(rightChannel.currentLevel)
// 输出 "10"
print(AudioChannel.maxInputLevelForAllChannels)
// 输出 "10"
| mit | 7cd16a217c2f1bc283078ea6ac19c081 | 20.910891 | 72 | 0.627203 | 3.703766 | false | false | false | false |
pattypatpat2632/EveryoneGetsToDJ | EveryoneGetsToDJ/SelectionViewController.swift | 1 | 6099 | //
// SelectionViewController.swift
// EveryoneGetsToDJ
//
// Created by Patrick O'Leary on 6/14/17.
// Copyright © 2017 Patrick O'Leary. All rights reserved.
//
import UIKit
import PromiseKit
class SelectionViewController: UIViewController {
let apiClient = ApiClient.sharedInstance
let firManager = FirebaseManager.sharedInstance
var searchActive = false
var selectionsLeft: Int = 5
let imageQueue = OperationQueue()
@IBOutlet weak var activityIndicator: DJActivityIndicatorView!
@IBOutlet weak var selectionsLeftView: SelectionsLeftView!
var tracks = [Track]() {
didSet {
DispatchQueue.main.async {
self.trackTableView.reloadData()
}
}
}
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var trackTableView: DJTableView!
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
hideKeyboardWhenTappedAround()
NotificationCenter.default.addObserver(self, selector: #selector(updateSelectionCount), name: .tracksUpdated, object: nil)
imageQueue.qualityOfService = .userInitiated
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let visibleCells = trackTableView.visibleCells as! [TrackCell]
visibleCells.forEach{$0.updateFavoritedState()}
}
func updateSelectionCount() {
if let tracks = firManager.jukebox?.tracks {
selectionsLeft = 5 - tracks.filter{$0.selectorID == firManager.uid}.count
selectionsLeftView.updateLabel(withValue: selectionsLeft)
}
}
@IBAction func exitTapped(_ sender: Any) {
navigationController?.popToRootViewController(animated: true)
}
}
//MARK: search bar delegate
extension SelectionViewController: UISearchBarDelegate {
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchActive = true
print("search active: \(searchActive)")
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchActive = true
print("search active: \(searchActive)")
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchActive = false
print("search active: \(searchActive)")
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchActive = false
print("search active: \(searchActive)")
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
self.searchActive = false
print("serch active: \(searchActive)")
} else {
self.searchActive = true
print("serch active: \(searchActive)")
if let searchText = searchBar.text {
search(text: searchText)
}
}
}
private func search(text: String) {
indicateActivity()
apiClient.getToken().then { token in
return self.apiClient.query(input: text, withToken: token)
}.then { (tracks) -> Void in
self.tracks = tracks
self.stopActivity()
}.catch{ error in
}
}
}
// MARK: tableview delegate and data source
extension SelectionViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tracks.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "trackCell", for: indexPath) as! TrackCell
cell.track = tracks[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
guard selectionsLeft > 0 else {
selectionsLeftView.flash()
return nil
}
return indexPath
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == trackTableView {
guard let jukeboxID = firManager.jukebox?.id else {return}
firManager.add(track: tracks[indexPath.row], toJukebox: jukeboxID)
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let trackCell = cell as! TrackCell
trackCell.set(image: #imageLiteral(resourceName: "playingDisk"))
if let imageResource = imageResource(from: trackCell.track?.imageURL) {
apiClient.getToken().then{ (token) -> Promise<UIImage> in
self.apiClient.fetch(resource: imageResource, with: token)
}.then(on: DispatchQueue.main, execute: { (image) -> Void in
trackCell.set(image: image)
}).catch { _ in
trackCell.set(image: #imageLiteral(resourceName: "playingDisk"))
}
}
}
private func imageResource(from str: String?) -> Resource<UIImage>? {
guard let urlString = str else {return nil}
guard let url = URL(string: urlString) else {return nil}
let imageResource = Resource(url: url) {data -> UIImage in
if let image = UIImage(data: data) {
return image
} else {
return #imageLiteral(resourceName: "playingDisk")
}
}
return imageResource
}
}
//MARK: activity indicator
extension SelectionViewController {
fileprivate func indicateActivity() {
activityIndicator.isHidden = false
trackTableView.isHidden = true
activityIndicator.startAnimating()
}
fileprivate func stopActivity() {
activityIndicator.stopAnimating()
trackTableView.isHidden = false
}
}
| mit | ff23504ea91419e58cd49d2ba486565c | 32.322404 | 130 | 0.629223 | 5.211966 | false | false | false | false |
Yokong/douyu | douyu/douyu/Classes/Main/Model/CateModel.swift | 1 | 782 | //
// CateModel.swift
// Just的测试
//
// Created by Yoko on 2017/4/26.
// Copyright © 2017年 Yokooll. All rights reserved.
//
import UIKit
class CateModel: NSObject {
var showers = [ShowerModel]()
var room_list: [[String : Any]]? {
didSet {
guard let room = room_list else { return }
for dict in room {
let s = ShowerModel(dict: dict)
self.showers.append(s)
}
}
}
var tag_name: String = ""
var tag_id: Int = 0
var icon_name: String?
override init() {
}
init(dict: [String : Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
| mit | d8f04fcf9591faa0ee19c1e228be2c63 | 19.342105 | 73 | 0.517464 | 3.770732 | false | false | false | false |
evgenyneu/SneakPeekScroll | SneakPeekScroll/iiAutoLayout.swift | 1 | 4106 | //
// Collection of shortcuts to create autolayout constraints.
//
import UIKit
class iiAutolayoutConstraints {
class func fillParent(view: UIView, parentView: UIView, margin: CGFloat = 0, vertically: Bool = false) {
var marginFormat = ""
if margin != 0 {
marginFormat = "-(\(margin))-"
}
var format = "|\(marginFormat)[view]\(marginFormat)|"
if vertically {
format = "V:" + format
}
let constraints = NSLayoutConstraint.constraintsWithVisualFormat(format,
options: [], metrics: nil,
views: ["view": view])
parentView.addConstraints(constraints)
}
// MARK: - Align view next to each other
class func viewsNextToEachOther(views: [UIView],
constraintContainer: UIView, margin: CGFloat = 0,
vertically: Bool = false) -> [NSLayoutConstraint] {
if views.count < 2 { return [] }
var constraints = [NSLayoutConstraint]()
for (index, view) in views.enumerate() {
if index >= views.count - 1 { break }
let viewTwo = views[index + 1]
constraints += twoViewsNextToEachOther(view, viewTwo: viewTwo,
constraintContainer: constraintContainer, margin: margin, vertically: vertically)
}
return constraints
}
class func twoViewsNextToEachOther(viewOne: UIView, viewTwo: UIView,
constraintContainer: UIView, margin: CGFloat = 0,
vertically: Bool = false) -> [NSLayoutConstraint] {
var marginFormat = ""
if margin != 0 {
marginFormat = "-\(margin)-"
}
var format = "[viewOne]\(marginFormat)[viewTwo]"
if vertically {
format = "V:" + format
}
let constraints = NSLayoutConstraint.constraintsWithVisualFormat(format,
options: [], metrics: nil,
views: [ "viewOne": viewOne, "viewTwo": viewTwo ])
constraintContainer.addConstraints(constraints)
return constraints
}
class func equalWidth(viewOne: UIView, viewTwo: UIView, constraintContainer: UIView,
multiplier: CGFloat = 1) -> [NSLayoutConstraint] {
return equalWidthOrHeight(viewOne, viewTwo: viewTwo,
constraintContainer: constraintContainer, isHeight: false, multiplier: multiplier)
}
private class func equalWidthOrHeight(viewOne: UIView, viewTwo: UIView, constraintContainer: UIView,
isHeight: Bool, multiplier: CGFloat = 1) -> [NSLayoutConstraint] {
let layoutAttribute = isHeight ? NSLayoutAttribute.Height : NSLayoutAttribute.Width
let constraint = NSLayoutConstraint(
item: viewOne,
attribute: layoutAttribute,
relatedBy: NSLayoutRelation.Equal,
toItem: viewTwo,
attribute: layoutAttribute,
multiplier: multiplier,
constant: 0)
let constraints = [constraint]
NSLayoutConstraint.activateConstraints(constraints)
return constraints
}
class func alignSameAttributes(item: AnyObject, toItem: AnyObject,
constraintContainer: UIView, attribute: NSLayoutAttribute, margin: CGFloat = 0) -> [NSLayoutConstraint] {
let constraint = NSLayoutConstraint(
item: item,
attribute: attribute,
relatedBy: NSLayoutRelation.Equal,
toItem: toItem,
attribute: attribute,
multiplier: 1,
constant: margin)
constraintContainer.addConstraint(constraint)
return [constraint]
}
class func height(view: UIView, value: CGFloat) -> [NSLayoutConstraint] {
return widthOrHeight(view, value: value, isHeight: true)
}
class func width(view: UIView, value: CGFloat) -> [NSLayoutConstraint] {
return widthOrHeight(view, value: value, isHeight: false)
}
class func widthOrHeight(view: UIView, value: CGFloat, isHeight: Bool) -> [NSLayoutConstraint] {
let layoutAttribute = isHeight ? NSLayoutAttribute.Height : NSLayoutAttribute.Width
let constraint = NSLayoutConstraint(
item: view,
attribute: layoutAttribute,
relatedBy: NSLayoutRelation.Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 1,
constant: value)
view.addConstraint(constraint)
return [constraint]
}
}
| mit | 875a3207ef603daf324cfb4c8f72003e | 27.513889 | 109 | 0.67925 | 4.952955 | false | false | false | false |
pennlabs/penn-mobile-ios | PennMobile/Home/Cells/Post/HomePostCell.swift | 1 | 8799 | //
// HomePostCell.swift
// PennMobile
//
// Created by Josh Doman on 3/1/19.
// Copyright © 2019 PennLabs. All rights reserved.
//
import Foundation
import Kingfisher
final class HomePostCell: UITableViewCell, HomeCellConformable {
static var identifier: String = "homePostCell"
var delegate: ModularTableViewCellDelegate!
var item: ModularTableViewItem! {
didSet {
guard let item = item as? HomePostCellItem else { return }
if item.post.subtitle != nil && subtitleLabel == nil {
self.prepareSubtitleLabel()
} else if item.post.subtitle == nil && subtitleLabel != nil {
subtitleLabel.removeFromSuperview()
subtitleLabel = nil
}
setupCell(with: item)
}
}
var post: Post!
// MARK: Cell Height
static let titleFont: UIFont = UIFont.primaryInformationFont.withSize(18)
static let titleEdgeOffset: CGFloat = 16
static let descriptionFont: UIFont = UIFont(name: "HelveticaNeue", size: 14)!
private static var titleHeightDictionary = [Int: CGFloat]()
private static var subtitleHeightDictionary = [Int: CGFloat]()
static func getCellHeight(for item: ModularTableViewItem) -> CGFloat {
guard let item = item as? HomePostCellItem else { return 0 }
let sourceHeight: CGFloat = item.post.source == nil ? 0 : 26
let imageHeight = getImageHeight()
let width: CGFloat = UIScreen.main.bounds.width - 2 * 20 - 2 * titleEdgeOffset
let titleHeight: CGFloat
if let height = titleHeightDictionary[item.post.id] {
titleHeight = height
} else if let title = item.post.title {
let spacing: CGFloat = item.post.source == nil ? 12 : 8
titleHeight = title.dynamicHeight(font: titleFont, width: width) + spacing
titleHeightDictionary[item.post.id] = titleHeight
} else {
titleHeight = 0.0
}
let subtitleHeight: CGFloat
if let height = subtitleHeightDictionary[item.post.id] {
subtitleHeight = height
} else if let subtitle = item.post.subtitle {
subtitleHeight = subtitle.dynamicHeight(font: descriptionFont, width: width) + 6
subtitleHeightDictionary[item.post.id] = subtitleHeight
} else {
subtitleHeight = 0.0
}
let bottomSpacing: CGFloat = item.post.source == nil && item.post.title == nil ? 0 : Padding.pad
return imageHeight + titleHeight + subtitleHeight + sourceHeight + bottomSpacing + (Padding.pad * 2)
}
// MARK: UI Elements
var cardView: UIView! = UIView()
fileprivate var postImageView: UIImageView!
fileprivate var sourceLabel: UILabel!
fileprivate var titleLabel: UILabel!
fileprivate var subtitleLabel: UILabel!
fileprivate var dateLabel: UILabel!
fileprivate var moreButton: UIButton!
fileprivate var titleTopConstraintToImage: NSLayoutConstraint!
fileprivate var titleTopConstraintToSource: NSLayoutConstraint!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
prepareHomeCell()
prepareUI()
let tapGestureRecognizer = getTapGestureRecognizer()
cardView.addGestureRecognizer(tapGestureRecognizer)
cardView.isUserInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Setup Item
extension HomePostCell {
fileprivate func setupCell(with item: HomePostCellItem) {
self.post = item.post
postImageView.kf.setImage(with: URL(string: item.post.imageUrl)!)
self.sourceLabel.text = post.source
self.titleLabel.text = post.title
self.subtitleLabel?.text = post.subtitle
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd"
self.dateLabel.text = dateFormatter.string(from: post.createdDate) + " - " + dateFormatter.string(from: post.expireDate)
if item.post.source == nil {
titleTopConstraintToSource.isActive = false
titleTopConstraintToImage.isActive = true
} else {
titleTopConstraintToSource.isActive = true
titleTopConstraintToImage.isActive = false
}
if item.post.title == nil && item.post.subtitle == nil {
postImageView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner]
} else {
postImageView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
}
}
}
// MARK: - Gesture Recognizer
extension HomePostCell {
fileprivate func getTapGestureRecognizer() -> UITapGestureRecognizer {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapped(_:)))
tapGestureRecognizer.numberOfTapsRequired = 1
return tapGestureRecognizer
}
@objc fileprivate func handleTapped(_ sender: Any) {
guard let delegate = delegate as? URLSelectable, let url = post.postUrl else { return }
let title = url.replacingOccurrences(of: "http://", with: "").replacingOccurrences(of: "https://", with: "").split(separator: "/").first!
delegate.handleUrlPressed(urlStr: url, title: String(title), item: self.item, shouldLog: true)
}
}
// MARK: - Prepare UI
extension HomePostCell {
fileprivate func prepareUI() {
prepareImageView()
prepareSourceLabel()
prepareTitleLabel()
prepareDateLabel()
}
private func prepareImageView() {
postImageView = UIImageView()
postImageView.layer.cornerRadius = cardView.layer.cornerRadius
postImageView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
postImageView.clipsToBounds = true
postImageView.contentMode = .scaleAspectFill
cardView.addSubview(postImageView)
let height = HomePostCell.getImageHeight()
_ = postImageView.anchor(cardView.topAnchor, left: cardView.leftAnchor, bottom: nil, right: cardView.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: height)
}
fileprivate static func getImageHeight() -> CGFloat {
let cardWidth = UIScreen.main.bounds.width - (2 * HomeViewController.edgeSpacing)
return 0.6 * cardWidth
}
private func prepareSourceLabel() {
sourceLabel = UILabel()
sourceLabel.font = .secondaryInformationFont
sourceLabel.textColor = UIColor.labelSecondary
sourceLabel.numberOfLines = 1
cardView.addSubview(sourceLabel)
_ = sourceLabel.anchor(postImageView.bottomAnchor, left: cardView.leftAnchor, bottom: nil, right: cardView.rightAnchor, topConstant: pad, leftConstant: pad, bottomConstant: 0, rightConstant: pad, widthConstant: 0, heightConstant: 0)
}
private func prepareTitleLabel() {
titleLabel = UILabel()
titleLabel.font = HomeNewsCell.titleFont
titleLabel.numberOfLines = 8
cardView.addSubview(titleLabel)
titleTopConstraintToSource = titleLabel.anchor(sourceLabel.bottomAnchor, left: cardView.leftAnchor, bottom: nil, right: cardView.rightAnchor, topConstant: pad, leftConstant: HomePostCell.titleEdgeOffset, bottomConstant: 0, rightConstant: HomePostCell.titleEdgeOffset, widthConstant: 0, heightConstant: 0)[0]
titleTopConstraintToImage = titleLabel.topAnchor.constraint(equalTo: postImageView.bottomAnchor, constant: pad)
titleTopConstraintToImage.isActive = false
}
fileprivate func prepareSubtitleLabel() {
subtitleLabel = UILabel()
subtitleLabel.font = HomeNewsCell.subtitleFont
subtitleLabel.textColor = UIColor.labelSecondary
subtitleLabel.numberOfLines = 5
cardView.addSubview(subtitleLabel)
_ = subtitleLabel.anchor(titleLabel.bottomAnchor, left: titleLabel.leftAnchor, bottom: nil, right: titleLabel.rightAnchor, topConstant: pad/2, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
}
private func prepareDateLabel() {
dateLabel = UILabel()
dateLabel.font = .secondaryInformationFont
dateLabel.textColor = UIColor.labelSecondary
dateLabel.translatesAutoresizingMaskIntoConstraints = false
cardView.addSubview(dateLabel)
dateLabel.firstBaselineAnchor.constraint(equalTo: sourceLabel.firstBaselineAnchor).isActive = true
dateLabel.rightAnchor.constraint(equalTo: postImageView.rightAnchor, constant: -HomePostCell.titleEdgeOffset).isActive = true
}
}
| mit | 6e62a734dffc2a836081f471a280938d | 40.5 | 315 | 0.688679 | 5.067972 | false | false | false | false |
evgenyneu/SigmaSwiftStatistics | SigmaSwiftStatistics/Skewness.swift | 2 | 2096 | //
// Created by Alan James Salmoni on 19/12/2016.
// Copyright © 2016 Thought Into Design Ltd. All rights reserved.
//
import Foundation
public extension Sigma {
/**
Returns the skewness of the dataset. This implementation is the same as the SKEW function in Excel and Google Docs Sheets.
https://en.wikipedia.org/wiki/Skewness
- parameter values: Array of decimal numbers.
- returns: Skewness based on a sample. Returns nil if the dataset contains less than 3 values. Returns nil if all the values in the dataset are the same.
Formula (LaTeX):
\frac{n}{(n-1)(n-2)}\sum_{i=1}^{n} \frac{(x_i - \bar{x})^3}{s^3}
Example:
Sigma.skewnessA([4, 2.1, 8, 21, 1]) // 1.6994131524
*/
static func skewnessA(_ values: [Double]) -> Double? {
let count = Double(values.count)
if count < 3 { return nil }
guard let moment3 = centralMoment(values, order: 3) else { return nil }
guard let stdDev = standardDeviationSample(values) else { return nil }
if stdDev == 0 { return nil }
return pow(count, 2) / ((count - 1) * (count - 2)) * moment3 / pow(stdDev, 3)
}
/**
Returns the skewness of the dataset. This implementation is the same as in Wolfram Alpha, SKEW.P in Microsoft Excel and `skewness` function in "moments" R package..
https://en.wikipedia.org/wiki/Skewness
- parameter values: Array of decimal numbers.
- returns: Skewness based on a sample. Returns nil if the dataset contains less than 3 values. Returns nil if all the values in the dataset are the same.
Formula (LaTeX):
\frac{1}{n}\sum_{i=1}^{n} \frac{(x_i - \bar{x})^3}{\sigma^3}
Example:
Sigma.skewnessB([4, 2.1, 8, 21, 1]) // 1.1400009992
*/
static func skewnessB(_ values: [Double]) -> Double? {
if values.count < 3 { return nil }
guard let stdDev = standardDeviationPopulation(values) else { return nil }
if stdDev == 0 { return nil }
guard let moment3 = centralMoment(values, order: 3) else { return nil }
return moment3 / pow(stdDev, 3)
}
}
| mit | 85df091392d4cefa40d214534edfee64 | 30.268657 | 166 | 0.643437 | 3.457096 | false | false | false | false |
billdonner/sheetcheats9 | sc9/Tyle.swift | 1 | 3063 | //
// Tyle.swift
// stories
//
// Created by bill donner on 7/9/15.
// Copyright © 2015 shovelreadyapps. All rights reserved.
//
import UIKit
enum TyleError:Error {
case generalFailure
case restoreFailure
}
enum TyleType {
case docPresentor
case urlPresentor
case spacer
}
// MARK: - Tyle internal representation
class Tyle {
var tyleType : TyleType = .docPresentor
var tyleID: Int
var tyleNote: String = ""
var tyleUrl: String = ""
var tyleBpm: String = ""
var tyleDoc: String = ""
var tyleKey: String = ""
var tyleTitle: String = ""
var tyleTextColor: UIColor = Col.r(.collectionSectionText)
var tyleBackColor: UIColor = Col.r(.collectionCellSelectedBackground)
// TODO: a change to any field will cause a change to all
func refresh() {
Globals.saveDataModel ()
}
init(label:String, bpm:String,key:String,docPath:String,url:String, note:String, textColor:UIColor,backColor:UIColor) {
Globals.shared.sequentialTyleID += 1 //generate id
self.tyleID = Globals.shared.sequentialTyleID
self.tyleTitle = label
self.tyleBpm = bpm
self.tyleKey = key
self.tyleUrl = url
self.tyleDoc = docPath
self.tyleBackColor = backColor
self.tyleTextColor = textColor
self.tyleNote = note
}
class func makeNewTile(_ section:String) -> Tyle {
let name = "tile \(Globals.shared.sequentialTyleID)"
let note = "note \(Globals.shared.sequentialTyleID)"
let tyle = Tyle(label: name, bpm: "", key: "", docPath: "", url: "", note: note,
textColor: .white, backColor: .clear)
// match section against headers
// }
return tyle
}
/// External Tiles are used for communicating with watch and today extensions
class func makeExternalTileFromTyle(_ t:Tyle)->ExternalTile {
var o = ExternalTile()
o[K_ExTile_Label] = t.tyleTitle
o[K_ExTile_Key] = t.tyleKey
o[K_ExTile_Bpm] = t.tyleBpm
o[K_ExTile_Note] = t.tyleNote
o[K_ExTile_Url] = t.tyleUrl
o[K_ExTile_Doc] = t.tyleDoc
o[K_ExTile_ID] = "\(t.tyleID)"
o[K_ExTile_Textcolor] = t.tyleTextColor.htmlRGBColor
o[K_ExTile_Backcolor] = t.tyleBackColor == .clear ? "":t.tyleBackColor.htmlRGBColor
return o
}
class func makeTyleFromExternalTile(_ o:ExternalTile) -> Tyle {
//print(o[K_ExTile_Textcolor]! + "|" + o[K_ExTile_Backcolor]!)
let t = Tyle( label: o[K_ExTile_Label]!,
bpm: o[K_ExTile_Bpm]!,
key: o[K_ExTile_Key]!,
docPath: o[K_ExTile_Doc]!,
url: o[K_ExTile_Url]!,
note: o[K_ExTile_Note]!,
textColor:o[K_ExTile_Textcolor]!.hexStringToUIColor,
backColor:o[K_ExTile_Backcolor]! == "" ? .clear : o[K_ExTile_Backcolor]!.hexStringToUIColor)
return t
}
}// struct Tyle
| apache-2.0 | 361018f233660dc5ebc04e899759d062 | 32.648352 | 123 | 0.59079 | 3.539884 | false | false | false | false |
DrabWeb/Azusa | Azusa.Previous/Azusa/Controllers/Music Player/AZMusicPlayerSidebarViewController.swift | 1 | 5725 | //
// AZMusicPlayerSidebarViewController.swift
// Azusa
//
// Created by Ushio on 12/19/16.
//
import Cocoa
/// The view controller for the sidebar of a music player
class AZMusicPlayerSidebarViewController: NSViewController {
/// The outline view for the sidebar of a `AZMusicPlayerViewController`
@IBOutlet weak var sidebarOutlineView: NSOutlineView!
/// The different sections for the sidebar to display
var sidebarSections : [AZMusicPlayerSidebarSection] = [
AZMusicPlayerSidebarSection(title: "Library", items: [
AZMusicPlayerSidebarSectionItem(title: "Recently Added", icon: NSImage(named: "NSSmartBadgeTemplate")!),
AZMusicPlayerSidebarSectionItem(title: "Artists", icon: NSImage(named: "NSSmartBadgeTemplate")!),
AZMusicPlayerSidebarSectionItem(title: "Albums", icon: NSImage(named: "NSSmartBadgeTemplate")!),
AZMusicPlayerSidebarSectionItem(title: "Songs", icon: NSImage(named: "NSSmartBadgeTemplate")!),
AZMusicPlayerSidebarSectionItem(title: "Genres", icon: NSImage(named: "NSSmartBadgeTemplate")!),
AZMusicPlayerSidebarSectionItem(title: "Files", icon: NSImage(named: "NSSmartBadgeTemplate")!)
]),
AZMusicPlayerSidebarSection(title: "Playlists", items: [])
];
override func viewDidLoad() {
super.viewDidLoad();
// Expand all the sidebar items
sidebarOutlineView.expandItem(nil, expandChildren: true);
}
}
extension AZMusicPlayerSidebarViewController: NSOutlineViewDelegate {
func outlineViewSelectionDidChange(_ notification: Notification) {
// If the item at the selected row is a `AZMusicPlayerSidebarSectionItem`...
if let selectedSidebarItem = self.sidebarOutlineView.item(atRow: self.sidebarOutlineView.selectedRow) as? AZMusicPlayerSidebarSectionItem {
}
}
func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
// Set the row height depending on if the row is a section header or section item
if item is AZMusicPlayerSidebarSection {
return 17;
}
else {
return 22;
}
}
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
// If the item is a sidebar section...
if let sidebarSection : AZMusicPlayerSidebarSection = item as? AZMusicPlayerSidebarSection {
// Return the amount items in the section
return sidebarSection.items.count;
}
// If the item isn't a sidebar section...
else {
// Return the amount of sidebar sections
return sidebarSections.count;
}
}
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
// Only allow section headers to expand
return item is AZMusicPlayerSidebarSection;
}
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
// If the item is a sidebar section...
if let sidebarSection : AZMusicPlayerSidebarSection = item as? AZMusicPlayerSidebarSection {
// Return the item in the section at `index`
return sidebarSection.items[index];
}
// If the item isn't a sidebar section...
else {
// Remove the sidebar section at `index`
return sidebarSections[index];
}
}
func outlineView(_ outlineView: NSOutlineView, objectValueFor tableColumn: NSTableColumn?, byItem item: Any?) -> Any? {
// Return the item
return item;
}
}
extension AZMusicPlayerSidebarViewController: NSOutlineViewDataSource {
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
// If the item is a sidebar item...
if let sidebarItem = item as? AZMusicPlayerSidebarItem {
// If the created cell view for the item isn't nil...
if let cellView : NSTableCellView = outlineView.make(withIdentifier: sidebarItem.cellIdentifier(), owner: self) as? NSTableCellView {
// Get the text field of the cell, and if it isn't nil...
if let textField = cellView.textField {
// Set the text field's string value to the item's title
textField.stringValue = sidebarItem.title;
}
// Get the image view of the cell, and if it isn't nil...
if let imageView = cellView.imageView {
// If the item is a sidebar section item...
if let sidebarSectionItem = sidebarItem as? AZMusicPlayerSidebarSectionItem {
// Set the image view's image to the sidebar item's icon
imageView.image = sidebarSectionItem.icon;
// Make sure the image is template
imageView.image?.isTemplate = true;
}
}
// Return the updated cell
return cellView;
}
}
// Default to nil
return nil;
}
func outlineView(_ outlineView: NSOutlineView, shouldSelectItem item: Any) -> Bool {
// Only allow non-section headers to be selected
return !self.outlineView(outlineView, isGroupItem: item);
}
func outlineView(_ outlineView: NSOutlineView, isGroupItem item: Any) -> Bool {
// Return if the item is a section header
return item is AZMusicPlayerSidebarSection;
}
}
| gpl-3.0 | 64b591ccac628c4da56fc95534122a0c | 41.095588 | 147 | 0.625153 | 5.315692 | false | false | false | false |
huonw/swift | stdlib/public/SDK/XPC/XPC.swift | 43 | 2935 | //===----------------------------------------------------------------------===//
//
// 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 XPC
import _SwiftXPCOverlayShims
//===----------------------------------------------------------------------===//
// XPC Types
//===----------------------------------------------------------------------===//
public var XPC_TYPE_CONNECTION: xpc_type_t {
return _swift_xpc_type_CONNECTION()
}
public var XPC_TYPE_ENDPOINT: xpc_type_t {
return _swift_xpc_type_ENDPOINT()
}
public var XPC_TYPE_NULL: xpc_type_t {
return _swift_xpc_type_NULL()
}
public var XPC_TYPE_BOOL: xpc_type_t {
return _swift_xpc_type_BOOL()
}
public var XPC_TYPE_INT64: xpc_type_t {
return _swift_xpc_type_INT64()
}
public var XPC_TYPE_UINT64: xpc_type_t {
return _swift_xpc_type_UINT64()
}
public var XPC_TYPE_DOUBLE: xpc_type_t {
return _swift_xpc_type_DOUBLE()
}
public var XPC_TYPE_DATE: xpc_type_t {
return _swift_xpc_type_DATE()
}
public var XPC_TYPE_DATA: xpc_type_t {
return _swift_xpc_type_DATA()
}
public var XPC_TYPE_STRING: xpc_type_t {
return _swift_xpc_type_STRING()
}
public var XPC_TYPE_UUID: xpc_type_t {
return _swift_xpc_type_UUID()
}
public var XPC_TYPE_FD: xpc_type_t {
return _swift_xpc_type_FD()
}
public var XPC_TYPE_SHMEM: xpc_type_t {
return _swift_xpc_type_SHMEM()
}
public var XPC_TYPE_ARRAY: xpc_type_t {
return _swift_xpc_type_ARRAY()
}
public var XPC_TYPE_DICTIONARY: xpc_type_t {
return _swift_xpc_type_DICTIONARY()
}
public var XPC_TYPE_ERROR: xpc_type_t {
return _swift_xpc_type_ERROR()
}
public var XPC_TYPE_ACTIVITY: xpc_type_t {
return _swift_xpc_type_ACTIVITY()
}
//===----------------------------------------------------------------------===//
// Macros
//===----------------------------------------------------------------------===//
// xpc/xpc.h
public let XPC_ERROR_KEY_DESCRIPTION: UnsafePointer<Int8> = _xpc_error_key_description
public let XPC_EVENT_KEY_NAME: UnsafePointer<Int8> = _xpc_event_key_name
public var XPC_BOOL_TRUE: xpc_object_t {
return _swift_xpc_bool_true()
}
public var XPC_BOOL_FALSE: xpc_object_t {
return _swift_xpc_bool_false()
}
public var XPC_ARRAY_APPEND: size_t {
return -1
}
// xpc/connection.h
public var XPC_ERROR_CONNECTION_INTERRUPTED: xpc_object_t {
return _swift_xpc_connection_interrupted()
}
public var XPC_ERROR_CONNECTION_INVALID: xpc_object_t {
return _swift_xpc_connection_invalid()
}
public var XPC_ERROR_TERMINATION_IMMINENT: xpc_object_t {
return _swift_xpc_connection_termination_imminent()
}
| apache-2.0 | 45b93bed56c1a2de2527006f77ef19ae | 23.663866 | 86 | 0.601022 | 3.27933 | false | false | false | false |
CoderST/XMLYDemo | XMLYDemo/XMLYDemo/Class/Home/Controller/SubViewController/PopularViewController/View/NowLiveCell.swift | 1 | 4448 | //
// NowLiveCell.swift
// XMLYDemo
//
// Created by xiudou on 2016/12/26.
// Copyright © 2016年 CoderST. All rights reserved.
// 现场直播
import UIKit
private let NowLiveSubCellIdentifier = "NowLiveSubCellIdentifier"
class NowLiveCell: UICollectionViewCell {
// MARK:- 属性
var newLiveItemTime : Timer?
fileprivate lazy var collectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
return collectionView
}()
var nowLiveSubItem : [HotSubModel]?{
didSet{
guard let nowLiveSubItem = nowLiveSubItem else { return }
collectionView.reloadData()
// 3.默认滚动到中间某一个位置
let indexPath = IndexPath(item: nowLiveSubItem.count * 10, section: 0)
collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
// 定时器操作
removeTime()
addTime()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.isPagingEnabled = true
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(NowLiveSubCell.self, forCellWithReuseIdentifier: NowLiveSubCellIdentifier)
contentView.addSubview(collectionView)
}
override func layoutSubviews() {
super.layoutSubviews()
//没用snp约束,用了之后发现在调用定时器方法滚动后,会在边缘多出10的间隙!!!????
collectionView.frame = CGRect(x: 10, y: 10, width: stScreenW - 20, height: bounds.height)
let layout = collectionView.collectionViewLayout as!UICollectionViewFlowLayout
print("kkkkkkkkkk",collectionView.frame.size)
layout.itemSize = collectionView.frame.size
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:- UICollectionViewDataSource
extension NowLiveCell : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (nowLiveSubItem?.count ?? 0) * 10000
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cycleCell = collectionView.dequeueReusableCell(withReuseIdentifier: NowLiveSubCellIdentifier, for: indexPath) as! NowLiveSubCell
let focusImagesItem = nowLiveSubItem?[indexPath.item % (nowLiveSubItem?.count ?? 0)]
cycleCell.nowLiveSubItem = focusImagesItem
return cycleCell
}
}
// MARK:- UICollectionViewDelegate
extension NowLiveCell : UICollectionViewDelegate, UICollectionViewDelegateFlowLayout{
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
removeTime()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
addTime()
}
}
// MARK:- 定时器相关
extension NowLiveCell {
// 创建定时器
fileprivate func addTime(){
newLiveItemTime = Timer(timeInterval: 3.0, target: self, selector: #selector(NowLiveCell.scrollToNextPage), userInfo: nil, repeats: true)
RunLoop.main.add(newLiveItemTime!, forMode: RunLoopMode.commonModes)
}
fileprivate func removeTime(){
newLiveItemTime?.invalidate()
newLiveItemTime = nil
}
@objc fileprivate func scrollToNextPage(){
// 获取当前的偏移量
let offSet = collectionView.contentOffset.x
// 即将要滚动的偏移量
let newOffSet = offSet + collectionView.bounds.width
// 开始滚动
collectionView.setContentOffset(CGPoint(x: newOffSet, y: 0), animated: true)
}
}
| mit | 979eda21b2c9d3f4770a16c072652b11 | 30.681481 | 145 | 0.659574 | 5.177966 | false | false | false | false |
JaSpa/swift | test/attr/attr_objc.swift | 2 | 89920 | // RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify %s -swift-version 4
// RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %s -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module -swift-version 4 | %FileCheck %s
// RUN: not %target-swift-frontend -typecheck -dump-ast -disable-objc-attr-requires-foundation-module %s -swift-version 4 2> %t.dump
// RUN: %FileCheck -check-prefix CHECK-DUMP %s < %t.dump
// REQUIRES: objc_interop
import Foundation
class PlainClass {}
struct PlainStruct {}
enum PlainEnum {}
protocol PlainProtocol {} // expected-note {{protocol 'PlainProtocol' declared here}}
enum ErrorEnum : Error {
case failed
}
@objc class Class_ObjC1 {}
protocol Protocol_Class1 : class {} // expected-note {{protocol 'Protocol_Class1' declared here}}
protocol Protocol_Class2 : class {}
@objc protocol Protocol_ObjC1 {}
@objc protocol Protocol_ObjC2 {}
//===--- Subjects of @objc attribute.
@objc extension PlainClass { } // expected-error{{@objc cannot be applied to this declaration}}{{1-7=}}
@objc
var subject_globalVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
var subject_getterSetter: Int {
@objc
get { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
return 0
}
@objc
set { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
}
var subject_global_observingAccessorsVar1: Int = 0 {
@objc
willSet { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
}
@objc
didSet { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
}
}
class subject_getterSetter1 {
var instanceVar1: Int {
@objc
get { // expected-error {{'@objc' getter for non-'@objc' property}}
return 0
}
}
var instanceVar2: Int {
get {
return 0
}
@objc
set { // expected-error {{'@objc' setter for non-'@objc' property}}
}
}
var instanceVar3: Int {
@objc
get { // expected-error {{'@objc' getter for non-'@objc' property}}
return 0
}
@objc
set { // expected-error {{'@objc' setter for non-'@objc' property}}
}
}
var observingAccessorsVar1: Int = 0 {
@objc
willSet { // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-10=}}
}
@objc
didSet { // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-10=}}
}
}
}
class subject_staticVar1 {
@objc
class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}}
@objc
class var staticVar2: Int { return 42 }
}
@objc
func subject_freeFunc() { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-6=}}
@objc
var subject_localVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_nestedFreeFunc() { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
}
@objc
func subject_genericFunc<T>(t: T) { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-6=}}
@objc
var subject_localVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
func subject_funcParam(a: @objc Int) { // expected-error {{attribute can only be applied to declarations, not types}} {{1-1=@objc }} {{27-33=}}
}
@objc // expected-error {{@objc cannot be applied to this declaration}} {{1-7=}}
struct subject_struct {
@objc
var subject_instanceVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
@objc // expected-error {{@objc cannot be applied to this declaration}} {{1-7=}}
struct subject_genericStruct<T> {
@objc
var subject_instanceVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
@objc
class subject_class1 { // no-error
@objc
var subject_instanceVar: Int // no-error
@objc
init() {} // no-error
@objc
func subject_instanceFunc() {} // no-error
}
@objc
class subject_class2 : Protocol_Class1, PlainProtocol { // no-error
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{1-7=}}
class subject_genericClass<T> {
@objc
var subject_instanceVar: Int // no-error
@objc
init() {} // no-error
@objc
func subject_instanceFunc() {} // no_error
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{1-7=}}
class subject_genericClass2<T> : Class_ObjC1 {
@objc
var subject_instanceVar: Int // no-error
@objc
init(foo: Int) {} // no-error
@objc
func subject_instanceFunc() {} // no_error
}
extension subject_genericClass where T : Hashable {
@objc var prop: Int { return 0 } // expected-error{{members of constrained extensions cannot be declared @objc}}
}
extension subject_genericClass {
@objc var extProp: Int { return 0 } // expected-error{{@objc is not supported within extensions of generic classes}}
@objc func extFoo() {} // expected-error{{@objc is not supported within extensions of generic classes}}
}
@objc
enum subject_enum: Int {
@objc // expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}}
case subject_enumElement1
@objc(subject_enumElement2)
case subject_enumElement2
@objc(subject_enumElement3)
case subject_enumElement3, subject_enumElement4 // expected-error {{'@objc' enum case declaration defines multiple enum cases with the same Objective-C name}}{{3-8=}}
@objc // expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}}
case subject_enumElement5, subject_enumElement6
@nonobjc // expected-error {{@nonobjc cannot be applied to this declaration}}
case subject_enumElement7
@objc
init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
enum subject_enum2 {
@objc(subject_enum2Element1)
case subject_enumElement1 // expected-error{{'@objc' enum case is not allowed outside of an '@objc' enum}}{{3-8=}}
}
@objc
protocol subject_protocol1 {
@objc
var subject_instanceVar: Int { get }
@objc
func subject_instanceFunc()
}
@objc protocol subject_protocol2 {} // no-error
// CHECK-LABEL: @objc protocol subject_protocol2 {
@objc protocol subject_protocol3 {} // no-error
// CHECK-LABEL: @objc protocol subject_protocol3 {
@objc
protocol subject_protocol4 : PlainProtocol {} // expected-error {{@objc protocol 'subject_protocol4' cannot refine non-@objc protocol 'PlainProtocol'}}
@objc
protocol subject_protocol5 : Protocol_Class1 {} // expected-error {{@objc protocol 'subject_protocol5' cannot refine non-@objc protocol 'Protocol_Class1'}}
@objc
protocol subject_protocol6 : Protocol_ObjC1 {}
protocol subject_containerProtocol1 {
@objc
var subject_instanceVar: Int { get } // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc
func subject_instanceFunc() // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc
static func subject_staticFunc() // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
@objc
protocol subject_containerObjCProtocol1 {
func func_FunctionReturn1() -> PlainStruct
// expected-error@-1 {{method cannot be a member of an @objc protocol because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
func func_FunctionParam1(a: PlainStruct)
// expected-error@-1 {{method cannot be a member of an @objc protocol because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
func func_Variadic(_: AnyObject...)
// expected-error @-1{{method cannot be a member of an @objc protocol because it has a variadic parameter}}
// expected-note @-2{{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
subscript(a: PlainStruct) -> Int { get }
// expected-error@-1 {{subscript cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
var varNonObjC1: PlainStruct { get }
// expected-error@-1 {{property cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
}
@objc
protocol subject_containerObjCProtocol2 {
init(a: Int)
@objc init(a: Double)
func func1() -> Int
@objc func func1_() -> Int
var instanceVar1: Int { get set }
@objc var instanceVar1_: Int { get set }
subscript(i: Int) -> Int { get set }
@objc subscript(i: String) -> Int { get set}
}
protocol nonObjCProtocol {
@objc func objcRequirement() // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
func concreteContext1() {
@objc
class subject_inConcreteContext {}
}
class ConcreteContext2 {
@objc
class subject_inConcreteContext {}
}
class ConcreteContext3 {
func dynamicSelf1() -> Self { return self }
@objc func dynamicSelf1_() -> Self { return self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func genericParams<T: NSObject>() -> [T] { return [] }
// expected-error@-1{{method cannot be marked @objc because it has generic parameters}}
@objc func returnObjCProtocolMetatype() -> NSCoding.Protocol { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias AnotherNSCoding = NSCoding
typealias MetaNSCoding1 = NSCoding.Protocol
typealias MetaNSCoding2 = AnotherNSCoding.Protocol
@objc func returnObjCAliasProtocolMetatype1() -> AnotherNSCoding.Protocol { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func returnObjCAliasProtocolMetatype2() -> MetaNSCoding1 { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func returnObjCAliasProtocolMetatype3() -> MetaNSCoding2 { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias Composition = NSCopying & NSCoding
@objc func returnCompositionMetatype1() -> Composition.Protocol { return Composition.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func returnCompositionMetatype2() -> (NSCopying & NSCoding).Protocol { return (NSCopying & NSCoding).self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias NSCodingExistential = NSCoding.Type
@objc func metatypeOfExistentialMetatypePram1(a: NSCodingExistential.Protocol) {}
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
@objc func metatypeOfExistentialMetatypePram2(a: NSCoding.Type.Protocol) {}
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
}
func genericContext1<T>(_: T) {
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{3-9=}}
class subject_inGenericContext {} // expected-error{{type 'subject_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{3-9=}}
class subject_inGenericContext2 : Class_ObjC1 {} // expected-error{{type 'subject_inGenericContext2' cannot be nested in generic function 'genericContext1'}}
class subject_constructor_inGenericContext { // expected-error{{type 'subject_constructor_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
init() {} // no-error
}
class subject_var_inGenericContext { // expected-error{{type 'subject_var_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
var subject_instanceVar: Int = 0 // no-error
}
class subject_func_inGenericContext { // expected-error{{type 'subject_func_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
func f() {} // no-error
}
}
class GenericContext2<T> {
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{3-9=}}
class subject_inGenericContext {}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{3-9=}}
class subject_inGenericContext2 : Class_ObjC1 {}
@objc
func f() {} // no-error
}
class GenericContext3<T> {
class MoreNested {
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{5-11=}}
class subject_inGenericContext {}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{5-11=}}
class subject_inGenericContext2 : Class_ObjC1 {}
@objc
func f() {} // no-error
}
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{1-7=}}
class ConcreteSubclassOfGeneric : GenericContext3<Int> {}
extension ConcreteSubclassOfGeneric {
@objc func foo() {} // expected-error {{@objc is not supported within extensions of generic classes}}
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{1-7=}}
class ConcreteSubclassOfGeneric2 : subject_genericClass2<Int> {}
extension ConcreteSubclassOfGeneric2 {
@objc func foo() {} // expected-error {{@objc is not supported within extensions of generic classes}}
}
class subject_subscriptIndexed1 {
@objc
subscript(a: Int) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptIndexed2 {
@objc
subscript(a: Int8) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptIndexed3 {
@objc
subscript(a: UInt8) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed1 {
@objc
subscript(a: String) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed2 {
@objc
subscript(a: Class_ObjC1) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed3 {
@objc
subscript(a: Class_ObjC1.Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed4 {
@objc
subscript(a: Protocol_ObjC1) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed5 {
@objc
subscript(a: Protocol_ObjC1.Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed6 {
@objc
subscript(a: Protocol_ObjC1 & Protocol_ObjC2) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed7 {
@objc
subscript(a: (Protocol_ObjC1 & Protocol_ObjC2).Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptBridgedFloat {
@objc
subscript(a: Float32) -> Int {
get { return 0 }
}
}
class subject_subscriptGeneric<T> {
@objc
subscript(a: Int) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptInvalid2 {
@objc
subscript(a: PlainClass) -> Int {
// expected-error@-1 {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid3 {
@objc
subscript(a: PlainClass.Type) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid4 {
@objc
subscript(a: PlainStruct) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{Swift structs cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid5 {
@objc
subscript(a: PlainEnum) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{enums cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid6 {
@objc
subscript(a: PlainProtocol) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol 'PlainProtocol' is not '@objc'}}
get { return 0 }
}
}
class subject_subscriptInvalid7 {
@objc
subscript(a: Protocol_Class1) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol 'Protocol_Class1' is not '@objc'}}
get { return 0 }
}
}
class subject_subscriptInvalid8 {
@objc
subscript(a: Protocol_Class1 & Protocol_Class2) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol 'Protocol_Class1' is not '@objc'}}
get { return 0 }
}
}
//===--- Tests for @objc inference.
@objc
class infer_instanceFunc1 {
// CHECK-LABEL: @objc class infer_instanceFunc1 {
func func1() {}
// CHECK-LABEL: @objc func func1() {
@objc func func1_() {} // no-error
func func2(a: Int) {}
// CHECK-LABEL: @objc func func2(a: Int) {
@objc func func2_(a: Int) {} // no-error
func func3(a: Int) -> Int {}
// CHECK-LABEL: @objc func func3(a: Int) -> Int {
@objc func func3_(a: Int) -> Int {} // no-error
func func4(a: Int, b: Double) {}
// CHECK-LABEL: @objc func func4(a: Int, b: Double) {
@objc func func4_(a: Int, b: Double) {} // no-error
func func5(a: String) {}
// CHECK-LABEL: @objc func func5(a: String) {
@objc func func5_(a: String) {} // no-error
func func6() -> String {}
// CHECK-LABEL: @objc func func6() -> String {
@objc func func6_() -> String {} // no-error
func func7(a: PlainClass) {}
// CHECK-LABEL: {{^}} func func7(a: PlainClass) {
@objc func func7_(a: PlainClass) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
func func7m(a: PlainClass.Type) {}
// CHECK-LABEL: {{^}} func func7m(a: PlainClass.Type) {
@objc func func7m_(a: PlainClass.Type) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
func func8() -> PlainClass {}
// CHECK-LABEL: {{^}} func func8() -> PlainClass {
@objc func func8_() -> PlainClass {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
func func8m() -> PlainClass.Type {}
// CHECK-LABEL: {{^}} func func8m() -> PlainClass.Type {
@objc func func8m_() -> PlainClass.Type {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
func func9(a: PlainStruct) {}
// CHECK-LABEL: {{^}} func func9(a: PlainStruct) {
@objc func func9_(a: PlainStruct) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
func func10() -> PlainStruct {}
// CHECK-LABEL: {{^}} func func10() -> PlainStruct {
@objc func func10_() -> PlainStruct {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
func func11(a: PlainEnum) {}
// CHECK-LABEL: {{^}} func func11(a: PlainEnum) {
@objc func func11_(a: PlainEnum) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}}
func func12(a: PlainProtocol) {}
// CHECK-LABEL: {{^}} func func12(a: PlainProtocol) {
@objc func func12_(a: PlainProtocol) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
func func13(a: Class_ObjC1) {}
// CHECK-LABEL: @objc func func13(a: Class_ObjC1) {
@objc func func13_(a: Class_ObjC1) {} // no-error
func func14(a: Protocol_Class1) {}
// CHECK-LABEL: {{^}} func func14(a: Protocol_Class1) {
@objc func func14_(a: Protocol_Class1) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}}
func func15(a: Protocol_ObjC1) {}
// CHECK-LABEL: @objc func func15(a: Protocol_ObjC1) {
@objc func func15_(a: Protocol_ObjC1) {} // no-error
func func16(a: AnyObject) {}
// CHECK-LABEL: @objc func func16(a: AnyObject) {
@objc func func16_(a: AnyObject) {} // no-error
func func17(a: @escaping () -> ()) {}
// CHECK-LABEL: {{^}} @objc func func17(a: @escaping () -> ()) {
@objc func func17_(a: @escaping () -> ()) {}
func func18(a: @escaping (Int) -> (), b: Int) {}
// CHECK-LABEL: {{^}} @objc func func18(a: @escaping (Int) -> (), b: Int)
@objc func func18_(a: @escaping (Int) -> (), b: Int) {}
func func19(a: @escaping (String) -> (), b: Int) {}
// CHECK-LABEL: {{^}} @objc func func19(a: @escaping (String) -> (), b: Int) {
@objc func func19_(a: @escaping (String) -> (), b: Int) {}
func func_FunctionReturn1() -> () -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn1() -> () -> () {
@objc func func_FunctionReturn1_() -> () -> () {}
func func_FunctionReturn2() -> (Int) -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn2() -> (Int) -> () {
@objc func func_FunctionReturn2_() -> (Int) -> () {}
func func_FunctionReturn3() -> () -> Int {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn3() -> () -> Int {
@objc func func_FunctionReturn3_() -> () -> Int {}
func func_FunctionReturn4() -> (String) -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn4() -> (String) -> () {
@objc func func_FunctionReturn4_() -> (String) -> () {}
func func_FunctionReturn5() -> () -> String {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn5() -> () -> String {
@objc func func_FunctionReturn5_() -> () -> String {}
func func_ZeroParams1() {}
// CHECK-LABEL: @objc func func_ZeroParams1() {
@objc func func_ZeroParams1a() {} // no-error
func func_OneParam1(a: Int) {}
// CHECK-LABEL: @objc func func_OneParam1(a: Int) {
@objc func func_OneParam1a(a: Int) {} // no-error
func func_TupleStyle1(a: Int, b: Int) {}
// CHECK-LABEL: {{^}} @objc func func_TupleStyle1(a: Int, b: Int) {
@objc func func_TupleStyle1a(a: Int, b: Int) {}
func func_TupleStyle2(a: Int, b: Int, c: Int) {}
// CHECK-LABEL: {{^}} @objc func func_TupleStyle2(a: Int, b: Int, c: Int) {
@objc func func_TupleStyle2a(a: Int, b: Int, c: Int) {}
// Check that we produce diagnostics for every parameter and return type.
@objc func func_MultipleDiags(a: PlainStruct, b: PlainEnum) -> Any {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter 1 cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-error@-3 {{method cannot be marked @objc because the type of the parameter 2 cannot be represented in Objective-C}}
// expected-note@-4 {{non-'@objc' enums cannot be represented in Objective-C}}
@objc func func_UnnamedParam1(_: Int) {} // no-error
@objc func func_UnnamedParam2(_: PlainStruct) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
@objc func func_varParam1(a: AnyObject) {
var a = a
let b = a; a = b
}
func func_varParam2(a: AnyObject) {
var a = a
let b = a; a = b
}
// CHECK-LABEL: @objc func func_varParam2(a: AnyObject) {
}
@objc
class infer_constructor1 {
// CHECK-LABEL: @objc class infer_constructor1
init() {}
// CHECK: @objc init()
init(a: Int) {}
// CHECK: @objc init(a: Int)
init(a: PlainStruct) {}
// CHECK: {{^}} init(a: PlainStruct)
init(malice: ()) {}
// CHECK: @objc init(malice: ())
init(forMurder _: ()) {}
// CHECK: @objc init(forMurder _: ())
}
@objc
class infer_destructor1 {
// CHECK-LABEL: @objc class infer_destructor1
deinit {}
// CHECK: @objc deinit
}
// @!objc
class infer_destructor2 {
// CHECK-LABEL: {{^}}class infer_destructor2
deinit {}
// CHECK: @objc deinit
}
@objc
class infer_instanceVar1 {
// CHECK-LABEL: @objc class infer_instanceVar1 {
init() {}
var instanceVar1: Int
// CHECK: @objc var instanceVar1: Int
var (instanceVar2, instanceVar3): (Int, PlainProtocol)
// CHECK: @objc var instanceVar2: Int
// CHECK: {{^}} var instanceVar3: PlainProtocol
@objc var (instanceVar1_, instanceVar2_): (Int, PlainProtocol)
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
var intstanceVar4: Int {
// CHECK: @objc var intstanceVar4: Int {
get {}
// CHECK-NEXT: @objc get {}
}
var intstanceVar5: Int {
// CHECK: @objc var intstanceVar5: Int {
get {}
// CHECK-NEXT: @objc get {}
set {}
// CHECK-NEXT: @objc set {}
}
@objc var instanceVar5_: Int {
// CHECK: @objc var instanceVar5_: Int {
get {}
// CHECK-NEXT: @objc get {}
set {}
// CHECK-NEXT: @objc set {}
}
var observingAccessorsVar1: Int {
// CHECK: @objc var observingAccessorsVar1: Int {
willSet {}
// CHECK-NEXT: {{^}} final willSet {}
didSet {}
// CHECK-NEXT: {{^}} final didSet {}
}
@objc var observingAccessorsVar1_: Int {
// CHECK: {{^}} @objc var observingAccessorsVar1_: Int {
willSet {}
// CHECK-NEXT: {{^}} final willSet {}
didSet {}
// CHECK-NEXT: {{^}} final didSet {}
}
var var_Int: Int
// CHECK-LABEL: @objc var var_Int: Int
var var_Bool: Bool
// CHECK-LABEL: @objc var var_Bool: Bool
var var_CBool: CBool
// CHECK-LABEL: @objc var var_CBool: CBool
var var_String: String
// CHECK-LABEL: @objc var var_String: String
var var_Float: Float
var var_Double: Double
// CHECK-LABEL: @objc var var_Float: Float
// CHECK-LABEL: @objc var var_Double: Double
var var_Char: UnicodeScalar
// CHECK-LABEL: @objc var var_Char: UnicodeScalar
//===--- Tuples.
var var_tuple1: ()
// CHECK-LABEL: {{^}} var var_tuple1: ()
@objc var var_tuple1_: ()
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{empty tuple type cannot be represented in Objective-C}}
var var_tuple2: Void
// CHECK-LABEL: {{^}} var var_tuple2: Void
@objc var var_tuple2_: Void
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{empty tuple type cannot be represented in Objective-C}}
var var_tuple3: (Int)
// CHECK-LABEL: @objc var var_tuple3: (Int)
@objc var var_tuple3_: (Int) // no-error
var var_tuple4: (Int, Int)
// CHECK-LABEL: {{^}} var var_tuple4: (Int, Int)
@objc var var_tuple4_: (Int, Int)
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{tuples cannot be represented in Objective-C}}
//===--- Stdlib integer types.
var var_Int8: Int8
var var_Int16: Int16
var var_Int32: Int32
var var_Int64: Int64
// CHECK-LABEL: @objc var var_Int8: Int8
// CHECK-LABEL: @objc var var_Int16: Int16
// CHECK-LABEL: @objc var var_Int32: Int32
// CHECK-LABEL: @objc var var_Int64: Int64
var var_UInt8: UInt8
var var_UInt16: UInt16
var var_UInt32: UInt32
var var_UInt64: UInt64
// CHECK-LABEL: @objc var var_UInt8: UInt8
// CHECK-LABEL: @objc var var_UInt16: UInt16
// CHECK-LABEL: @objc var var_UInt32: UInt32
// CHECK-LABEL: @objc var var_UInt64: UInt64
var var_OpaquePointer: OpaquePointer
// CHECK-LABEL: @objc var var_OpaquePointer: OpaquePointer
var var_PlainClass: PlainClass
// CHECK-LABEL: {{^}} var var_PlainClass: PlainClass
@objc var var_PlainClass_: PlainClass
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
var var_PlainStruct: PlainStruct
// CHECK-LABEL: {{^}} var var_PlainStruct: PlainStruct
@objc var var_PlainStruct_: PlainStruct
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
var var_PlainEnum: PlainEnum
// CHECK-LABEL: {{^}} var var_PlainEnum: PlainEnum
@objc var var_PlainEnum_: PlainEnum
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}}
var var_PlainProtocol: PlainProtocol
// CHECK-LABEL: {{^}} var var_PlainProtocol: PlainProtocol
@objc var var_PlainProtocol_: PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
var var_ClassObjC: Class_ObjC1
// CHECK-LABEL: @objc var var_ClassObjC: Class_ObjC1
@objc var var_ClassObjC_: Class_ObjC1 // no-error
var var_ProtocolClass: Protocol_Class1
// CHECK-LABEL: {{^}} var var_ProtocolClass: Protocol_Class1
@objc var var_ProtocolClass_: Protocol_Class1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}}
var var_ProtocolObjC: Protocol_ObjC1
// CHECK-LABEL: @objc var var_ProtocolObjC: Protocol_ObjC1
@objc var var_ProtocolObjC_: Protocol_ObjC1 // no-error
var var_PlainClassMetatype: PlainClass.Type
// CHECK-LABEL: {{^}} var var_PlainClassMetatype: PlainClass.Type
@objc var var_PlainClassMetatype_: PlainClass.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainStructMetatype: PlainStruct.Type
// CHECK-LABEL: {{^}} var var_PlainStructMetatype: PlainStruct.Type
@objc var var_PlainStructMetatype_: PlainStruct.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainEnumMetatype: PlainEnum.Type
// CHECK-LABEL: {{^}} var var_PlainEnumMetatype: PlainEnum.Type
@objc var var_PlainEnumMetatype_: PlainEnum.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainExistentialMetatype: PlainProtocol.Type
// CHECK-LABEL: {{^}} var var_PlainExistentialMetatype: PlainProtocol.Type
@objc var var_PlainExistentialMetatype_: PlainProtocol.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ClassObjCMetatype: Class_ObjC1.Type
// CHECK-LABEL: @objc var var_ClassObjCMetatype: Class_ObjC1.Type
@objc var var_ClassObjCMetatype_: Class_ObjC1.Type // no-error
var var_ProtocolClassMetatype: Protocol_Class1.Type
// CHECK-LABEL: {{^}} var var_ProtocolClassMetatype: Protocol_Class1.Type
@objc var var_ProtocolClassMetatype_: Protocol_Class1.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type
// CHECK-LABEL: @objc var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type
@objc var var_ProtocolObjCMetatype1_: Protocol_ObjC1.Type // no-error
var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type
// CHECK-LABEL: @objc var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type
@objc var var_ProtocolObjCMetatype2_: Protocol_ObjC2.Type // no-error
var var_AnyObject1: AnyObject
var var_AnyObject2: AnyObject.Type
// CHECK-LABEL: @objc var var_AnyObject1: AnyObject
// CHECK-LABEL: @objc var var_AnyObject2: AnyObject.Type
var var_Existential0: Any
// CHECK-LABEL: @objc var var_Existential0: Any
@objc var var_Existential0_: Any
var var_Existential1: PlainProtocol
// CHECK-LABEL: {{^}} var var_Existential1: PlainProtocol
@objc var var_Existential1_: PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
var var_Existential2: PlainProtocol & PlainProtocol
// CHECK-LABEL: {{^}} var var_Existential2: PlainProtocol
@objc var var_Existential2_: PlainProtocol & PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
var var_Existential3: PlainProtocol & Protocol_Class1
// CHECK-LABEL: {{^}} var var_Existential3: PlainProtocol & Protocol_Class1
@objc var var_Existential3_: PlainProtocol & Protocol_Class1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
var var_Existential4: PlainProtocol & Protocol_ObjC1
// CHECK-LABEL: {{^}} var var_Existential4: PlainProtocol & Protocol_ObjC1
@objc var var_Existential4_: PlainProtocol & Protocol_ObjC1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
var var_Existential5: Protocol_Class1
// CHECK-LABEL: {{^}} var var_Existential5: Protocol_Class1
@objc var var_Existential5_: Protocol_Class1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}}
var var_Existential6: Protocol_Class1 & Protocol_Class2
// CHECK-LABEL: {{^}} var var_Existential6: Protocol_Class1 & Protocol_Class2
@objc var var_Existential6_: Protocol_Class1 & Protocol_Class2
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}}
var var_Existential7: Protocol_Class1 & Protocol_ObjC1
// CHECK-LABEL: {{^}} var var_Existential7: Protocol_Class1 & Protocol_ObjC1
@objc var var_Existential7_: Protocol_Class1 & Protocol_ObjC1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}}
var var_Existential8: Protocol_ObjC1
// CHECK-LABEL: @objc var var_Existential8: Protocol_ObjC1
@objc var var_Existential8_: Protocol_ObjC1 // no-error
var var_Existential9: Protocol_ObjC1 & Protocol_ObjC2
// CHECK-LABEL: @objc var var_Existential9: Protocol_ObjC1 & Protocol_ObjC2
@objc var var_Existential9_: Protocol_ObjC1 & Protocol_ObjC2 // no-error
var var_ExistentialMetatype0: Any.Type
var var_ExistentialMetatype1: PlainProtocol.Type
var var_ExistentialMetatype2: (PlainProtocol & PlainProtocol).Type
var var_ExistentialMetatype3: (PlainProtocol & Protocol_Class1).Type
var var_ExistentialMetatype4: (PlainProtocol & Protocol_ObjC1).Type
var var_ExistentialMetatype5: (Protocol_Class1).Type
var var_ExistentialMetatype6: (Protocol_Class1 & Protocol_Class2).Type
var var_ExistentialMetatype7: (Protocol_Class1 & Protocol_ObjC1).Type
var var_ExistentialMetatype8: Protocol_ObjC1.Type
var var_ExistentialMetatype9: (Protocol_ObjC1 & Protocol_ObjC2).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype0: Any.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype1: PlainProtocol.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype2: (PlainProtocol).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype3: (PlainProtocol & Protocol_Class1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype4: (PlainProtocol & Protocol_ObjC1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype5: (Protocol_Class1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype6: (Protocol_Class1 & Protocol_Class2).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype7: (Protocol_Class1 & Protocol_ObjC1).Type
// CHECK-LABEL: @objc var var_ExistentialMetatype8: Protocol_ObjC1.Type
// CHECK-LABEL: @objc var var_ExistentialMetatype9: (Protocol_ObjC1 & Protocol_ObjC2).Type
var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int>
var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool>
var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool>
var var_UnsafeMutablePointer4: UnsafeMutablePointer<String>
var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float>
var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double>
var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer>
var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass>
var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct>
var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum>
var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol>
var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject>
var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type>
var var_UnsafeMutablePointer100: UnsafeMutableRawPointer
var var_UnsafeMutablePointer101: UnsafeMutableRawPointer
var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer4: UnsafeMutablePointer<String>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject>
// CHECK-LABEL: var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type>
// CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer100: UnsafeMutableRawPointer
// CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer101: UnsafeMutableRawPointer
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)>
var var_Optional1: Class_ObjC1?
var var_Optional2: Protocol_ObjC1?
var var_Optional3: Class_ObjC1.Type?
var var_Optional4: Protocol_ObjC1.Type?
var var_Optional5: AnyObject?
var var_Optional6: AnyObject.Type?
var var_Optional7: String?
var var_Optional8: Protocol_ObjC1?
var var_Optional9: Protocol_ObjC1.Type?
var var_Optional10: (Protocol_ObjC1 & Protocol_ObjC2)?
var var_Optional11: (Protocol_ObjC1 & Protocol_ObjC2).Type?
var var_Optional12: OpaquePointer?
var var_Optional13: UnsafeMutablePointer<Int>?
var var_Optional14: UnsafeMutablePointer<Class_ObjC1>?
// CHECK-LABEL: @objc var var_Optional1: Class_ObjC1?
// CHECK-LABEL: @objc var var_Optional2: Protocol_ObjC1?
// CHECK-LABEL: @objc var var_Optional3: Class_ObjC1.Type?
// CHECK-LABEL: @objc var var_Optional4: Protocol_ObjC1.Type?
// CHECK-LABEL: @objc var var_Optional5: AnyObject?
// CHECK-LABEL: @objc var var_Optional6: AnyObject.Type?
// CHECK-LABEL: @objc var var_Optional7: String?
// CHECK-LABEL: @objc var var_Optional8: Protocol_ObjC1?
// CHECK-LABEL: @objc var var_Optional9: Protocol_ObjC1.Type?
// CHECK-LABEL: @objc var var_Optional10: (Protocol_ObjC1 & Protocol_ObjC2)?
// CHECK-LABEL: @objc var var_Optional11: (Protocol_ObjC1 & Protocol_ObjC2).Type?
// CHECK-LABEL: @objc var var_Optional12: OpaquePointer?
// CHECK-LABEL: @objc var var_Optional13: UnsafeMutablePointer<Int>?
// CHECK-LABEL: @objc var var_Optional14: UnsafeMutablePointer<Class_ObjC1>?
var var_ImplicitlyUnwrappedOptional1: Class_ObjC1!
var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1!
var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type!
var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type!
var var_ImplicitlyUnwrappedOptional5: AnyObject!
var var_ImplicitlyUnwrappedOptional6: AnyObject.Type!
var var_ImplicitlyUnwrappedOptional7: String!
var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1!
var var_ImplicitlyUnwrappedOptional9: (Protocol_ObjC1 & Protocol_ObjC2)!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional1: Class_ObjC1!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional5: AnyObject!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional6: AnyObject.Type!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional7: String!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional9: (Protocol_ObjC1 & Protocol_ObjC2)!
var var_Optional_fail1: PlainClass?
var var_Optional_fail2: PlainClass.Type?
var var_Optional_fail3: PlainClass!
var var_Optional_fail4: PlainStruct?
var var_Optional_fail5: PlainStruct.Type?
var var_Optional_fail6: PlainEnum?
var var_Optional_fail7: PlainEnum.Type?
var var_Optional_fail8: PlainProtocol?
var var_Optional_fail10: PlainProtocol?
var var_Optional_fail11: (PlainProtocol & Protocol_ObjC1)?
var var_Optional_fail12: Int?
var var_Optional_fail13: Bool?
var var_Optional_fail14: CBool?
var var_Optional_fail20: AnyObject??
var var_Optional_fail21: AnyObject.Type??
var var_Optional_fail22: ComparisonResult? // a non-bridged imported value type
var var_Optional_fail23: NSRange? // a bridged struct imported from C
// CHECK-NOT: @objc{{.*}}Optional_fail
// CHECK-LABEL: @objc var var_CFunctionPointer_1: @convention(c) () -> ()
var var_CFunctionPointer_1: @convention(c) () -> ()
// CHECK-LABEL: @objc var var_CFunctionPointer_invalid_1: Int
var var_CFunctionPointer_invalid_1: @convention(c) Int // expected-error {{@convention attribute only applies to function types}}
// CHECK-LABEL: {{^}} var var_CFunctionPointer_invalid_2: @convention(c) (PlainStruct) -> Int
var var_CFunctionPointer_invalid_2: @convention(c) (PlainStruct) -> Int // expected-error {{'(PlainStruct) -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}}
// <rdar://problem/20918869> Confusing diagnostic for @convention(c) throws
var var_CFunctionPointer_invalid_3 : @convention(c) (Int) throws -> Int // expected-error {{'(Int) throws -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}}
weak var var_Weak1: Class_ObjC1?
weak var var_Weak2: Protocol_ObjC1?
// <rdar://problem/16473062> weak and unowned variables of metatypes are rejected
//weak var var_Weak3: Class_ObjC1.Type?
//weak var var_Weak4: Protocol_ObjC1.Type?
weak var var_Weak5: AnyObject?
//weak var var_Weak6: AnyObject.Type?
weak var var_Weak7: Protocol_ObjC1?
weak var var_Weak8: (Protocol_ObjC1 & Protocol_ObjC2)?
// CHECK-LABEL: @objc weak var var_Weak1: @sil_weak Class_ObjC1
// CHECK-LABEL: @objc weak var var_Weak2: @sil_weak Protocol_ObjC1
// CHECK-LABEL: @objc weak var var_Weak5: @sil_weak AnyObject
// CHECK-LABEL: @objc weak var var_Weak7: @sil_weak Protocol_ObjC1
// CHECK-LABEL: @objc weak var var_Weak8: @sil_weak (Protocol_ObjC1 & Protocol_ObjC2)?
weak var var_Weak_fail1: PlainClass?
weak var var_Weak_bad2: PlainStruct?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainStruct'}}
weak var var_Weak_bad3: PlainEnum?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainEnum'}}
weak var var_Weak_bad4: String?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'String'}}
// CHECK-NOT: @objc{{.*}}Weak_fail
unowned var var_Unowned1: Class_ObjC1
unowned var var_Unowned2: Protocol_ObjC1
// <rdar://problem/16473062> weak and unowned variables of metatypes are rejected
//unowned var var_Unowned3: Class_ObjC1.Type
//unowned var var_Unowned4: Protocol_ObjC1.Type
unowned var var_Unowned5: AnyObject
//unowned var var_Unowned6: AnyObject.Type
unowned var var_Unowned7: Protocol_ObjC1
unowned var var_Unowned8: Protocol_ObjC1 & Protocol_ObjC2
// CHECK-LABEL: @objc unowned var var_Unowned1: @sil_unowned Class_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned2: @sil_unowned Protocol_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned5: @sil_unowned AnyObject
// CHECK-LABEL: @objc unowned var var_Unowned7: @sil_unowned Protocol_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned8: @sil_unowned Protocol_ObjC1 & Protocol_ObjC2
unowned var var_Unowned_fail1: PlainClass
unowned var var_Unowned_bad2: PlainStruct
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainStruct'}}
unowned var var_Unowned_bad3: PlainEnum
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainEnum'}}
unowned var var_Unowned_bad4: String
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'String'}}
// CHECK-NOT: @objc{{.*}}Unowned_fail
var var_FunctionType1: () -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType1: () -> ()
var var_FunctionType2: (Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType2: (Int) -> ()
var var_FunctionType3: (Int) -> Int
// CHECK-LABEL: {{^}} @objc var var_FunctionType3: (Int) -> Int
var var_FunctionType4: (Int, Double) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType4: (Int, Double) -> ()
var var_FunctionType5: (String) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType5: (String) -> ()
var var_FunctionType6: () -> String
// CHECK-LABEL: {{^}} @objc var var_FunctionType6: () -> String
var var_FunctionType7: (PlainClass) -> ()
// CHECK-NOT: @objc var var_FunctionType7: (PlainClass) -> ()
var var_FunctionType8: () -> PlainClass
// CHECK-NOT: @objc var var_FunctionType8: () -> PlainClass
var var_FunctionType9: (PlainStruct) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType9: (PlainStruct) -> ()
var var_FunctionType10: () -> PlainStruct
// CHECK-LABEL: {{^}} var var_FunctionType10: () -> PlainStruct
var var_FunctionType11: (PlainEnum) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType11: (PlainEnum) -> ()
var var_FunctionType12: (PlainProtocol) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType12: (PlainProtocol) -> ()
var var_FunctionType13: (Class_ObjC1) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType13: (Class_ObjC1) -> ()
var var_FunctionType14: (Protocol_Class1) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType14: (Protocol_Class1) -> ()
var var_FunctionType15: (Protocol_ObjC1) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType15: (Protocol_ObjC1) -> ()
var var_FunctionType16: (AnyObject) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType16: (AnyObject) -> ()
var var_FunctionType17: (() -> ()) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType17: (() -> ()) -> ()
var var_FunctionType18: ((Int) -> (), Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType18: ((Int) -> (), Int) -> ()
var var_FunctionType19: ((String) -> (), Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType19: ((String) -> (), Int) -> ()
var var_FunctionTypeReturn1: () -> () -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn1: () -> () -> ()
@objc var var_FunctionTypeReturn1_: () -> () -> () // no-error
var var_FunctionTypeReturn2: () -> (Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn2: () -> (Int) -> ()
@objc var var_FunctionTypeReturn2_: () -> (Int) -> () // no-error
var var_FunctionTypeReturn3: () -> () -> Int
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn3: () -> () -> Int
@objc var var_FunctionTypeReturn3_: () -> () -> Int // no-error
var var_FunctionTypeReturn4: () -> (String) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn4: () -> (String) -> ()
@objc var var_FunctionTypeReturn4_: () -> (String) -> () // no-error
var var_FunctionTypeReturn5: () -> () -> String
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn5: () -> () -> String
@objc var var_FunctionTypeReturn5_: () -> () -> String // no-error
var var_BlockFunctionType1: @convention(block) () -> ()
// CHECK-LABEL: @objc var var_BlockFunctionType1: @convention(block) () -> ()
@objc var var_BlockFunctionType1_: @convention(block) () -> () // no-error
var var_ArrayType1: [AnyObject]
// CHECK-LABEL: {{^}} @objc var var_ArrayType1: [AnyObject]
@objc var var_ArrayType1_: [AnyObject] // no-error
var var_ArrayType2: [@convention(block) (AnyObject) -> AnyObject] // no-error
// CHECK-LABEL: {{^}} @objc var var_ArrayType2: [@convention(block) (AnyObject) -> AnyObject]
@objc var var_ArrayType2_: [@convention(block) (AnyObject) -> AnyObject] // no-error
var var_ArrayType3: [PlainStruct]
// CHECK-LABEL: {{^}} var var_ArrayType3: [PlainStruct]
@objc var var_ArrayType3_: [PlainStruct]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType4: [(AnyObject) -> AnyObject] // no-error
// CHECK-LABEL: {{^}} var var_ArrayType4: [(AnyObject) -> AnyObject]
@objc var var_ArrayType4_: [(AnyObject) -> AnyObject]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType5: [Protocol_ObjC1]
// CHECK-LABEL: {{^}} @objc var var_ArrayType5: [Protocol_ObjC1]
@objc var var_ArrayType5_: [Protocol_ObjC1] // no-error
var var_ArrayType6: [Class_ObjC1]
// CHECK-LABEL: {{^}} @objc var var_ArrayType6: [Class_ObjC1]
@objc var var_ArrayType6_: [Class_ObjC1] // no-error
var var_ArrayType7: [PlainClass]
// CHECK-LABEL: {{^}} var var_ArrayType7: [PlainClass]
@objc var var_ArrayType7_: [PlainClass]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType8: [PlainProtocol]
// CHECK-LABEL: {{^}} var var_ArrayType8: [PlainProtocol]
@objc var var_ArrayType8_: [PlainProtocol]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType9: [Protocol_ObjC1 & PlainProtocol]
// CHECK-LABEL: {{^}} var var_ArrayType9: [PlainProtocol & Protocol_ObjC1]
@objc var var_ArrayType9_: [Protocol_ObjC1 & PlainProtocol]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType10: [Protocol_ObjC1 & Protocol_ObjC2]
// CHECK-LABEL: {{^}} @objc var var_ArrayType10: [Protocol_ObjC1 & Protocol_ObjC2]
@objc var var_ArrayType10_: [Protocol_ObjC1 & Protocol_ObjC2]
// no-error
var var_ArrayType11: [Any]
// CHECK-LABEL: @objc var var_ArrayType11: [Any]
@objc var var_ArrayType11_: [Any]
var var_ArrayType13: [Any?]
// CHECK-LABEL: {{^}} var var_ArrayType13: [Any?]
@objc var var_ArrayType13_: [Any?]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType15: [AnyObject?]
// CHECK-LABEL: {{^}} var var_ArrayType15: [AnyObject?]
@objc var var_ArrayType15_: [AnyObject?]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType16: [[@convention(block) (AnyObject) -> AnyObject]] // no-error
// CHECK-LABEL: {{^}} @objc var var_ArrayType16: {{\[}}[@convention(block) (AnyObject) -> AnyObject]]
@objc var var_ArrayType16_: [[@convention(block) (AnyObject) -> AnyObject]] // no-error
var var_ArrayType17: [[(AnyObject) -> AnyObject]] // no-error
// CHECK-LABEL: {{^}} var var_ArrayType17: {{\[}}[(AnyObject) -> AnyObject]]
@objc var var_ArrayType17_: [[(AnyObject) -> AnyObject]]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
}
@objc
class ObjCBase {}
class infer_instanceVar2<
GP_Unconstrained,
GP_PlainClass : PlainClass,
GP_PlainProtocol : PlainProtocol,
GP_Class_ObjC : Class_ObjC1,
GP_Protocol_Class : Protocol_Class1,
GP_Protocol_ObjC : Protocol_ObjC1> : ObjCBase {
// CHECK-LABEL: class infer_instanceVar2<{{.*}}> : ObjCBase where {{.*}} {
override init() {}
var var_GP_Unconstrained: GP_Unconstrained
// CHECK-LABEL: {{^}} var var_GP_Unconstrained: GP_Unconstrained
@objc var var_GP_Unconstrained_: GP_Unconstrained
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_PlainClass: GP_PlainClass
// CHECK-LABEL: {{^}} var var_GP_PlainClass: GP_PlainClass
@objc var var_GP_PlainClass_: GP_PlainClass
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_PlainProtocol: GP_PlainProtocol
// CHECK-LABEL: {{^}} var var_GP_PlainProtocol: GP_PlainProtocol
@objc var var_GP_PlainProtocol_: GP_PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Class_ObjC: GP_Class_ObjC
// CHECK-LABEL: {{^}} var var_GP_Class_ObjC: GP_Class_ObjC
@objc var var_GP_Class_ObjC_: GP_Class_ObjC
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Protocol_Class: GP_Protocol_Class
// CHECK-LABEL: {{^}} var var_GP_Protocol_Class: GP_Protocol_Class
@objc var var_GP_Protocol_Class_: GP_Protocol_Class
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Protocol_ObjC: GP_Protocol_ObjC
// CHECK-LABEL: {{^}} var var_GP_Protocol_ObjC: GP_Protocol_ObjC
@objc var var_GP_Protocol_ObjCa: GP_Protocol_ObjC
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
func func_GP_Unconstrained(a: GP_Unconstrained) {}
// CHECK-LABEL: {{^}} func func_GP_Unconstrained(a: GP_Unconstrained) {
@objc func func_GP_Unconstrained_(a: GP_Unconstrained) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
@objc func func_GP_Unconstrained_() -> GP_Unconstrained {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
@objc func func_GP_Class_ObjC__() -> GP_Class_ObjC {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
}
class infer_instanceVar3 : Class_ObjC1 {
// CHECK-LABEL: @objc class infer_instanceVar3 : Class_ObjC1 {
var v1: Int = 0
// CHECK-LABEL: @objc var v1: Int
}
@objc
protocol infer_instanceVar4 {
// CHECK-LABEL: @objc protocol infer_instanceVar4 {
var v1: Int { get }
// CHECK-LABEL: @objc var v1: Int { get }
}
// @!objc
class infer_instanceVar5 {
// CHECK-LABEL: {{^}}class infer_instanceVar5 {
@objc
var intstanceVar1: Int {
// CHECK: @objc var intstanceVar1: Int
get {}
// CHECK: @objc get {}
set {}
// CHECK: @objc set {}
}
}
@objc
class infer_staticVar1 {
// CHECK-LABEL: @objc class infer_staticVar1 {
class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}}
// CHECK: @objc class var staticVar1: Int
}
// @!objc
class infer_subscript1 {
// CHECK-LABEL: class infer_subscript1
@objc
subscript(i: Int) -> Int {
// CHECK: @objc subscript(i: Int) -> Int
get {}
// CHECK: @objc get {}
set {}
// CHECK: @objc set {}
}
}
@objc
protocol infer_throughConformanceProto1 {
// CHECK-LABEL: @objc protocol infer_throughConformanceProto1 {
func funcObjC1()
var varObjC1: Int { get }
var varObjC2: Int { get set }
// CHECK: @objc func funcObjC1()
// CHECK: @objc var varObjC1: Int { get }
// CHECK: @objc var varObjC2: Int { get set }
}
class infer_class1 : PlainClass {}
// CHECK-LABEL: {{^}}class infer_class1 : PlainClass {
class infer_class2 : Class_ObjC1 {}
// CHECK-LABEL: @objc class infer_class2 : Class_ObjC1 {
class infer_class3 : infer_class2 {}
// CHECK-LABEL: @objc class infer_class3 : infer_class2 {
class infer_class4 : Protocol_Class1 {}
// CHECK-LABEL: {{^}}class infer_class4 : Protocol_Class1 {
class infer_class5 : Protocol_ObjC1 {}
// CHECK-LABEL: {{^}}class infer_class5 : Protocol_ObjC1 {
//
// If a protocol conforms to an @objc protocol, this does not infer @objc on
// the protocol itself, or on the newly introduced requirements. Only the
// inherited @objc requirements get @objc.
//
// Same rule applies to classes.
//
protocol infer_protocol1 {
// CHECK-LABEL: {{^}}protocol infer_protocol1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol2 : Protocol_Class1 {
// CHECK-LABEL: {{^}}protocol infer_protocol2 : Protocol_Class1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol3 : Protocol_ObjC1 {
// CHECK-LABEL: {{^}}protocol infer_protocol3 : Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 {
// CHECK-LABEL: {{^}}protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol5 : Protocol_ObjC1, Protocol_Class1 {
// CHECK-LABEL: {{^}}protocol infer_protocol5 : Protocol_ObjC1, Protocol_Class1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
class C {
// Don't crash.
@objc func foo(x: Undeclared) {} // expected-error {{use of undeclared type 'Undeclared'}}
@IBAction func myAction(sender: Undeclared) {} // expected-error {{use of undeclared type 'Undeclared'}}
}
//===---
//===--- @IBOutlet implies @objc
//===---
class HasIBOutlet {
// CHECK-LABEL: {{^}}class HasIBOutlet {
init() {}
@IBOutlet weak var goodOutlet: Class_ObjC1!
// CHECK-LABEL: {{^}} @IBOutlet @objc weak var goodOutlet: @sil_weak Class_ObjC1!
@IBOutlet var badOutlet: PlainStruct
// expected-error@-1 {{@IBOutlet property cannot have non-object type 'PlainStruct'}} {{3-13=}}
// CHECK-LABEL: {{^}} @IBOutlet var badOutlet: PlainStruct
}
//===---
//===--- @IBAction implies @objc
//===---
// CHECK-LABEL: {{^}}class HasIBAction {
class HasIBAction {
@IBAction func goodAction(_ sender: AnyObject?) { }
// CHECK: {{^}} @IBAction @objc func goodAction(_ sender: AnyObject?) {
@IBAction func badAction(_ sender: PlainStruct?) { }
// expected-error@-1{{argument to @IBAction method cannot have non-object type 'PlainStruct?'}}
// expected-error@-2{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}}
}
//===---
//===--- @NSManaged implies @objc
//===---
class HasNSManaged {
// CHECK-LABEL: {{^}}class HasNSManaged {
init() {}
@NSManaged
var goodManaged: Class_ObjC1
// CHECK-LABEL: {{^}} @NSManaged @objc dynamic var goodManaged: Class_ObjC1
@NSManaged
var badManaged: PlainStruct
// expected-error@-1 {{property cannot be marked @NSManaged because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// CHECK-LABEL: {{^}} @NSManaged var badManaged: PlainStruct
}
//===---
//===--- Pointer argument types
//===---
@objc class TakesCPointers {
// CHECK-LABEL: {{^}}@objc class TakesCPointers {
func constUnsafeMutablePointer(p: UnsafePointer<Int>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointer(p: UnsafePointer<Int>) {
func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) {
func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) {
func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) {}
// CHECK-LABEL: @objc func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) {
func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) {}
// CHECK-LABEL: {{^}} @objc func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) {
func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) {}
// CHECK-LABEL: {{^}} @objc func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) {
}
// @objc with nullary names
@objc(NSObjC2)
class Class_ObjC2 {
// CHECK-LABEL: @objc(NSObjC2) class Class_ObjC2
@objc(initWithMalice)
init(foo: ()) { }
@objc(initWithIntent)
init(bar _: ()) { }
@objc(initForMurder)
init() { }
@objc(isFoo)
func foo() -> Bool {}
// CHECK-LABEL: @objc(isFoo) func foo() -> Bool {
}
@objc() // expected-error{{expected name within parentheses of @objc attribute}}
class Class_ObjC3 {
}
// @objc with selector names
extension PlainClass {
// CHECK-LABEL: @objc(setFoo:) dynamic func
@objc(setFoo:)
func foo(b: Bool) { }
// CHECK-LABEL: @objc(setWithRed:green:blue:alpha:) dynamic func set
@objc(setWithRed:green:blue:alpha:)
func set(_: Float, green: Float, blue: Float, alpha: Float) { }
// CHECK-LABEL: @objc(createWithRed:green:blue:alpha:) dynamic class func createWith
@objc(createWithRed:green blue:alpha)
class func createWithRed(_: Float, green: Float, blue: Float, alpha: Float) { }
// expected-error@-2{{missing ':' after selector piece in @objc attribute}}{{28-28=:}}
// expected-error@-3{{missing ':' after selector piece in @objc attribute}}{{39-39=:}}
// CHECK-LABEL: @objc(::) dynamic func badlyNamed
@objc(::)
func badlyNamed(_: Int, y: Int) {}
}
@objc(Class:) // expected-error{{'@objc' class must have a simple name}}{{12-13=}}
class BadClass1 { }
@objc(Protocol:) // expected-error{{'@objc' protocol must have a simple name}}{{15-16=}}
protocol BadProto1 { }
@objc(Enum:) // expected-error{{'@objc' enum must have a simple name}}{{11-12=}}
enum BadEnum1: Int { case X }
@objc
enum BadEnum2: Int {
@objc(X:) // expected-error{{'@objc' enum case must have a simple name}}{{10-11=}}
case X
}
class BadClass2 {
@objc(badprop:foo:wibble:) // expected-error{{'@objc' property must have a simple name}}{{16-28=}}
var badprop: Int = 5
@objc(foo) // expected-error{{'@objc' subscript cannot have a name; did you mean to put the name on the getter or setter?}}
subscript (i: Int) -> Int {
get {
return i
}
}
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}}
func noArgNamesOneParam(x: Int) { }
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}}
func noArgNamesOneParam2(_: Int) { }
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has 2 parameters}}
func noArgNamesTwoParams(_: Int, y: Int) { }
@objc(foo:) // expected-error{{'@objc' method name provides one argument name, but method has 2 parameters}}
func oneArgNameTwoParams(_: Int, y: Int) { }
@objc(foo:) // expected-error{{'@objc' method name provides one argument name, but method has 0 parameters}}
func oneArgNameNoParams() { }
@objc(foo:) // expected-error{{'@objc' initializer name provides one argument name, but initializer has 0 parameters}}
init() { }
var _prop = 5
@objc var prop: Int {
@objc(property) get { return _prop }
@objc(setProperty:) set { _prop = newValue }
}
var prop2: Int {
@objc(property) get { return _prop } // expected-error{{'@objc' getter for non-'@objc' property}}
@objc(setProperty:) set { _prop = newValue } // expected-error{{'@objc' setter for non-'@objc' property}}
}
var prop3: Int {
@objc(setProperty:) didSet { } // expected-error{{observing accessors are not allowed to be marked @objc}} {{5-10=}}
}
@objc
subscript (c: Class_ObjC1) -> Class_ObjC1 {
@objc(getAtClass:) get {
return c
}
@objc(setAtClass:class:) set {
}
}
}
// Swift overrides that aren't also @objc overrides.
class Super {
@objc(renamedFoo)
var foo: Int { get { return 3 } } // expected-note 2{{overridden declaration is here}}
@objc func process(i: Int) -> Int { } // expected-note {{overriding '@objc' method 'process(i:)' here}}
}
class Sub1 : Super {
@objc(foo) // expected-error{{Objective-C property has a different name from the property it overrides ('foo' vs. 'renamedFoo')}}{{9-12=renamedFoo}}
override var foo: Int { get { return 5 } }
override func process(i: Int?) -> Int { } // expected-error{{method cannot be an @objc override because the type of the parameter cannot be represented in Objective-C}}
}
class Sub2 : Super {
@objc
override var foo: Int { get { return 5 } }
}
class Sub3 : Super {
override var foo: Int { get { return 5 } }
}
class Sub4 : Super {
@objc(renamedFoo)
override var foo: Int { get { return 5 } }
}
class Sub5 : Super {
@objc(wrongFoo) // expected-error{{Objective-C property has a different name from the property it overrides ('wrongFoo' vs. 'renamedFoo')}} {{9-17=renamedFoo}}
override var foo: Int { get { return 5 } }
}
enum NotObjCEnum { case X }
struct NotObjCStruct {}
// Closure arguments can only be @objc if their parameters and returns are.
// CHECK-LABEL: @objc class ClosureArguments
@objc class ClosureArguments {
// CHECK: @objc func foo
@objc func foo(f: (Int) -> ()) {}
// CHECK: @objc func bar
@objc func bar(f: (NotObjCEnum) -> NotObjCStruct) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func bas
@objc func bas(f: (NotObjCEnum) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func zim
@objc func zim(f: () -> NotObjCStruct) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func zang
@objc func zang(f: (NotObjCEnum, NotObjCStruct) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
@objc func zangZang(f: (Int...) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func fooImplicit
func fooImplicit(f: (Int) -> ()) {}
// CHECK: {{^}} func barImplicit
func barImplicit(f: (NotObjCEnum) -> NotObjCStruct) {}
// CHECK: {{^}} func basImplicit
func basImplicit(f: (NotObjCEnum) -> ()) {}
// CHECK: {{^}} func zimImplicit
func zimImplicit(f: () -> NotObjCStruct) {}
// CHECK: {{^}} func zangImplicit
func zangImplicit(f: (NotObjCEnum, NotObjCStruct) -> ()) {}
// CHECK: {{^}} func zangZangImplicit
func zangZangImplicit(f: (Int...) -> ()) {}
}
typealias GoodBlock = @convention(block) (Int) -> ()
typealias BadBlock = @convention(block) (NotObjCEnum) -> () // expected-error{{'(NotObjCEnum) -> ()' is not representable in Objective-C, so it cannot be used with '@convention(block)'}}
@objc class AccessControl {
// CHECK: @objc func foo
func foo() {}
// CHECK: {{^}} private func bar
private func bar() {}
// CHECK: @objc private func baz
@objc private func baz() {}
}
//===--- Ban @objc +load methods
class Load1 {
// Okay: not @objc
class func load() { }
class func alloc() {}
class func allocWithZone(_: Int) {}
class func initialize() {}
}
@objc class Load2 {
class func load() { } // expected-error{{method 'load()' defines Objective-C class method 'load', which is not permitted by Swift}}
class func alloc() {} // expected-error{{method 'alloc()' defines Objective-C class method 'alloc', which is not permitted by Swift}}
class func allocWithZone(_: Int) {} // expected-error{{method 'allocWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}}
class func initialize() {} // expected-error{{method 'initialize()' defines Objective-C class method 'initialize', which is not permitted by Swift}}
}
@objc class Load3 {
class var load: Load3 {
get { return Load3() } // expected-error{{getter for 'load' defines Objective-C class method 'load', which is not permitted by Swift}}
set { }
}
@objc(alloc) class var prop: Int { return 0 } // expected-error{{getter for 'prop' defines Objective-C class method 'alloc', which is not permitted by Swift}}
@objc(allocWithZone:) class func fooWithZone(_: Int) {} // expected-error{{method 'fooWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}}
@objc(initialize) class func barnitialize() {} // expected-error{{method 'barnitialize()' defines Objective-C class method 'initialize', which is not permitted by Swift}}
}
// Members of protocol extensions cannot be @objc
extension PlainProtocol {
@objc final var property: Int { return 5 } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc final subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc final func fun() { } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
extension Protocol_ObjC1 {
@objc final var property: Int { return 5 } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc final subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc final func fun() { } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
extension Protocol_ObjC1 {
// Don't infer @objc for extensions of @objc protocols.
// CHECK: {{^}} var propertyOK: Int
final var propertyOK: Int { return 5 }
}
//===---
//===--- Error handling
//===---
class ClassThrows1 {
// CHECK: @objc func methodReturnsVoid() throws
@objc func methodReturnsVoid() throws { }
// CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1
@objc func methodReturnsObjCClass() throws -> Class_ObjC1 {
return Class_ObjC1()
}
// CHECK: @objc func methodReturnsBridged() throws -> String
@objc func methodReturnsBridged() throws -> String { return String() }
// CHECK: @objc func methodReturnsArray() throws -> [String]
@objc func methodReturnsArray() throws -> [String] { return [String]() }
// CHECK: @objc init(degrees: Double) throws
@objc init(degrees: Double) throws { }
// Errors
@objc func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil } // expected-error{{throwing method cannot be marked @objc because it returns a value of optional type 'Class_ObjC1?'; 'nil' indicates failure to Objective-C}}
@objc func methodReturnsOptionalArray() throws -> [String]? { return nil } // expected-error{{throwing method cannot be marked @objc because it returns a value of optional type '[String]?'; 'nil' indicates failure to Objective-C}}
@objc func methodReturnsInt() throws -> Int { return 0 } // expected-error{{throwing method cannot be marked @objc because it returns a value of type 'Int'; return 'Void' or a type that bridges to an Objective-C class}}
@objc func methodAcceptsThrowingFunc(fn: (String) throws -> Int) { }
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{throwing function types cannot be represented in Objective-C}}
@objc init?(radians: Double) throws { } // expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}}
@objc init!(string: String) throws { } // expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}}
@objc func fooWithErrorEnum1(x: ErrorEnum) {}
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{non-'@objc' enums cannot be represented in Objective-C}}
// CHECK: {{^}} func fooWithErrorEnum2(x: ErrorEnum)
func fooWithErrorEnum2(x: ErrorEnum) {}
@objc func fooWithErrorProtocolComposition1(x: Error & Protocol_ObjC1) { }
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{protocol composition involving 'Error' cannot be represented in Objective-C}}
// CHECK: {{^}} func fooWithErrorProtocolComposition2(x: Error & Protocol_ObjC1)
func fooWithErrorProtocolComposition2(x: Error & Protocol_ObjC1) { }
}
// CHECK-DUMP-LABEL: class_decl "ImplicitClassThrows1"
@objc class ImplicitClassThrows1 {
// CHECK: @objc func methodReturnsVoid() throws
// CHECK-DUMP: func_decl "methodReturnsVoid()"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
func methodReturnsVoid() throws { }
// CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1
// CHECK-DUMP: func_decl "methodReturnsObjCClass()" {{.*}}foreign_error=NilResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>
func methodReturnsObjCClass() throws -> Class_ObjC1 {
return Class_ObjC1()
}
// CHECK: @objc func methodReturnsBridged() throws -> String
func methodReturnsBridged() throws -> String { return String() }
// CHECK: @objc func methodReturnsArray() throws -> [String]
func methodReturnsArray() throws -> [String] { return [String]() }
// CHECK: {{^}} func methodReturnsOptionalObjCClass() throws -> Class_ObjC1?
func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil }
// CHECK: @objc func methodWithTrailingClosures(_ s: String, fn1: @escaping ((Int) -> Int), fn2: @escaping (Int) -> Int, fn3: @escaping (Int) -> Int)
// CHECK-DUMP: func_decl "methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
func methodWithTrailingClosures(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int, fn3: @escaping (Int) -> Int) throws { }
// CHECK: @objc init(degrees: Double) throws
// CHECK-DUMP: constructor_decl "init(degrees:)"{{.*}}foreign_error=NilResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>
init(degrees: Double) throws { }
// CHECK: {{^}} func methodReturnsBridgedValueType() throws -> NSRange
func methodReturnsBridgedValueType() throws -> NSRange { return NSRange() }
@objc func methodReturnsBridgedValueType2() throws -> NSRange {
return NSRange()
}
// expected-error@-3{{throwing method cannot be marked @objc because it returns a value of type 'NSRange' (aka '_NSRange'); return 'Void' or a type that bridges to an Objective-C class}}
// CHECK: {{^}} @objc func methodReturnsError() throws -> Error
func methodReturnsError() throws -> Error { return ErrorEnum.failed }
// CHECK: @objc func methodReturnStaticBridged() throws -> ((Int) -> (Int) -> Int)
func methodReturnStaticBridged() throws -> ((Int) -> (Int) -> Int) {
func add(x: Int) -> (Int) -> Int {
return { x + $0 }
}
}
}
// CHECK-DUMP-LABEL: class_decl "SubclassImplicitClassThrows1"
@objc class SubclassImplicitClassThrows1 : ImplicitClassThrows1 {
// CHECK: @objc override func methodWithTrailingClosures(_ s: String, fn1: @escaping ((Int) -> Int), fn2: @escaping ((Int) -> Int), fn3: @escaping ((Int) -> Int))
// CHECK-DUMP: func_decl "methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func methodWithTrailingClosures(_ s: String, fn1: (@escaping (Int) -> Int), fn2: (@escaping (Int) -> Int), fn3: (@escaping (Int) -> Int)) throws { }
}
class ThrowsRedecl1 {
@objc func method1(_ x: Int, error: Class_ObjC1) { } // expected-note{{declared here}}
@objc func method1(_ x: Int) throws { } // expected-error{{with Objective-C selector 'method1:error:'}}
@objc func method2AndReturnError(_ x: Int) { } // expected-note{{declared here}}
@objc func method2() throws { } // expected-error{{with Objective-C selector 'method2AndReturnError:'}}
@objc func method3(_ x: Int, error: Int, closure: @escaping (Int) -> Int) { } // expected-note{{declared here}}
@objc func method3(_ x: Int, closure: (Int) -> Int) throws { } // expected-error{{with Objective-C selector 'method3:error:closure:'}}
@objc(initAndReturnError:) func initMethod1(error: Int) { } // expected-note{{declared here}}
@objc init() throws { } // expected-error{{with Objective-C selector 'initAndReturnError:'}}
@objc(initWithString:error:) func initMethod2(string: String, error: Int) { } // expected-note{{declared here}}
@objc init(string: String) throws { } // expected-error{{with Objective-C selector 'initWithString:error:'}}
@objc(initAndReturnError:fn:) func initMethod3(error: Int, fn: @escaping (Int) -> Int) { } // expected-note{{declared here}}
@objc init(fn: (Int) -> Int) throws { } // expected-error{{with Objective-C selector 'initAndReturnError:fn:'}}
}
class ThrowsObjCName {
@objc(method4:closure:error:) func method4(x: Int, closure: @escaping (Int) -> Int) throws { }
@objc(method5AndReturnError:x:closure:) func method5(x: Int, closure: @escaping (Int) -> Int) throws { }
@objc(method6) func method6() throws { } // expected-error{{@objc' method name provides names for 0 arguments, but method has one parameter (the error parameter)}}
@objc(method7) func method7(x: Int) throws { } // expected-error{{@objc' method name provides names for 0 arguments, but method has 2 parameters (including the error parameter)}}
// CHECK-DUMP: func_decl "method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
@objc(method8:fn1:error:fn2:)
func method8(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
// CHECK-DUMP: func_decl "method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
@objc(method9AndReturnError:s:fn1:fn2:)
func method9(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
}
class SubclassThrowsObjCName : ThrowsObjCName {
// CHECK-DUMP: func_decl "method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func method8(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
// CHECK-DUMP: func_decl "method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func method9(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
}
@objc protocol ProtocolThrowsObjCName {
@objc optional func doThing(_ x: String) throws -> String // expected-note{{requirement 'doThing' declared here}}
}
class ConformsToProtocolThrowsObjCName1 : ProtocolThrowsObjCName {
@objc func doThing(_ x: String) throws -> String { return x } // okay
}
class ConformsToProtocolThrowsObjCName2 : ProtocolThrowsObjCName {
@objc func doThing(_ x: Int) throws -> String { return "" }
// expected-warning@-1{{instance method 'doThing' nearly matches optional requirement 'doThing' of protocol 'ProtocolThrowsObjCName'}}
// expected-note@-2{{move 'doThing' to an extension to silence this warning}}
// expected-note@-3{{make 'doThing' private to silence this warning}}{{9-9=private }}
// expected-note@-4{{candidate has non-matching type '(Int) throws -> String'}}
}
@objc class DictionaryTest {
// CHECK-LABEL: @objc func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>)
func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>) { }
// CHECK-LABEL: @objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>)
@objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>) { }
func func_dictionary2a(x: Dictionary<String, Int>) { }
@objc func func_dictionary2b(x: Dictionary<String, Int>) { }
}
@objc class ObjC_Class1 : Hashable {
var hashValue: Int { return 0 }
}
func ==(lhs: ObjC_Class1, rhs: ObjC_Class1) -> Bool {
return true
}
// CHECK-LABEL: @objc class OperatorInClass
@objc class OperatorInClass {
// CHECK: {{^}} static func ==(lhs: OperatorInClass, rhs: OperatorInClass) -> Bool
static func ==(lhs: OperatorInClass, rhs: OperatorInClass) -> Bool {
return true
}
// CHECK: {{^}} @objc static func +(lhs: OperatorInClass, rhs: OperatorInClass) -> OperatorInClass
@objc static func +(lhs: OperatorInClass, rhs: OperatorInClass) -> OperatorInClass { // expected-error {{operator methods cannot be declared @objc}}
return lhs
}
} // CHECK: {{^}$}}
@objc protocol OperatorInProtocol {
static func +(lhs: Self, rhs: Self) -> Self // expected-error {{@objc protocols may not have operator requirements}}
}
class AdoptsOperatorInProtocol : OperatorInProtocol {
static func +(lhs: AdoptsOperatorInProtocol, rhs: AdoptsOperatorInProtocol) -> Self {}
// expected-error@-1 {{operator methods cannot be declared @objc}}
}
//===--- @objc inference for witnesses
@objc protocol InferFromProtocol {
@objc(inferFromProtoMethod1:)
optional func method1(value: Int)
}
// Infer when in the same declaration context.
// CHECK-LABEL: ClassInfersFromProtocol1
class ClassInfersFromProtocol1 : InferFromProtocol{
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
// Infer when in a different declaration context of the same class.
// CHECK-LABEL: ClassInfersFromProtocol2a
class ClassInfersFromProtocol2a {
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
extension ClassInfersFromProtocol2a : InferFromProtocol { }
// Infer when in a different declaration context of the same class.
class ClassInfersFromProtocol2b : InferFromProtocol { }
// CHECK-LABEL: ClassInfersFromProtocol2b
extension ClassInfersFromProtocol2b {
// CHECK: {{^}} @objc dynamic func method1(value: Int)
func method1(value: Int) { }
}
// Don't infer when there is a signature mismatch.
// CHECK-LABEL: ClassInfersFromProtocol3
class ClassInfersFromProtocol3 : InferFromProtocol {
}
extension ClassInfersFromProtocol3 {
// CHECK: {{^}} func method1(value: String)
func method1(value: String) { }
}
// Inference for subclasses.
class SuperclassImplementsProtocol : InferFromProtocol { }
class SubclassInfersFromProtocol1 : SuperclassImplementsProtocol {
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
class SubclassInfersFromProtocol2 : SuperclassImplementsProtocol {
}
extension SubclassInfersFromProtocol2 {
// CHECK: {{^}} @objc dynamic func method1(value: Int)
func method1(value: Int) { }
}
@objc class NeverReturningMethod {
@objc func doesNotReturn() -> Never {}
}
| apache-2.0 | b55177be24b651ba33c9bfd92bb05af7 | 39.559314 | 293 | 0.702235 | 3.871023 | false | false | false | false |
dflax/CookieCrunch | CookieCrunch/Chain.swift | 1 | 1042 | //
// Chain.swift
// CookieCrunch
//
// Created by Daniel Flax on 5/6/15.
// Copyright (c) 2015 Daniel Flax. All rights reserved.
//
class Chain: Hashable, Printable {
var cookies = [Cookie]()
// For scores
var score = 0
enum ChainType: Printable {
case Horizontal
case Vertical
var description: String {
switch self {
case .Horizontal: return "Horizontal"
case .Vertical: return "Vertical"
}
}
}
var chainType: ChainType
init(chainType: ChainType) {
self.chainType = chainType
}
func addCookie(cookie: Cookie) {
cookies.append(cookie)
}
func firstCookie() -> Cookie {
return cookies[0]
}
func lastCookie() -> Cookie {
return cookies[cookies.count - 1]
}
var length: Int {
return cookies.count
}
var description: String {
return "type:\(chainType) cookies:\(cookies)"
}
var hashValue: Int {
return reduce(cookies, 0) { $0.hashValue ^ $1.hashValue }
}
}
// To support the hashable protocol
func ==(lhs: Chain, rhs: Chain) -> Bool {
return lhs.cookies == rhs.cookies
}
| mit | 87ed3a6404d19ae46d1c5d4b6c2da9e5 | 15.28125 | 59 | 0.661228 | 3.176829 | false | false | false | false |
dhruvit-r/AKImageCropperView | AKImageCropperView/AKImageCropperScrollView.swift | 1 | 2301 | //
// AKImageCropperScrollView.swift
// AKImageCropperView
//
// Created by Artem Krachulov on 12/17/16.
// Copyright © 2016 Artem Krachulov. All rights reserved.
//
import UIKit
final class AKImageCropperScrollView: UIScrollView {
// MARK: -
// MARK: ** Properties **
/** Return visible rect of an UIScrollView's content */
open var visibleRect: CGRect {
return CGRect(
x : contentInset.left,
y : contentInset.top,
width : frame.size.width - contentInset.left - contentInset.right,
height : frame.size.height - contentInset.top - contentInset.bottom)
}
/** Returns scaled visible rect of an UIScrollView's content */
open var scaledVisibleRect: CGRect {
return CGRect(
x : (contentOffset.x + contentInset.left) / zoomScale,
y : (contentOffset.y + contentInset.top) / zoomScale,
width : visibleRect.size.width / zoomScale,
height : visibleRect.size.height / zoomScale)
}
// MARK: -
// MARK: ** Initialization OBJECTS(VIEWS) & theirs parameters **
fileprivate lazy var imageView: UIImageView! = {
let view = UIImageView()
return view
}()
fileprivate var isUpdating: Bool = false
open var image: UIImage! {
didSet {
/* Prepare scroll view to changing the image */
maximumZoomScale = 1
minimumZoomScale = 1
zoomScale = 1
/* Update an image view */
imageView.image = image
imageView.frame.size = image.size
contentSize = image.size
}
}
// MARK: - Initialization
/** Returns an scroll view initialized object. */
init() {
super.init(frame: .zero)
alwaysBounceVertical = true
alwaysBounceHorizontal = true
showsVerticalScrollIndicator = false
showsHorizontalScrollIndicator = false
addSubview(imageView)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 65854048232b6a4b71955858cb15ef7b | 27.04878 | 81 | 0.556087 | 5.324074 | false | false | false | false |
danielmartin/swift | stdlib/private/StdlibCollectionUnittest/LoggingWrappers.swift | 6 | 21752 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import StdlibUnittest
public protocol Wrapper {
associatedtype Base
init(wrapping base: Base)
var base: Base { get set }
}
public protocol LoggingType: Wrapper {
associatedtype Log : AnyObject
}
extension LoggingType {
public var log: Log.Type {
return Log.self
}
public var selfType: Any.Type {
return type(of: self)
}
}
//===----------------------------------------------------------------------===//
// Iterator
//===----------------------------------------------------------------------===//
public class IteratorLog {
public static func dispatchTester<I>(
_ iterator: I
) -> LoggingIterator<LoggingIterator<I>> {
return LoggingIterator(wrapping: LoggingIterator(wrapping: iterator))
}
public static var next = TypeIndexed(0)
}
public struct LoggingIterator<Base : IteratorProtocol> {
public var base: Base
}
extension LoggingIterator: LoggingType {
public typealias Log = IteratorLog
public init(wrapping base: Base) {
self.base = base
}
}
extension LoggingIterator: IteratorProtocol {
public mutating func next() -> Base.Element? {
Log.next[selfType] += 1
return base.next()
}
}
//===----------------------------------------------------------------------===//
// Sequence and Collection logs
//===----------------------------------------------------------------------===//
// FIXME: it's not clear if it's really worth this hierarchy. the
// test.log pattern requires all the static properties be at the top
// since Log is an associated type that cannot be refined in extensions
// that add functionality.
public class SequenceLog {
// Sequence
public static var makeIterator = TypeIndexed(0)
public static var underestimatedCount = TypeIndexed(0)
public static var dropFirst = TypeIndexed(0)
public static var dropLast = TypeIndexed(0)
public static var dropWhile = TypeIndexed(0)
public static var prefixWhile = TypeIndexed(0)
public static var prefixMaxLength = TypeIndexed(0)
public static var suffixMaxLength = TypeIndexed(0)
public static var withContiguousStorageIfAvailable = TypeIndexed(0)
public static var _customContainsEquatableElement = TypeIndexed(0)
public static var _copyToContiguousArray = TypeIndexed(0)
public static var _copyContents = TypeIndexed(0)
// Collection
public static var startIndex = TypeIndexed(0)
public static var endIndex = TypeIndexed(0)
public static var subscriptIndex = TypeIndexed(0)
public static var subscriptRange = TypeIndexed(0)
public static var _failEarlyRangeCheckIndex = TypeIndexed(0)
public static var _failEarlyRangeCheckRange = TypeIndexed(0)
public static var successor = TypeIndexed(0)
public static var formSuccessor = TypeIndexed(0)
public static var indices = TypeIndexed(0)
public static var isEmpty = TypeIndexed(0)
public static var count = TypeIndexed(0)
public static var _customIndexOfEquatableElement = TypeIndexed(0)
public static var advance = TypeIndexed(0)
public static var advanceLimit = TypeIndexed(0)
public static var distance = TypeIndexed(0)
// BidirectionalCollection
public static var predecessor = TypeIndexed(0)
public static var formPredecessor = TypeIndexed(0)
// MutableCollection
public static var subscriptIndexSet = TypeIndexed(0)
public static var subscriptRangeSet = TypeIndexed(0)
public static var partitionBy = TypeIndexed(0)
public static var _withUnsafeMutableBufferPointerIfSupported = TypeIndexed(0)
public static var _withUnsafeMutableBufferPointerIfSupportedNonNilReturns =
TypeIndexed(0)
public static var withContiguousMutableStorageIfAvailable = TypeIndexed(0)
public static var withContiguousMutableStorageIfAvailableNonNilReturns =
TypeIndexed(0)
// RangeReplaceableCollection
public static var init_ = TypeIndexed(0)
public static var initRepeating = TypeIndexed(0)
public static var initWithSequence = TypeIndexed(0)
public static var _customRemoveLast = TypeIndexed(0)
public static var _customRemoveLastN = TypeIndexed(0)
public static var append = TypeIndexed(0)
public static var appendContentsOf = TypeIndexed(0)
public static var insert = TypeIndexed(0)
public static var insertContentsOf = TypeIndexed(0)
public static var removeAll = TypeIndexed(0)
public static var removeAt = TypeIndexed(0)
public static var removeFirst = TypeIndexed(0)
public static var removeFirstN = TypeIndexed(0)
public static var removeSubrange = TypeIndexed(0)
public static var replaceSubrange = TypeIndexed(0)
public static var reserveCapacity = TypeIndexed(0)
public class func dispatchTester<S>(
_ s: S
) -> LoggingSequence<LoggingSequence<S>> {
return LoggingSequence(wrapping: LoggingSequence(wrapping: s))
}
}
public class CollectionLog : SequenceLog {
public override class func dispatchTester<C>(
_ c: C
) -> LoggingCollection<LoggingCollection<C>> {
return LoggingCollection(wrapping: LoggingCollection(wrapping: c))
}
}
public class BidirectionalCollectionLog : CollectionLog {
public override class func dispatchTester<C>(
_ c: C
) -> LoggingBidirectionalCollection<LoggingBidirectionalCollection<C>> {
return LoggingBidirectionalCollection(
wrapping: LoggingBidirectionalCollection(wrapping: c))
}
}
public class MutableCollectionLog : CollectionLog {
public override class func dispatchTester<C>(
_ c: C
) -> LoggingMutableCollection<LoggingMutableCollection<C>> {
return LoggingMutableCollection(
wrapping: LoggingMutableCollection(wrapping: c))
}
}
/// Data container to keep track of how many times each `Base` type calls methods
/// of `RangeReplaceableCollection`.
///
/// Each static variable is a mapping of Type -> Number of calls.
public class RangeReplaceableCollectionLog : CollectionLog {
public override class func dispatchTester<C>(
_ rrc: C
) -> LoggingRangeReplaceableCollection<LoggingRangeReplaceableCollection<C>> {
return LoggingRangeReplaceableCollection(
wrapping: LoggingRangeReplaceableCollection(wrapping: rrc)
)
}
}
//===----------------------------------------------------------------------===//
// Sequence and Collection that count method calls
//===----------------------------------------------------------------------===//
/// Interposes between `Sequence` method calls to increment each method's
/// counter.
public struct LoggingSequence<Base : Sequence> {
public var base: Base
}
extension LoggingSequence: LoggingType {
// I know, I know. It doesn't matter though. The benefit of the whole logging
// class hiearchy is unclear...
public typealias Log = SequenceLog
public init(wrapping base: Base) {
self.base = base
}
}
extension LoggingSequence: Sequence {
public typealias Element = Base.Element
public typealias Iterator = LoggingIterator<Base.Iterator>
public func makeIterator() -> Iterator {
SequenceLog.makeIterator[selfType] += 1
return LoggingIterator(wrapping: base.makeIterator())
}
public var underestimatedCount: Int {
SequenceLog.underestimatedCount[selfType] += 1
return base.underestimatedCount
}
public func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R? {
SequenceLog.withContiguousStorageIfAvailable[selfType] += 1
return try base.withContiguousStorageIfAvailable(body)
}
public func _customContainsEquatableElement(_ element: Element) -> Bool? {
SequenceLog._customContainsEquatableElement[selfType] += 1
return base._customContainsEquatableElement(element)
}
/// Create a native array buffer containing the elements of `self`,
/// in the same order.
public func _copyToContiguousArray() -> ContiguousArray<Element> {
SequenceLog._copyToContiguousArray[selfType] += 1
return base._copyToContiguousArray()
}
/// Copy a Sequence into an array.
public func _copyContents(
initializing buffer: UnsafeMutableBufferPointer<Element>
) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) {
SequenceLog._copyContents[selfType] += 1
let (it,idx) = base._copyContents(initializing: buffer)
return (Iterator(wrapping: it),idx)
}
}
public typealias LoggingCollection<Base: Collection> = LoggingSequence<Base>
extension LoggingCollection: Collection {
public typealias Index = Base.Index
public typealias Indices = Base.Indices
public typealias SubSequence = Base.SubSequence
public var startIndex: Index {
CollectionLog.startIndex[selfType] += 1
return base.startIndex
}
public var endIndex: Index {
CollectionLog.endIndex[selfType] += 1
return base.endIndex
}
public subscript(position: Index) -> Element {
CollectionLog.subscriptIndex[selfType] += 1
return base[position]
}
public subscript(bounds: Range<Index>) -> SubSequence {
CollectionLog.subscriptRange[selfType] += 1
return base[bounds]
}
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
CollectionLog._failEarlyRangeCheckIndex[selfType] += 1
base._failEarlyRangeCheck(index, bounds: bounds)
}
public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {
CollectionLog._failEarlyRangeCheckRange[selfType] += 1
base._failEarlyRangeCheck(range, bounds: bounds)
}
public func index(after i: Index) -> Index {
CollectionLog.successor[selfType] += 1
return base.index(after: i)
}
public func formIndex(after i: inout Index) {
CollectionLog.formSuccessor[selfType] += 1
base.formIndex(after: &i)
}
public var indices: Indices {
CollectionLog.indices[selfType] += 1
return base.indices
}
public var isEmpty: Bool {
CollectionLog.isEmpty[selfType] += 1
return base.isEmpty
}
public var count: Int {
CollectionLog.count[selfType] += 1
return base.count
}
public func _customIndexOfEquatableElement(
_ element: Element
) -> Index?? {
CollectionLog._customIndexOfEquatableElement[selfType] += 1
return base._customIndexOfEquatableElement(element)
}
public func index(_ i: Index, offsetBy n: Int) -> Index {
CollectionLog.advance[selfType] += 1
return base.index(i, offsetBy: n)
}
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
CollectionLog.advanceLimit[selfType] += 1
return base.index(i, offsetBy: n, limitedBy: limit)
}
public func distance(from start: Index, to end: Index) -> Int {
CollectionLog.distance[selfType] += 1
return base.distance(from: start, to: end)
}
}
public typealias LoggingBidirectionalCollection<
Base: BidirectionalCollection
> = LoggingCollection<Base>
extension LoggingBidirectionalCollection: BidirectionalCollection {
public func index(before i: Index) -> Index {
BidirectionalCollectionLog.predecessor[selfType] += 1
return base.index(before: i)
}
public func formIndex(before i: inout Index) {
BidirectionalCollectionLog.formPredecessor[selfType] += 1
base.formIndex(before: &i)
}
}
public typealias LoggingRandomAccessCollection<Base: RandomAccessCollection>
= LoggingBidirectionalCollection<Base>
extension LoggingRandomAccessCollection: RandomAccessCollection { }
public typealias LoggingMutableCollection<Base: MutableCollection>
= LoggingCollection<Base>
extension LoggingMutableCollection: MutableCollection {
public subscript(position: Index) -> Element {
get {
MutableCollectionLog.subscriptIndex[selfType] += 1
return base[position]
}
set {
MutableCollectionLog.subscriptIndexSet[selfType] += 1
base[position] = newValue
}
}
public subscript(bounds: Range<Index>) -> SubSequence {
get {
MutableCollectionLog.subscriptRange[selfType] += 1
return base[bounds]
}
set {
MutableCollectionLog.subscriptRangeSet[selfType] += 1
base[bounds] = newValue
}
}
public mutating func partition(
by belongsInSecondPartition: (Iterator.Element) throws -> Bool
) rethrows -> Index {
Log.partitionBy[selfType] += 1
return try base.partition(by: belongsInSecondPartition)
}
public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
MutableCollectionLog._withUnsafeMutableBufferPointerIfSupported[selfType] += 1
let result = try base._withUnsafeMutableBufferPointerIfSupported(body)
if result != nil {
Log._withUnsafeMutableBufferPointerIfSupportedNonNilReturns[selfType] += 1
}
return result
}
public mutating func withContiguousMutableStorageIfAvailable<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
MutableCollectionLog.withContiguousMutableStorageIfAvailable[selfType] += 1
let result = try base.withContiguousMutableStorageIfAvailable(body)
if result != nil {
Log.withContiguousMutableStorageIfAvailable[selfType] += 1
}
return result
}
}
public typealias LoggingMutableBidirectionalCollection<
Base: MutableCollection & BidirectionalCollection
> = LoggingMutableCollection<Base>
public typealias LoggingMutableRandomAccessCollection<
Base: MutableCollection & RandomAccessCollection
> = LoggingMutableCollection<Base>
public typealias LoggingRangeReplaceableCollection<
Base: RangeReplaceableCollection
> = LoggingCollection<Base>
extension LoggingRangeReplaceableCollection: RangeReplaceableCollection {
public init() {
self.base = Base()
RangeReplaceableCollectionLog.init_[selfType] += 1
}
public init(repeating repeatedValue: Element, count: Int) {
self.base = Base(repeating: repeatedValue, count: count)
RangeReplaceableCollectionLog.initRepeating[selfType] += 1
}
public init<S : Sequence>(_ elements: S)
where S.Element == Element {
self.base = Base(elements)
RangeReplaceableCollectionLog.initWithSequence[selfType] += 1
}
public mutating func _customRemoveLast() -> Element? {
RangeReplaceableCollectionLog._customRemoveLast[selfType] += 1
return base._customRemoveLast()
}
public mutating func _customRemoveLast(_ n: Int) -> Bool {
RangeReplaceableCollectionLog._customRemoveLastN[selfType] += 1
return base._customRemoveLast(n)
}
public mutating func append(_ newElement: Element) {
RangeReplaceableCollectionLog.append[selfType] += 1
base.append(newElement)
}
public mutating func append<S : Sequence>(
contentsOf newElements: S
) where S.Element == Element {
RangeReplaceableCollectionLog.appendContentsOf[selfType] += 1
base.append(contentsOf: newElements)
}
public mutating func insert(
_ newElement: Element, at i: Index
) {
RangeReplaceableCollectionLog.insert[selfType] += 1
base.insert(newElement, at: i)
}
public mutating func insert<C : Collection>(
contentsOf newElements: C, at i: Index
) where C.Element == Element {
RangeReplaceableCollectionLog.insertContentsOf[selfType] += 1
base.insert(contentsOf: newElements, at: i)
}
public mutating func removeAll(keepingCapacity keepCapacity: Bool) {
RangeReplaceableCollectionLog.removeAll[selfType] += 1
base.removeAll(keepingCapacity: keepCapacity)
}
@discardableResult
public mutating func remove(at index: Index) -> Element {
RangeReplaceableCollectionLog.removeAt[selfType] += 1
return base.remove(at: index)
}
@discardableResult
public mutating func removeFirst() -> Element {
RangeReplaceableCollectionLog.removeFirst[selfType] += 1
return base.removeFirst()
}
public mutating func removeFirst(_ n: Int) {
RangeReplaceableCollectionLog.removeFirstN[selfType] += 1
base.removeFirst(n)
}
public mutating func removeSubrange(_ bounds: Range<Index>) {
RangeReplaceableCollectionLog.removeSubrange[selfType] += 1
base.removeSubrange(bounds)
}
public mutating func replaceSubrange<C : Collection>(
_ bounds: Range<Index>, with newElements: C
) where C.Element == Element {
RangeReplaceableCollectionLog.replaceSubrange[selfType] += 1
base.replaceSubrange(bounds, with: newElements)
}
public mutating func reserveCapacity(_ n: Int) {
RangeReplaceableCollectionLog.reserveCapacity[selfType] += 1
base.reserveCapacity(n)
}
}
public typealias LoggingRangeReplaceableBidirectionalCollection<
Base: BidirectionalCollection & RangeReplaceableCollection
> = LoggingRangeReplaceableCollection<Base>
public typealias LoggingRangeReplaceableRandomAccessCollection<
Base: RandomAccessCollection & RangeReplaceableCollection
> = LoggingRangeReplaceableCollection<Base>
//===----------------------------------------------------------------------===//
// Collections that count calls to `withContiguousMutableStorageIfAvailable`
//===----------------------------------------------------------------------===//
/// Interposes between `withContiguousMutableStorageIfAvailable` method calls
/// to increment a counter. Calls to this method from within dispatched methods
/// are uncounted by the standard logging collection wrapper.
public struct BufferAccessLoggingMutableCollection<
Base : MutableCollection
> {
public var base: Base
}
extension BufferAccessLoggingMutableCollection: LoggingType {
public typealias Log = MutableCollectionLog
public init(wrapping base: Base) {
self.base = base
}
}
extension BufferAccessLoggingMutableCollection: Sequence {
public typealias SubSequence = Base.SubSequence
public typealias Iterator = Base.Iterator
public typealias Element = Base.Element
public func makeIterator() -> Iterator {
return base.makeIterator()
}
}
extension BufferAccessLoggingMutableCollection: MutableCollection {
public typealias Index = Base.Index
public typealias Indices = Base.Indices
public var startIndex: Index {
return base.startIndex
}
public var endIndex: Index {
return base.endIndex
}
public var indices: Indices {
return base.indices
}
public subscript(position: Index) -> Element {
get {
return base[position]
}
set {
base[position] = newValue
}
}
public subscript(bounds: Range<Index>) -> SubSequence {
get {
return base[bounds]
}
set {
base[bounds] = newValue
}
}
public func index(after i: Index) -> Index {
return base.index(after: i)
}
public func index(_ i: Index, offsetBy n: Int) -> Index {
return base.index(i, offsetBy: n)
}
public func distance(from start: Index, to end: Index) -> Int {
return base.distance(from: start, to: end)
}
public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
Log._withUnsafeMutableBufferPointerIfSupported[selfType] += 1
let result = try base._withUnsafeMutableBufferPointerIfSupported(body)
if result != nil {
Log._withUnsafeMutableBufferPointerIfSupportedNonNilReturns[selfType] += 1
}
return result
}
public mutating func withContiguousMutableStorageIfAvailable<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
Log.withContiguousMutableStorageIfAvailable[selfType] += 1
let result = try base.withContiguousMutableStorageIfAvailable(body)
if result != nil {
Log.withContiguousMutableStorageIfAvailable[selfType] += 1
}
return result
}
}
public typealias BufferAccessLoggingMutableBidirectionalCollection<
Base: MutableCollection & BidirectionalCollection
> = BufferAccessLoggingMutableCollection<Base>
extension BufferAccessLoggingMutableBidirectionalCollection: BidirectionalCollection {
public func index(before i: Index) -> Index {
return base.index(before: i)
}
}
public typealias BufferAccessLoggingMutableRandomAccessCollection<
Base: MutableCollection & RandomAccessCollection
> = BufferAccessLoggingMutableCollection<Base>
//===----------------------------------------------------------------------===//
// Custom assertions
//===----------------------------------------------------------------------===//
public func expectCustomizable<T : LoggingType>(
_: T, _ counters: TypeIndexed<Int>,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) where
T.Base : LoggingType,
T.Log == T.Base.Log {
let newTrace = stackTrace.pushIf(showFrame, file: file, line: line)
expectNotEqual(0, counters[T.self], message(), stackTrace: newTrace)
expectEqual(
counters[T.self], counters[T.Base.self], message(), stackTrace: newTrace)
}
public func expectNotCustomizable<T : LoggingType>(
_: T, _ counters: TypeIndexed<Int>,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) where
T.Base : LoggingType,
T.Log == T.Base.Log {
let newTrace = stackTrace.pushIf(showFrame, file: file, line: line)
expectNotEqual(0, counters[T.self], message(), stackTrace: newTrace)
expectEqual(0, counters[T.Base.self], message(), stackTrace: newTrace)
}
| apache-2.0 | fdf498511cb0065f9932b4c56cd507c3 | 31.465672 | 86 | 0.707797 | 5.135033 | false | false | false | false |
amigocloud/amigoSurvey | iOS/amigoSurvey/amigoSurvey/Location/LocationViewModel.swift | 1 | 1587 | //
// LocationModel.swift
// amigoSurvey
//
// Created by Victor Chernetsky on 9/8/17.
// Copyright © 2017 AmigoCloud. All rights reserved.
//
import Foundation
import CoreLocation
class LocationModel {
var lat: Double = 0
var lng: Double = 0
var alt: Double = 0
var accuracy: Double = 0
var bearing: Double = 0
var speed: Double = 0
}
class LocationViewModel {
static var lastLocation: LocationModel = LocationModel()
static func updateLocation(location: CLLocation) {
lastLocation.lat = location.coordinate.latitude
lastLocation.lng = location.coordinate.longitude
lastLocation.alt = location.altitude
lastLocation.accuracy = location.horizontalAccuracy
lastLocation.bearing = location.course
lastLocation.speed = location.speed
}
static func getGPSInfoJSON() -> String {
let pos = LocationModel()
var json : String = ""
json = "{"
json += "\"gpsActive\":1,"
json += "\"longitude\":" + String(pos.lng) + ","
json += "\"latitude\":" + String(pos.lat) + ","
json += "\"altitude\":" + String(pos.alt) + ","
json += "\"horizontalAccuracy\":" + String(pos.accuracy) + ","
json += "\"bearing\":" + String(pos.bearing) + ","
json += "\"speed\":" + String(pos.speed)
json += "}"
return json
}
static func getLastLocationWKT() -> String {
let lat = lastLocation.lat
let lng = lastLocation.lng
return "SRID=4326;POINT(\(lng) \(lat))"
}
}
| gpl-3.0 | a6dff7bea62929ce14bc281ed8a10ca8 | 27.836364 | 70 | 0.587642 | 4.333333 | false | false | false | false |
brave/browser-ios | Storage/ThirdParty/SwiftData.swift | 1 | 41774 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* This is a heavily modified version of SwiftData.swift by Ryan Fowler
* This has been enhanced to support custom files, correct binding, versioning,
* and a streaming results via Cursors. The API has also been changed to use NSError, Cursors, and
* to force callers to request a connection before executing commands. Database creation helpers, savepoint
* helpers, image support, and other features have been removed.
*/
// SwiftData.swift
//
// Copyright (c) 2014 Ryan Fowler
//
// 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
import Shared
import XCGLogger
private let DatabaseBusyTimeout: Int32 = 3 * 1000
private let log = Logger.syncLogger
/**
* Handle to a SQLite database.
* Each instance holds a single connection that is shared across all queries.
*/
open class SwiftData {
let filename: String
static var EnableWAL = true
static var EnableForeignKeys = true
/// Used to keep track of the corrupted databases we've logged.
static var corruptionLogsWritten = Set<String>()
/// Used for testing.
static var ReuseConnections = true
/// For thread-safe access to the shared connection.
fileprivate let sharedConnectionQueue: DispatchQueue
/// Shared connection to this database.
fileprivate var sharedConnection: ConcreteSQLiteDBConnection?
fileprivate var key: String?
fileprivate var prevKey: String?
/// A simple state flag to track whether we should accept new connection requests.
/// If a connection request is made while the database is closed, a
/// FailedSQLiteDBConnection will be returned.
fileprivate(set) var closed = false
init(filename: String, key: String? = nil, prevKey: String? = nil) {
self.filename = filename
self.sharedConnectionQueue = DispatchQueue(label: "SwiftData queue: \(filename)", attributes: [])
// Ensure that multi-thread mode is enabled by default.
// See https://www.sqlite.org/threadsafe.html
assert(sqlite3_threadsafe() == 2)
self.key = key
self.prevKey = prevKey
}
fileprivate func getSharedConnection() -> ConcreteSQLiteDBConnection? {
var connection: ConcreteSQLiteDBConnection?
sharedConnectionQueue.sync {
if self.closed {
log.warning(">>> Database is closed for \(self.filename)")
return
}
if self.sharedConnection == nil {
log.debug(">>> Creating shared SQLiteDBConnection for \(self.filename) on thread \(Thread.current).")
self.sharedConnection = ConcreteSQLiteDBConnection(filename: self.filename, flags: SwiftData.Flags.readWriteCreate.toSQL(), key: self.key, prevKey: self.prevKey)
}
connection = self.sharedConnection
}
return connection
}
/**
* The real meat of all the execute methods. This is used internally to open and
* close a database connection and run a block of code inside it.
*/
func withConnection(_ flags: SwiftData.Flags, synchronous: Bool=true, cb: @escaping (_ db: SQLiteDBConnection) -> NSError?) -> NSError? {
/**
* We use a weak reference here instead of strongly retaining the connection because we don't want
* any control over when the connection deallocs. If the only owner of the connection (SwiftData)
* decides to dealloc it, we should respect that since the deinit method of the connection is tied
* to the app lifecycle. This is to prevent background disk access causing springboard crashes.
*/
weak var conn = getSharedConnection()
let queue = self.sharedConnectionQueue
if synchronous {
var error: NSError? = nil
queue.sync {
/**
* By the time this dispatch block runs, it is possible the user has backgrounded the app
* and the connection has been dealloc'ed since we last grabbed the reference
*/
guard let connection = SwiftData.ReuseConnections ? conn :
ConcreteSQLiteDBConnection(filename: filename, flags: flags.toSQL(), key: self.key, prevKey: self.prevKey) else {
error = cb(FailedSQLiteDBConnection()) ?? NSError(domain: "mozilla",
code: 0,
userInfo: [NSLocalizedDescriptionKey: "Could not create a connection"])
return
}
error = cb(connection)
}
return error
}
queue.async {
guard let connection = SwiftData.ReuseConnections ? conn :
ConcreteSQLiteDBConnection(filename: self.filename, flags: flags.toSQL(), key: self.key, prevKey: self.prevKey) else {
let _ = cb(FailedSQLiteDBConnection())
return
}
let _ = cb(connection)
}
return nil
}
func transaction(_ transactionClosure: @escaping (_ db: SQLiteDBConnection) -> Bool) -> NSError? {
return self.transaction(synchronous: true, transactionClosure: transactionClosure)
}
/**
* Helper for opening a connection, starting a transaction, and then running a block of code inside it.
* The code block can return true if the transaction should be committed. False if we should roll back.
*/
func transaction(synchronous: Bool=true, transactionClosure: @escaping (_ db: SQLiteDBConnection) -> Bool) -> NSError? {
return withConnection(SwiftData.Flags.readWriteCreate, synchronous: synchronous) { db in
if let err = db.executeChange("BEGIN EXCLUSIVE") {
log.warning("BEGIN EXCLUSIVE failed.")
return err
}
if transactionClosure(db) {
log.verbose("Op in transaction succeeded. Committing.")
if let err = db.executeChange("COMMIT") {
log.error("COMMIT failed. Rolling back.")
let _ = db.executeChange("ROLLBACK")
return err
}
} else {
log.debug("Op in transaction failed. Rolling back.")
if let err = db.executeChange("ROLLBACK") {
return err
}
}
return nil
}
}
/// Don't use this unless you know what you're doing. The deinitializer
/// should be used to achieve refcounting semantics.
func forceClose() {
sharedConnectionQueue.sync {
self.closed = true
self.sharedConnection = nil
}
}
/// Reopens a database that had previously been force-closed.
/// Does nothing if this database is already open.
func reopenIfClosed() {
sharedConnectionQueue.sync {
self.closed = false
}
}
public enum Flags {
case readOnly
case readWrite
case readWriteCreate
fileprivate func toSQL() -> Int32 {
switch self {
case .readOnly:
return SQLITE_OPEN_READONLY
case .readWrite:
return SQLITE_OPEN_READWRITE
case .readWriteCreate:
return SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
}
}
}
}
/**
* Wrapper class for a SQLite statement.
* This class helps manage the statement lifecycle. By holding a reference to the SQL connection, we ensure
* the connection is never deinitialized while the statement is active. This class is responsible for
* finalizing the SQL statement once it goes out of scope.
*/
private class SQLiteDBStatement {
var pointer: OpaquePointer?
fileprivate let connection: ConcreteSQLiteDBConnection
init(connection: ConcreteSQLiteDBConnection, query: String, args: [Any?]?) throws {
self.connection = connection
let status = sqlite3_prepare_v2(connection.sqliteDB, query, -1, &pointer, nil)
if status != SQLITE_OK {
throw connection.createErr("During: SQL Prepare \(query)", status: Int(status))
}
if let args = args,
let bindError = bind(args) {
throw bindError
}
}
/// Binds arguments to the statement.
fileprivate func bind(_ objects: [Any?]) -> NSError? {
let count = Int(sqlite3_bind_parameter_count(pointer))
if count < objects.count {
return connection.createErr("During: Bind", status: 202)
}
if count > objects.count {
return connection.createErr("During: Bind", status: 201)
}
for (index, obj) in objects.enumerated() {
var status: Int32 = SQLITE_OK
// Doubles also pass obj as Int, so order is important here.
if obj is Double {
status = sqlite3_bind_double(pointer, Int32(index+1), obj as! Double)
} else if obj is Int {
status = sqlite3_bind_int(pointer, Int32(index+1), Int32(obj as! Int))
} else if obj is Bool {
status = sqlite3_bind_int(pointer, Int32(index+1), (obj as! Bool) ? 1 : 0)
} else if obj is String {
typealias CFunction = @convention(c) (UnsafeMutableRawPointer?) -> Void
let transient = unsafeBitCast(-1, to: CFunction.self)
status = sqlite3_bind_text(pointer, Int32(index+1), (obj as! String).cString(using: String.Encoding.utf8)!, -1, transient)
} else if obj is Data {
status = sqlite3_bind_blob(pointer, Int32(index+1), ((obj as! Data) as NSData).bytes, -1, nil)
} else if obj is Date {
let timestamp = (obj as! Date).timeIntervalSince1970
status = sqlite3_bind_double(pointer, Int32(index+1), timestamp)
} else if obj is UInt64 {
status = sqlite3_bind_double(pointer, Int32(index+1), Double(obj as! UInt64))
} else if obj == nil {
status = sqlite3_bind_null(pointer, Int32(index+1))
}
if status != SQLITE_OK {
return connection.createErr("During: Bind", status: Int(status))
}
}
return nil
}
func close() {
if nil != self.pointer {
sqlite3_finalize(self.pointer)
self.pointer = nil
}
}
deinit {
if nil != self.pointer {
sqlite3_finalize(self.pointer)
}
}
}
protocol SQLiteDBConnection {
var lastInsertedRowID: Int { get }
var numberOfRowsModified: Int { get }
func executeChange(_ sqlStr: String) -> NSError?
func executeChange(_ sqlStr: String, withArgs args: Args?) -> NSError?
func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T)) -> Cursor<T>
func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T>
func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T>
func interrupt()
func checkpoint()
func checkpoint(_ mode: Int32)
func vacuum() -> NSError?
}
// Represents a failure to open.
class FailedSQLiteDBConnection: SQLiteDBConnection {
func executeChange(_ sqlStr: String, withArgs args: Args?) -> NSError? {
return self.fail("Non-open connection; can't execute change.")
}
fileprivate func fail(_ str: String) -> NSError {
return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: str])
}
var lastInsertedRowID: Int { return 0 }
var numberOfRowsModified: Int { return 0 }
func executeChange(_ sqlStr: String) -> NSError? {
return self.fail("Non-open connection; can't execute change.")
}
func executeQuery<T>(_ sqlStr: String) -> Cursor<T> {
return Cursor<T>(err: self.fail("Non-open connection; can't execute query."))
}
func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T)) -> Cursor<T> {
return Cursor<T>(err: self.fail("Non-open connection; can't execute query."))
}
func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> {
return Cursor<T>(err: self.fail("Non-open connection; can't execute query."))
}
func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> {
return Cursor<T>(err: self.fail("Non-open connection; can't execute query."))
}
func interrupt() {}
func checkpoint() {}
func checkpoint(_ mode: Int32) {}
func vacuum() -> NSError? {
return self.fail("Non-open connection; can't vacuum.")
}
}
open class ConcreteSQLiteDBConnection: SQLiteDBConnection {
fileprivate var sqliteDB: OpaquePointer?
fileprivate let filename: String
fileprivate let debug_enabled = false
fileprivate let queue: DispatchQueue
open var version: Int {
get {
return pragma("user_version", factory: IntFactory) ?? 0
}
set {
let _ = executeChange("PRAGMA user_version = \(newValue)")
}
}
fileprivate func setKey(_ key: String?) -> NSError? {
sqlite3_key(sqliteDB, key ?? "", Int32((key ?? "").characters.count))
let cursor = executeQuery("SELECT count(*) FROM sqlite_master;", factory: IntFactory, withArgs: nil as Args?)
if cursor.status != .success {
return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid key"])
}
return nil
}
fileprivate func reKey(_ oldKey: String?, newKey: String?) -> NSError? {
sqlite3_key(sqliteDB, oldKey ?? "", Int32((oldKey ?? "").characters.count))
sqlite3_rekey(sqliteDB, newKey ?? "", Int32((newKey ?? "").characters.count))
// Check that the new key actually works
sqlite3_key(sqliteDB, newKey ?? "", Int32((newKey ?? "").characters.count))
let cursor = executeQuery("SELECT count(*) FROM sqlite_master;", factory: IntFactory, withArgs: nil as Args?)
if cursor.status != .success {
return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Rekey failed"])
}
return nil
}
func interrupt() {
log.debug("Interrupt")
sqlite3_interrupt(sqliteDB)
}
fileprivate func pragma<T: Equatable>(_ pragma: String, expected: T?, factory: @escaping (SDRow) -> T, message: String) throws {
let cursorResult = self.pragma(pragma, factory: factory)
if cursorResult != expected {
log.error("\(message): \(cursorResult.debugDescription), \(expected.debugDescription)")
throw NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "PRAGMA didn't return expected output: \(message)."])
}
}
fileprivate func pragma<T>(_ pragma: String, factory: @escaping (SDRow) -> T) -> T? {
let cursor = executeQueryUnsafe("PRAGMA \(pragma)", factory: factory, withArgs: [] as Args)
defer { cursor.close() }
return cursor[0]
}
fileprivate func prepareShared() {
if SwiftData.EnableForeignKeys {
let _ = pragma("foreign_keys=ON", factory: IntFactory)
}
// Retry queries before returning locked errors.
sqlite3_busy_timeout(self.sqliteDB, DatabaseBusyTimeout)
}
fileprivate func prepareEncrypted(_ flags: Int32, key: String?, prevKey: String? = nil) throws {
// Setting the key needs to be the first thing done with the database.
if let _ = setKey(key) {
if let err = closeCustomConnection(immediately: true) {
log.error("Couldn't close connection: \(err). Failing to open.")
throw err
}
if let err = openWithFlags(flags) {
throw err
}
if let err = reKey(prevKey, newKey: key) {
log.error("Unable to encrypt database")
throw err
}
}
if SwiftData.EnableWAL {
log.info("Enabling WAL mode.")
try pragma("journal_mode=WAL", expected: "wal",
factory: StringFactory, message: "WAL journal mode set")
}
self.prepareShared()
}
fileprivate func prepareCleartext() throws {
// If we just created the DB -- i.e., no tables have been created yet -- then
// we can set the page size right now and save a vacuum.
//
// For where these values come from, see Bug 1213623.
//
// Note that sqlcipher uses cipher_page_size instead, but we don't set that
// because it needs to be set from day one.
let desiredPageSize = 32 * 1024
let _ = pragma("page_size=\(desiredPageSize)", factory: IntFactory)
let currentPageSize = pragma("page_size", factory: IntFactory)
// This has to be done without WAL, so we always hop into rollback/delete journal mode.
if currentPageSize != desiredPageSize {
try pragma("journal_mode=DELETE", expected: "delete",
factory: StringFactory, message: "delete journal mode set")
try pragma("page_size=\(desiredPageSize)", expected: nil,
factory: IntFactory, message: "Page size set")
log.info("Vacuuming to alter database page size from \(currentPageSize ?? 0) to \(desiredPageSize).")
if let err = self.vacuum() {
log.error("Vacuuming failed: \(err).")
} else {
log.debug("Vacuuming succeeded.")
}
}
if SwiftData.EnableWAL {
log.info("Enabling WAL mode.")
let desiredPagesPerJournal = 16
let desiredCheckpointSize = desiredPagesPerJournal * desiredPageSize
let desiredJournalSizeLimit = 3 * desiredCheckpointSize
/*
* With whole-module-optimization enabled in Xcode 7.2 and 7.2.1, the
* compiler seems to eagerly discard these queries if they're simply
* inlined, causing a crash in `pragma`.
*
* Hackily hold on to them.
*/
let journalModeQuery = "journal_mode=WAL"
let autoCheckpointQuery = "wal_autocheckpoint=\(desiredPagesPerJournal)"
let journalSizeQuery = "journal_size_limit=\(desiredJournalSizeLimit)"
try withExtendedLifetime(journalModeQuery, {
try pragma(journalModeQuery, expected: "wal",
factory: StringFactory, message: "WAL journal mode set")
})
try withExtendedLifetime(autoCheckpointQuery, {
try pragma(autoCheckpointQuery, expected: desiredPagesPerJournal,
factory: IntFactory, message: "WAL autocheckpoint set")
})
try withExtendedLifetime(journalSizeQuery, {
try pragma(journalSizeQuery, expected: desiredJournalSizeLimit,
factory: IntFactory, message: "WAL journal size limit set")
})
}
self.prepareShared()
}
init?(filename: String, flags: Int32, key: String? = nil, prevKey: String? = nil) {
log.debug("Opening connection to \(filename).")
self.filename = filename
self.queue = DispatchQueue(label: "SQLite connection: \(filename)", attributes: [])
if let failure = openWithFlags(flags) {
log.warning("Opening connection to \(filename) failed: \(failure).")
return nil
}
if key == nil && prevKey == nil {
do {
try self.prepareCleartext()
} catch {
return nil
}
} else {
do {
try self.prepareEncrypted(flags, key: key, prevKey: prevKey)
} catch {
return nil
}
}
}
deinit {
log.debug("deinit: closing connection on thread \(Thread.current).")
let _ = self.queue.sync {
self.closeCustomConnection()
}
}
open var lastInsertedRowID: Int {
return Int(sqlite3_last_insert_rowid(sqliteDB))
}
open var numberOfRowsModified: Int {
return Int(sqlite3_changes(sqliteDB))
}
func checkpoint() {
self.checkpoint(SQLITE_CHECKPOINT_FULL)
}
/**
* Blindly attempts a WAL checkpoint on all attached databases.
*/
func checkpoint(_ mode: Int32) {
guard sqliteDB != nil else {
log.warning("Trying to checkpoint a nil DB!")
return
}
log.debug("Running WAL checkpoint on \(self.filename) on thread \(Thread.current).")
sqlite3_wal_checkpoint_v2(sqliteDB, nil, mode, nil, nil)
log.debug("WAL checkpoint done on \(self.filename).")
}
func vacuum() -> NSError? {
return self.executeChange("VACUUM")
}
/// Creates an error from a sqlite status. Will print to the console if debug_enabled is set.
/// Do not call this unless you're going to return this error.
fileprivate func createErr(_ description: String, status: Int) -> NSError {
var msg = SDError.errorMessageFromCode(status)
if debug_enabled {
log.debug("SwiftData Error -> \(description)")
log.debug(" -> Code: \(status) - \(msg)")
}
if let errMsg = String(validatingUTF8: sqlite3_errmsg(sqliteDB)) {
msg += " " + errMsg
if debug_enabled {
log.debug(" -> Details: \(errMsg)")
}
}
return NSError(domain: "org.mozilla", code: status, userInfo: [NSLocalizedDescriptionKey: msg])
}
/// Open the connection. This is called when the db is created. You should not call it yourself.
fileprivate func openWithFlags(_ flags: Int32) -> NSError? {
let status = sqlite3_open_v2(filename.cString(using: String.Encoding.utf8)!, &sqliteDB, flags, nil)
if status != SQLITE_OK {
return createErr("During: Opening Database with Flags", status: Int(status))
}
return nil
}
/// Closes a connection. This is called via deinit. Do not call this yourself.
fileprivate func closeCustomConnection(immediately: Bool=false) -> NSError? {
log.debug("Closing custom connection for \(self.filename) on \(Thread.current).")
// TODO: add a lock here?
let db = self.sqliteDB
self.sqliteDB = nil
// Don't bother trying to call sqlite3_close multiple times.
guard db != nil else {
log.warning("Connection was nil.")
return nil
}
let status = immediately ? sqlite3_close(db) : sqlite3_close_v2(db)
// Note that if we use sqlite3_close_v2, this will still return SQLITE_OK even if
// there are outstanding prepared statements
if status != SQLITE_OK {
log.error("Got status \(status) while attempting to close.")
return createErr("During: closing database with flags", status: Int(status))
}
log.debug("Closed \(self.filename).")
return nil
}
open func executeChange(_ sqlStr: String) -> NSError? {
return self.executeChange(sqlStr, withArgs: nil)
}
/// Executes a change on the database.
open func executeChange(_ sqlStr: String, withArgs args: Args?) -> NSError? {
var error: NSError?
let statement: SQLiteDBStatement?
do {
statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args)
} catch let error1 as NSError {
error = error1
statement = nil
log.error("SQL error: \(error1.localizedDescription) for SQL \(sqlStr).")
}
// Close, not reset -- this isn't going to be reused.
defer { statement?.close() }
if let error = error {
// Special case: Write additional info to the database log in the case of a database corruption.
if error.code == Int(SQLITE_CORRUPT) {
writeCorruptionInfoForDBNamed(filename, toLogger: Logger.corruptLogger)
}
log.error("SQL error: \(error.localizedDescription) for SQL \(sqlStr).")
return error
}
let status = sqlite3_step(statement!.pointer)
if status != SQLITE_DONE && status != SQLITE_OK {
error = createErr("During: SQL Step \(sqlStr)", status: Int(status))
}
return error
}
func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T)) -> Cursor<T> {
return self.executeQuery(sqlStr, factory: factory, withArgs: nil)
}
/// Queries the database.
/// Returns a cursor pre-filled with the complete result set.
func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> {
var error: NSError?
let statement: SQLiteDBStatement?
do {
statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args)
} catch let error1 as NSError {
error = error1
statement = nil
}
// Close, not reset -- this isn't going to be reused, and the FilledSQLiteCursor
// consumes everything.
defer { statement?.close() }
if let error = error {
// Special case: Write additional info to the database log in the case of a database corruption.
if error.code == Int(SQLITE_CORRUPT) {
writeCorruptionInfoForDBNamed(filename, toLogger: Logger.corruptLogger)
}
log.error("SQL error: \(error.localizedDescription).")
return Cursor<T>(err: error)
}
return FilledSQLiteCursor<T>(statement: statement!, factory: factory)
}
func writeCorruptionInfoForDBNamed(_ dbFilename: String, toLogger logger: XCGLogger) {
DispatchQueue.global(qos: DispatchQoS.default.qosClass).sync {
guard !SwiftData.corruptionLogsWritten.contains(dbFilename) else { return }
logger.error("Corrupt DB detected! DB filename: \(dbFilename)")
let dbFileSize = ("file://\(dbFilename)".asURL)?.allocatedFileSize() ?? 0
logger.error("DB file size: \(dbFileSize) bytes")
logger.error("Integrity check:")
let args: [Any?]? = nil
let messages = self.executeQueryUnsafe("PRAGMA integrity_check", factory: StringFactory, withArgs: args)
defer { messages.close() }
if messages.status == CursorStatus.success {
for message in messages {
logger.error(message)
}
logger.error("----")
} else {
logger.error("Couldn't run integrity check: \(messages.statusMessage).")
}
// Write call stack.
logger.error("Call stack: ")
for message in Thread.callStackSymbols {
logger.error(" >> \(message)")
}
logger.error("----")
// Write open file handles.
let openDescriptors = FSUtils.openFileDescriptors()
logger.error("Open file descriptors: ")
for (k, v) in openDescriptors {
logger.error(" \(k): \(v)")
}
logger.error("----")
SwiftData.corruptionLogsWritten.insert(dbFilename)
}
}
// func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> {
// return self.executeQueryUnsafe(sqlStr, factory: factory, withArgs: args)
// }
/**
* Queries the database.
* Returns a live cursor that holds the query statement and database connection.
* Instances of this class *must not* leak outside of the connection queue!
*/
func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> {
var error: NSError?
let statement: SQLiteDBStatement?
do {
statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args)
} catch let error1 as NSError {
error = error1
statement = nil
}
if let error = error {
return Cursor(err: error)
}
return LiveSQLiteCursor(statement: statement!, factory: factory)
}
}
/// Helper for queries that return a single integer result.
func IntFactory(_ row: SDRow) -> Int {
return row[0] as! Int
}
/// Helper for queries that return a single String result.
func StringFactory(_ row: SDRow) -> String {
return row[0] as! String
}
/// Wrapper around a statement for getting data from a row. This provides accessors for subscript indexing
/// and a generator for iterating over columns.
class SDRow: Sequence {
// The sqlite statement this row came from.
fileprivate let statement: SQLiteDBStatement
// The columns of this database. The indices of these are assumed to match the indices
// of the statement.
fileprivate let columnNames: [String]
fileprivate init(statement: SQLiteDBStatement, columns: [String]) {
self.statement = statement
self.columnNames = columns
}
// Return the value at this index in the row
fileprivate func getValue(_ index: Int) -> Any? {
let i = Int32(index)
let type = sqlite3_column_type(statement.pointer, i)
var ret: Any? = nil
switch type {
case SQLITE_NULL, SQLITE_INTEGER:
//Everyone expects this to be an Int. On Ints larger than 2^31 this will lose information.
ret = Int(truncatingIfNeeded: sqlite3_column_int64(statement.pointer, i))
case SQLITE_TEXT:
if let text = sqlite3_column_text(statement.pointer, i) {
return String(cString: text)
}
case SQLITE_BLOB:
if let blob = sqlite3_column_blob(statement.pointer, i) {
let size = sqlite3_column_bytes(statement.pointer, i)
ret = Data(bytes: blob, count: Int(size))
}
case SQLITE_FLOAT:
ret = Double(sqlite3_column_double(statement.pointer, i))
default:
log.warning("SwiftData Warning -> Column: \(index) is of an unrecognized type, returning nil")
}
return ret
}
// Accessor getting column 'key' in the row
subscript(key: Int) -> Any? {
return getValue(key)
}
// Accessor getting a named column in the row. This (currently) depends on
// the columns array passed into this Row to find the correct index.
subscript(key: String) -> Any? {
get {
if let index = columnNames.index(of: key) {
return getValue(index)
}
return nil
}
}
// Allow iterating through the row. This is currently broken.
func makeIterator() -> AnyIterator<Any> {
let nextIndex = 0
return AnyIterator() {
// This crashes the compiler. Yay!
if nextIndex < self.columnNames.count {
return nil // self.getValue(nextIndex)
}
return nil
}
}
}
/// Helper for pretty printing SQL (and other custom) error codes.
private struct SDError {
fileprivate static func errorMessageFromCode(_ errorCode: Int) -> String {
switch errorCode {
case -1:
return "No error"
// SQLite error codes and descriptions as per: http://www.sqlite.org/c3ref/c_abort.html
case 0:
return "Successful result"
case 1:
return "SQL error or missing database"
case 2:
return "Internal logic error in SQLite"
case 3:
return "Access permission denied"
case 4:
return "Callback routine requested an abort"
case 5:
return "The database file is busy"
case 6:
return "A table in the database is locked"
case 7:
return "A malloc() failed"
case 8:
return "Attempt to write a readonly database"
case 9:
return "Operation terminated by sqlite3_interrupt()"
case 10:
return "Some kind of disk I/O error occurred"
case 11:
return "The database disk image is malformed"
case 12:
return "Unknown opcode in sqlite3_file_control()"
case 13:
return "Insertion failed because database is full"
case 14:
return "Unable to open the database file"
case 15:
return "Database lock protocol error"
case 16:
return "Database is empty"
case 17:
return "The database schema changed"
case 18:
return "String or BLOB exceeds size limit"
case 19:
return "Abort due to constraint violation"
case 20:
return "Data type mismatch"
case 21:
return "Library used incorrectly"
case 22:
return "Uses OS features not supported on host"
case 23:
return "Authorization denied"
case 24:
return "Auxiliary database format error"
case 25:
return "2nd parameter to sqlite3_bind out of range"
case 26:
return "File opened that is not a database file"
case 27:
return "Notifications from sqlite3_log()"
case 28:
return "Warnings from sqlite3_log()"
case 100:
return "sqlite3_step() has another row ready"
case 101:
return "sqlite3_step() has finished executing"
// Custom SwiftData errors
// Binding errors
case 201:
return "Not enough objects to bind provided"
case 202:
return "Too many objects to bind provided"
// Custom connection errors
case 301:
return "A custom connection is already open"
case 302:
return "Cannot open a custom connection inside a transaction"
case 303:
return "Cannot open a custom connection inside a savepoint"
case 304:
return "A custom connection is not currently open"
case 305:
return "Cannot close a custom connection inside a transaction"
case 306:
return "Cannot close a custom connection inside a savepoint"
// Index and table errors
case 401:
return "At least one column name must be provided"
case 402:
return "Error extracting index names from sqlite_master"
case 403:
return "Error extracting table names from sqlite_master"
// Transaction and savepoint errors
case 501:
return "Cannot begin a transaction within a savepoint"
case 502:
return "Cannot begin a transaction within another transaction"
// Unknown error
default:
return "Unknown error"
}
}
}
/// Provides access to the result set returned by a database query.
/// The entire result set is cached, so this does not retain a reference
/// to the statement or the database connection.
private class FilledSQLiteCursor<T>: ArrayCursor<T> {
fileprivate init(statement: SQLiteDBStatement, factory: (SDRow) -> T) {
var status = CursorStatus.success
var statusMessage = ""
let data = FilledSQLiteCursor.getValues(statement, factory: factory, status: &status, statusMessage: &statusMessage)
super.init(data: data, status: status, statusMessage: statusMessage)
}
/// Return an array with the set of results and release the statement.
fileprivate class func getValues(_ statement: SQLiteDBStatement, factory: (SDRow) -> T, status: inout CursorStatus, statusMessage: inout String) -> [T] {
var rows = [T]()
var count = 0
status = CursorStatus.success
statusMessage = "Success"
var columns = [String]()
let columnCount = sqlite3_column_count(statement.pointer)
for i in 0..<columnCount {
let columnName = String(cString: sqlite3_column_name(statement.pointer, i))
columns.append(columnName)
}
while true {
let sqlStatus = sqlite3_step(statement.pointer)
if sqlStatus != SQLITE_ROW {
if sqlStatus != SQLITE_DONE {
// NOTE: By setting our status to failure here, we'll report our count as zero,
// regardless of how far we've read at this point.
status = CursorStatus.failure
statusMessage = SDError.errorMessageFromCode(Int(sqlStatus))
}
break
}
count += 1
let row = SDRow(statement: statement, columns: columns)
let result = factory(row)
rows.append(result)
}
return rows
}
}
/// Wrapper around a statement to help with iterating through the results.
private class LiveSQLiteCursor<T>: Cursor<T> {
fileprivate var statement: SQLiteDBStatement!
// Function for generating objects of type T from a row.
fileprivate let factory: (SDRow) -> T
// Status of the previous fetch request.
fileprivate var sqlStatus: Int32 = 0
// Number of rows in the database
// XXX - When Cursor becomes an interface, this should be a normal property, but right now
// we can't override the Cursor getter for count with a stored property.
fileprivate var _count: Int = 0
override var count: Int {
get {
if status != .success {
return 0
}
return _count
}
}
fileprivate var position: Int = -1 {
didSet {
// If we're already there, shortcut out.
if oldValue == position {
return
}
var stepStart = oldValue
// If we're currently somewhere in the list after this position
// we'll have to jump back to the start.
if position < oldValue {
sqlite3_reset(self.statement.pointer)
stepStart = -1
}
// Now step up through the list to the requested position
for _ in stepStart..<position {
sqlStatus = sqlite3_step(self.statement.pointer)
}
}
}
init(statement: SQLiteDBStatement, factory: @escaping (SDRow) -> T) {
self.factory = factory
self.statement = statement
// The only way I know to get a count. Walk through the entire statement to see how many rows there are.
var count = 0
self.sqlStatus = sqlite3_step(statement.pointer)
while self.sqlStatus != SQLITE_DONE {
count += 1
self.sqlStatus = sqlite3_step(statement.pointer)
}
sqlite3_reset(statement.pointer)
self._count = count
super.init(status: .success, msg: "success")
}
// Helper for finding all the column names in this statement.
fileprivate lazy var columns: [String] = {
// This untangles all of the columns and values for this row when its created
let columnCount = sqlite3_column_count(self.statement.pointer)
var columns = [String]()
for i: Int32 in 0 ..< columnCount {
let columnName = String(cString: sqlite3_column_name(self.statement.pointer, i))
columns.append(columnName)
}
return columns
}()
override subscript(index: Int) -> T? {
get {
if status != .success {
return nil
}
self.position = index
if self.sqlStatus != SQLITE_ROW {
return nil
}
let row = SDRow(statement: statement, columns: self.columns)
return self.factory(row)
}
}
override func close() {
statement = nil
super.close()
}
}
| mpl-2.0 | d4cf30545f354007dbbf335b61617456 | 36.804525 | 177 | 0.598171 | 4.802713 | false | false | false | false |
PrashantMangukiya/SwiftUIDemo | Demo36-IndexedTableView/Demo36-IndexedTableView/ListTableViewController.swift | 1 | 4961 | //
// ListTableViewController.swift
// Demo36-IndexedTableView
//
// Created by Prashant on 21/10/15.
// Copyright © 2015 PrashantKumar Mangukiya. All rights reserved.
//
import UIKit
class ListTableViewController: UITableViewController {
// array of fruit list
var fruitList: [String] = Array()
// array of fruit list that converted into Group (i.e. section)
var fruitListGrouped = NSDictionary() as! [String : [String]]
// array of section titles
var sectionTitleList = [String]()
// MARK: - View functions
override func viewDidLoad() {
super.viewDidLoad()
// create data for the list
self.createData()
// split data into section
self.splitDataInToSection()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
// return the number of sections
override func numberOfSections(in tableView: UITableView) -> Int {
return self.fruitListGrouped.count
}
// return the number of rows
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// find section title
let sectionTitle = self.sectionTitleList[section]
// find fruit list for given section title
let fruits = self.fruitListGrouped[sectionTitle]
// return count for fruits
return fruits!.count
}
// return cell for given row
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// collect reusable cell
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
// Configure the cell...
// find section title
let sectionTitle = self.sectionTitleList[(indexPath as NSIndexPath).section]
// find fruit list for given section title
let fruits = self.fruitListGrouped[sectionTitle]
// find fruit name based on the row within section
cell.textLabel?.text = fruits![(indexPath as NSIndexPath).row]
// return cell
return cell
}
// return section header title
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sectionTitleList[section]
}
// return title list for section index
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return self.sectionTitleList
}
// return section for given section index title
override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
return index
}
// MARK: - Utility functions
fileprivate func createData() {
// fill up data
self.fruitList = [
"Strawberry",
"Apple", "Apricot", "Avocado",
"Banana", "Blueberry",
"Coconut", "Custard Apple",
"Dates", "Durian",
"Fig",
"Gooseberry", "Grapes", "Guava",
"Jackfruit",
"Lemon", "Lime", "Longan", "Lychee",
"Mango",
"Orange",
"Papaya", "Pear", "Pineapple", "Pomogranate",
"Raspberry",
"Watermelon"
]
// sort the array (Important)
self.fruitList = self.fruitList.sorted()
}
fileprivate func splitDataInToSection() {
// set section title "" at initial
var sectionTitle: String = ""
// iterate all records from array
for i in 0..<self.fruitList.count {
// get current record
let currentRecord = self.fruitList[i]
// find first character from current record
let firstChar = currentRecord[currentRecord.startIndex]
// convert first character into string
let firstCharString = "\(firstChar)"
// if first character not match with past section title then create new section
if firstCharString != sectionTitle {
// set new title for section
sectionTitle = firstCharString
// add new section having key as section title and value as empty array of string
self.fruitListGrouped[sectionTitle] = [String]()
// append title within section title list
self.sectionTitleList.append(sectionTitle)
}
// add record to the section
self.fruitListGrouped[firstCharString]?.append(currentRecord)
}
}
}
| mit | 4d0fe03686cdcbabe14d707742dc44c3 | 28.879518 | 120 | 0.579637 | 5.373781 | false | false | false | false |
ssathy2/SwiftCollectionViewTest | SwiftCollectionViewTest/LiveDataServices.swift | 1 | 2082 | //
// LiveDataServices.swift
// SwiftCollectionViewTest
//
// Created by Sidd Sathyam on 6/4/14.
// Copyright (c) 2014 dotdotdot. All rights reserved.
//
import Foundation
import UIKit
import Argo
class StackOverflowLiveServices: StackOverflowServices {
let baseURL = "http://api.stackexchange.com/2.2/"
let requestFetcher: RequestFetcher = RequestFetcher(baseURL: "http://api.stackexchange.com/2.2/", defaultParameters: ["site" : "stackoverflow"])
class func sharedInstance() -> AnyObject {
struct Static {
static var sharedManager: StackOverflowLiveServices? = nil
static var onceToken: dispatch_once_t = 0
}
dispatch_once(&Static.onceToken, {
Static.sharedManager = StackOverflowLiveServices()
})
return Static.sharedManager!
}
func fetchSearchResults(query: String, page: Int, completionHandler handler: IDQuestionsHandler) {
let url = "\(self.baseURL)search?"
let urlParams = ["intitle" : query, "page" : page.description, "site" : "stackoverflow"]
let request : IDURLRequest = IDURLRequest.createRequest(IDURLRequest.HTTPMethod.GET, stringURL: url, urlParams: urlParams, headers: nil)
self.requestFetcher.fetchJSON(request) { (innerClosure) -> Void in
do {
var allItems : [Question] = Array<Question>()
if let j: NSDictionary = try innerClosure() as NSDictionary? {
let items : [NSDictionary]? = j.valueForKey("items") as? [NSDictionary]
for item in items!
{
allItems.append(decode(item)!)
}
}
handler(innerClosure: { return allItems })
} catch let error {
handler(innerClosure: { throw error })
}
}
}
func fetchImage(url: NSURL, completionHandler handler: IDURLImageResponseHandler){
let request = IDURLRequest(URL: url)
self.requestFetcher.fetchImage(request) { (innerClosure) -> Void in
handler(innerClosure: innerClosure)
}
}
} | mit | c02976da7cbd60168808f9848281192c | 36.872727 | 148 | 0.635447 | 4.346555 | false | false | false | false |
christophhagen/Signal-iOS | SignalMessaging/utils/ConversationSearcher.swift | 1 | 3350 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
import SignalServiceKit
@objc
public class ConversationSearcher: NSObject {
@objc
public static let shared: ConversationSearcher = ConversationSearcher()
override private init() {
super.init()
}
@objc(filterThreads:withSearchText:)
public func filterThreads(_ threads: [TSThread], searchText: String) -> [TSThread] {
guard searchText.trimmingCharacters(in: .whitespacesAndNewlines).count > 0 else {
return threads
}
return threads.filter { thread in
switch thread {
case let groupThread as TSGroupThread:
return self.groupThreadSearcher.matches(item: groupThread, query: searchText)
case let contactThread as TSContactThread:
return self.contactThreadSearcher.matches(item: contactThread, query: searchText)
default:
owsFail("Unexpected thread type: \(thread)")
return false
}
}
}
@objc(filterGroupThreads:withSearchText:)
public func filterGroupThreads(_ groupThreads: [TSGroupThread], searchText: String) -> [TSGroupThread] {
guard searchText.trimmingCharacters(in: .whitespacesAndNewlines).count > 0 else {
return groupThreads
}
return groupThreads.filter { groupThread in
return self.groupThreadSearcher.matches(item: groupThread, query: searchText)
}
}
@objc(filterSignalAccounts:withSearchText:)
public func filterSignalAccounts(_ signalAccounts: [SignalAccount], searchText: String) -> [SignalAccount] {
guard searchText.trimmingCharacters(in: .whitespacesAndNewlines).count > 0 else {
return signalAccounts
}
return signalAccounts.filter { signalAccount in
self.signalAccountSearcher.matches(item: signalAccount, query: searchText)
}
}
// MARK: - Helpers
// MARK: Searchers
private lazy var groupThreadSearcher: Searcher<TSGroupThread> = Searcher { (groupThread: TSGroupThread) in
let groupName = groupThread.groupModel.groupName
let memberStrings = groupThread.groupModel.groupMemberIds.map { recipientId in
self.indexingString(recipientId: recipientId)
}.joined(separator: " ")
return "\(memberStrings) \(groupName ?? "")"
}
private lazy var contactThreadSearcher: Searcher<TSContactThread> = Searcher { (contactThread: TSContactThread) in
let recipientId = contactThread.contactIdentifier()
return self.indexingString(recipientId: recipientId)
}
private lazy var signalAccountSearcher: Searcher<SignalAccount> = Searcher { (signalAccount: SignalAccount) in
let recipientId = signalAccount.recipientId
return self.indexingString(recipientId: recipientId)
}
private var contactsManager: OWSContactsManager {
return Environment.current().contactsManager
}
private func indexingString(recipientId: String) -> String {
let contactName = contactsManager.displayName(forPhoneIdentifier: recipientId)
let profileName = contactsManager.profileName(forRecipientId: recipientId)
return "\(recipientId) \(contactName) \(profileName ?? "")"
}
}
| gpl-3.0 | 60d8e4f90cdcdbf8cccab796db27c9de | 36.222222 | 118 | 0.681493 | 5.138037 | false | false | false | false |
KyoheiG3/RxSwift | RxExample/RxExample/Examples/WikipediaImageSearch/Views/WikipediaSearchViewController.swift | 8 | 3336 | //
// WikipediaSearchViewController.swift
// RxExample
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
class WikipediaSearchViewController: ViewController {
@IBOutlet var searchBar: UISearchBar!
@IBOutlet var resultsTableView: UITableView!
@IBOutlet var emptyView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
}
// lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = .all
configureTableDataSource()
configureKeyboardDismissesOnScroll()
configureNavigateOnRowClick()
configureActivityIndicatorsShow()
}
func configureTableDataSource() {
resultsTableView.register(UINib(nibName: "WikipediaSearchCell", bundle: nil), forCellReuseIdentifier: "WikipediaSearchCell")
resultsTableView.rowHeight = 194
resultsTableView.hideEmptyCells()
// This is for clarity only, don't use static dependencies
let API = DefaultWikipediaAPI.sharedAPI
let results = searchBar.rx.text.orEmpty
.asDriver()
.throttle(0.3)
.distinctUntilChanged()
.flatMapLatest { query in
API.getSearchResults(query)
.retry(3)
.retryOnBecomesReachable([], reachabilityService: Dependencies.sharedDependencies.reachabilityService)
.startWith([]) // clears results on new search term
.asDriver(onErrorJustReturn: [])
}
.map { results in
results.map(SearchResultViewModel.init)
}
results
.drive(resultsTableView.rx.items(cellIdentifier: "WikipediaSearchCell", cellType: WikipediaSearchCell.self)) { (_, viewModel, cell) in
cell.viewModel = viewModel
}
.addDisposableTo(disposeBag)
results
.map { $0.count != 0 }
.drive(self.emptyView.rx.isHidden)
.addDisposableTo(disposeBag)
}
func configureKeyboardDismissesOnScroll() {
let searchBar = self.searchBar
resultsTableView.rx.contentOffset
.asDriver()
.drive(onNext: { _ in
if searchBar?.isFirstResponder ?? false {
_ = searchBar?.resignFirstResponder()
}
})
.addDisposableTo(disposeBag)
}
func configureNavigateOnRowClick() {
let wireframe = DefaultWireframe.sharedInstance
resultsTableView.rx.modelSelected(SearchResultViewModel.self)
.asDriver()
.drive(onNext: { searchResult in
wireframe.open(url:searchResult.searchResult.URL)
})
.addDisposableTo(disposeBag)
}
func configureActivityIndicatorsShow() {
Driver.combineLatest(
DefaultWikipediaAPI.sharedAPI.loadingWikipediaData,
DefaultImageService.sharedImageService.loadingImage
) { $0 || $1 }
.distinctUntilChanged()
.drive(UIApplication.shared.rx.isNetworkActivityIndicatorVisible)
.addDisposableTo(disposeBag)
}
}
| mit | a4b0b54f91f6d4b33fdfdf62fc77b2bc | 30.462264 | 146 | 0.616792 | 5.623946 | false | true | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Edit data/Edit feature attachments/EditFeatureAttachmentsViewController.swift | 1 | 4485 | // Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class EditFeatureAttachmentsViewController: UIViewController {
@IBOutlet private weak var mapView: AGSMapView!
private let featureLayer: AGSFeatureLayer
private var lastQuery: AGSCancelable?
private var selectedFeature: AGSArcGISFeature?
required init?(coder aDecoder: NSCoder) {
let featureServiceURL = URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer/0")!
let featureTable = AGSServiceFeatureTable(url: featureServiceURL)
self.featureLayer = AGSFeatureLayer(featureTable: featureTable)
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// add the source code button item to the right of navigation bar
(navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = [
"EditFeatureAttachmentsViewController",
"AttachmentsTableViewController"
]
let map = AGSMap(basemapStyle: .arcGISOceans)
map.operationalLayers.add(featureLayer)
mapView.map = map
mapView.setViewpoint(AGSViewpoint(
center: AGSPoint(x: 0, y: 0, spatialReference: .webMercator()),
scale: 100000000
))
mapView.touchDelegate = self
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let navController = segue.destination as? UINavigationController,
let controller = navController.viewControllers.first as? AttachmentsTableViewController {
controller.feature = selectedFeature
controller.isModalInPresentation = true
}
}
}
extension EditFeatureAttachmentsViewController: AGSGeoViewTouchDelegate {
func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
if let lastQuery = lastQuery {
lastQuery.cancel()
}
// hide the callout
mapView.callout.dismiss()
lastQuery = mapView.identifyLayer(featureLayer, screenPoint: screenPoint, tolerance: 12, returnPopupsOnly: false, maximumResults: 1) { [weak self] (identifyLayerResult: AGSIdentifyLayerResult) in
guard let self = self else {
return
}
if let error = identifyLayerResult.error {
print(error)
} else if let features = identifyLayerResult.geoElements as? [AGSArcGISFeature],
let feature = features.first,
// show callout for the first feature
let title = feature.attributes["typdamage"] as? String {
// fetch attachment
feature.fetchAttachments { (attachments: [AGSAttachment]?, error: Error?) in
if let error = error {
print(error)
} else if let attachments = attachments {
let detail = "Number of attachments: \(attachments.count)"
self.mapView.callout.title = title
self.mapView.callout.detail = detail
self.mapView.callout.delegate = self
self.mapView.callout.show(for: feature, tapLocation: mapPoint, animated: true)
// update selected feature
self.selectedFeature = feature
}
}
}
}
}
}
extension EditFeatureAttachmentsViewController: AGSCalloutDelegate {
func didTapAccessoryButton(for callout: AGSCallout) {
// hide the callout
mapView.callout.dismiss()
// show the attachments list vc
performSegue(withIdentifier: "AttachmentsSegue", sender: self)
}
}
| apache-2.0 | 562f01f4d08f153382f4237eb115e5cf | 39.405405 | 203 | 0.631215 | 5.178984 | false | false | false | false |
brentdax/swift | stdlib/public/core/SequenceWrapper.swift | 1 | 4112 | //===--- SequenceWrapper.swift - sequence/collection wrapper protocols ----===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// To create a Sequence that forwards requirements to an
// underlying Sequence, have it conform to this protocol.
//
//===----------------------------------------------------------------------===//
/// A type that is just a wrapper over some base Sequence
@_show_in_interface
public // @testable
protocol _SequenceWrapper : Sequence {
associatedtype Base : Sequence where Base.Element == Element
associatedtype Iterator = Base.Iterator
associatedtype SubSequence = Base.SubSequence
var _base: Base { get }
}
extension _SequenceWrapper {
@inlinable // generic-performance
public var underestimatedCount: Int {
return _base.underestimatedCount
}
@inlinable // generic-performance
public func _preprocessingPass<R>(
_ preprocess: () throws -> R
) rethrows -> R? {
return try _base._preprocessingPass(preprocess)
}
}
extension _SequenceWrapper where Iterator == Base.Iterator {
@inlinable // generic-performance
public __consuming func makeIterator() -> Iterator {
return self._base.makeIterator()
}
@inlinable // generic-performance
@discardableResult
public __consuming func _copyContents(
initializing buf: UnsafeMutableBufferPointer<Element>
) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {
return _base._copyContents(initializing: buf)
}
}
extension _SequenceWrapper {
@inlinable // generic-performance
public func map<T>(
_ transform: (Element) throws -> T
) rethrows -> [T] {
return try _base.map(transform)
}
@inlinable // generic-performance
public __consuming func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {
return try _base.filter(isIncluded)
}
@inlinable // generic-performance
public func forEach(_ body: (Element) throws -> Void) rethrows {
return try _base.forEach(body)
}
@inlinable // generic-performance
public func _customContainsEquatableElement(
_ element: Element
) -> Bool? {
return _base._customContainsEquatableElement(element)
}
@inlinable // generic-performance
public __consuming func _copyToContiguousArray()
-> ContiguousArray<Element> {
return _base._copyToContiguousArray()
}
}
extension _SequenceWrapper where SubSequence == Base.SubSequence {
@inlinable // generic-performance
public __consuming func dropFirst(_ n: Int) -> SubSequence {
return _base.dropFirst(n)
}
@inlinable // generic-performance
public __consuming func dropLast(_ n: Int) -> SubSequence {
return _base.dropLast(n)
}
@inlinable // generic-performance
public __consuming func prefix(_ maxLength: Int) -> SubSequence {
return _base.prefix(maxLength)
}
@inlinable // generic-performance
public __consuming func suffix(_ maxLength: Int) -> SubSequence {
return _base.suffix(maxLength)
}
@inlinable // generic-performance
public __consuming func drop(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
return try _base.drop(while: predicate)
}
@inlinable // generic-performance
public __consuming func prefix(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
return try _base.prefix(while: predicate)
}
@inlinable // generic-performance
public __consuming func split(
maxSplits: Int, omittingEmptySubsequences: Bool,
whereSeparator isSeparator: (Element) throws -> Bool
) rethrows -> [SubSequence] {
return try _base.split(
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences,
whereSeparator: isSeparator
)
}
}
| apache-2.0 | 7076af70fc2b045f5b7f1bd5bed1f72e | 29.459259 | 80 | 0.677529 | 4.764774 | false | false | false | false |
orta/RxSwift | RxSwift/RxSwift/Disposables/SerialDisposable.swift | 3 | 1435 | //
// SerialDisposable.swift
// Rx
//
// Created by Krunoslav Zaher on 3/12/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
public class SerialDisposable : DisposeBase, Cancelable {
typealias State = (
current: Disposable?,
disposed: Bool
)
var lock = Lock()
var state: State = (
current: nil,
disposed: false
)
public var disposed: Bool {
get {
return state.disposed
}
}
override public init() {
super.init()
}
public func setDisposable(disposable: Disposable) {
var disposable: Disposable? = self.lock.calculateLocked {
if state.disposed {
return disposable
}
else {
var toDispose = state.current
state.current = disposable
return toDispose
}
}
if let disposable = disposable {
disposable.dispose()
}
}
public func dispose() {
var disposable: Disposable? = self.lock.calculateLocked {
if state.disposed {
return nil
}
else {
state.disposed = true
return state.current
}
}
if let disposable = disposable {
disposable.dispose()
}
}
} | mit | 5330f760c1425509049783f562e48c20 | 21.092308 | 65 | 0.499652 | 5.25641 | false | false | false | false |
andrewarrow/boring_company_chat | chat4work/ComposeMessage.swift | 1 | 6467 | //
// CurrentCompany.swift
// chat4work
//
// Created by A Arrow on 6/7/17.
// Copyright © 2017 755R3VBZ84. All rights reserved.
//
import Cocoa
import Moya
import RxSwift
import RealmSwift
class ComposeMessage: NSView, NSTextFieldDelegate {
let text = NSTextField(frame: NSMakeRect(5, 5, 600, 50))
var disposeBag = DisposeBag()
var channel: ChannelObject?
func channelDidChange(notification: NSNotification) {
let b = notification.object as! ButtonWithStringTag
channel = b.channel
}
func pasteText(notification: NSNotification) {
let b = notification.object as! String
text.stringValue = text.stringValue + "" + b
}
func addToArrayOfTeams(id: String) {
let defaults = UserDefaults.standard
let existing = UserDefaults.standard.value(forKey: "bcc_teams")
if (existing != nil) {
var to_save = defaults.value(forKey: "bcc_teams") as! Array<String>
to_save.append(id)
defaults.set(to_save, forKey: "bcc_teams")
} else {
let to_save = [id]
defaults.set(to_save, forKey: "bcc_teams")
}
}
func addNewTeam(token: String) {
let provider = RxMoyaProvider<ChatService>()
let channelApi = ChannelApiImpl(provider: provider)
channelApi.getTeamInfo(token: token).subscribe(
onNext: { team in
Swift.print("\(team)")
var jsonTeam = Team(withToken: token, id: team.id!)!
jsonTeam.icon = team.icon
jsonTeam.name = team.name
jsonTeam.url = team.url
jsonTeam.index = 1
let JSONString = jsonTeam.toJSONString(prettyPrint: false)
Swift.print("\(String(describing: JSONString))")
let defaults = UserDefaults.standard
defaults.set(JSONString, forKey: "bcc_\(team.id!)")
self.addToArrayOfTeams(id: team.id!)
let existing = UserDefaults.standard.value(forKey: "bcc_teams")
if (existing != nil) {
let defaults = UserDefaults.standard
let to_save = defaults.value(forKey: "bcc_teams") as! Array<String>
jsonTeam.index = to_save.count-1
}
NotificationCenter.default.post(
name:NSNotification.Name(rawValue: "newTeamAdded"),
object: jsonTeam)
},
onError: { error in
}).addDisposableTo(disposeBag)
}
func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
if commandSelector == #selector(NSResponder.insertNewline(_:)) {
let realm = try! Realm()
if text.stringValue.hasPrefix("/token ") {
let tokens = text.stringValue.components(separatedBy: " ")
text.stringValue = ""
addNewTeam(token: tokens[1])
return true
} else if text.stringValue.hasPrefix("/logout all") {
let existing = UserDefaults.standard.value(forKey: "bcc_teams") as! Array<String>
for team in existing {
UserDefaults.standard.removeObject(forKey: "bcc_\(team)")
}
UserDefaults.standard.removeObject(forKey: "bcc_teams")
try! realm.write {
realm.deleteAll()
}
exit(1)
} else if text.stringValue.hasPrefix("/logout") {
text.stringValue = ""
NotificationCenter.default.post(
name:NSNotification.Name(rawValue: "teamLogout"),
object: nil)
return true
}
let provider = RxMoyaProvider<ChatService>()
let channelApi = ChannelApiImpl(provider: provider)
let def = ""
let json = UserDefaults.standard.value(forKey: "bcc_\(channel?.team ?? def)") as! String
let team = Team(JSONString: json)!
let say = text.stringValue
text.stringValue = ""
channelApi.postMessage(token: team.token!, id: (channel?.id)!, text: say).subscribe(
onNext: { message in
//NSLog("\(String(describing: message.ts))")
let mo = MessageObject()
mo.ts = message.ts!
mo.tsd = Double(mo.ts)!
mo.channel = (self.channel?.id)!
mo.text = say
mo.user = message.user!
mo.username = "me"
let pkey = "\(team.id!).\(mo.user)"
if let existing = realm.object(ofType: UserObject.self,
forPrimaryKey: pkey as AnyObject) {
mo.username = existing.name
}
mo.team = team.id!
mo.id = "\(team.id!).\(self.channel?.id ?? "").\(mo.ts)"
let existing = realm.object(ofType: MessageObject.self, forPrimaryKey: mo.id as AnyObject)
if (existing == nil) {
try! realm.write {
realm.add(mo)
}
}
NotificationCenter.default.post(
name:NSNotification.Name(rawValue: "contentIsReady"),
object: ["team": mo.team, "channel": mo.channel])
},
onError: { error in
}).addDisposableTo(disposeBag)
return true
}
return false
}
override init(frame frameRect: NSRect) {
super.init(frame:frameRect);
//autoresizingMask.insert(NSAutoresizingMaskOptions.viewMinYMargin)
autoresizingMask.insert(NSAutoresizingMaskOptions.viewMaxYMargin)
translatesAutoresizingMaskIntoConstraints = true
NotificationCenter.default.addObserver(self,
selector: #selector(pasteText),
name: NSNotification.Name(rawValue: "pasteText"),
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(channelDidChange),
name: NSNotification.Name(rawValue: "channelDidChange"),
object: nil)
wantsLayer = true
layer?.backgroundColor = NSColor.darkGray.cgColor
text.stringValue = ""
text.isEditable = true
text.backgroundColor = NSColor.white
text.isBordered = true
text.font = NSFont.systemFont(ofSize: 14.0)
text.delegate = self;
addSubview(text)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | a3d4e2422018417c075d98212e2059f8 | 30.236715 | 107 | 0.574544 | 4.645115 | false | false | false | false |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Profile Editor Toolbar/ProfileEditorWindowToolbarItemTitle.swift | 1 | 7131 | //
// ProfileEditorToolbarItemTitle.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Cocoa
class ProfileEditorWindowToolbarItemTitle: NSView {
// MARK: -
// MARK: Variables
public weak var profile: Profile?
let toolbarItemHeight: CGFloat = 32.0
let textFieldTitle = NSTextField()
let toolbarItem: NSToolbarItem
var selectionTitle: String?
// MARK: -
// MARK: Initialization
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(profile: Profile) {
// ---------------------------------------------------------------------
// Setup Variables
// ---------------------------------------------------------------------
self.profile = profile
var constraints = [NSLayoutConstraint]()
// ---------------------------------------------------------------------
// Create the text field
// ---------------------------------------------------------------------
self.textFieldTitle.translatesAutoresizingMaskIntoConstraints = false
self.textFieldTitle.isBordered = false
self.textFieldTitle.isBezeled = false
self.textFieldTitle.drawsBackground = false
self.textFieldTitle.isEditable = false
self.textFieldTitle.font = NSFont.systemFont(ofSize: 18, weight: .light)
self.textFieldTitle.textColor = .labelColor
self.textFieldTitle.alignment = .center
self.textFieldTitle.lineBreakMode = .byTruncatingTail
self.textFieldTitle.stringValue = profile.settings.title
// ---------------------------------------------------------------------
// Create the initial size of the toolbar item
// ---------------------------------------------------------------------
let frame = NSRect(x: 0.0, y: 0.0, width: self.textFieldTitle.intrinsicContentSize.width, height: self.toolbarItemHeight)
// ---------------------------------------------------------------------
// Create the actual toolbar item
// ---------------------------------------------------------------------
self.toolbarItem = NSToolbarItem(itemIdentifier: .editorTitle)
self.toolbarItem.minSize = frame.size
self.toolbarItem.maxSize = frame.size
// ---------------------------------------------------------------------
// Initialize self after the class variables have been instantiated
// ---------------------------------------------------------------------
super.init(frame: frame)
// ---------------------------------------------------------------------
// Add constraints to text field
// ---------------------------------------------------------------------
setupTextFieldTitle(constraints: &constraints)
// ---------------------------------------------------------------------
// Activate Layout Constraints
// ---------------------------------------------------------------------
NSLayoutConstraint.activate(constraints)
// ---------------------------------------------------------------------
// Set the toolbar item view
// ---------------------------------------------------------------------
self.toolbarItem.view = self
// ---------------------------------------------------------------------
// Setup key/value observer for the profile title
// ---------------------------------------------------------------------
profile.settings.addObserver(self, forKeyPath: profile.settings.titleSelector, options: .new, context: nil)
}
deinit {
guard let profile = self.profile else { return }
profile.settings.removeObserver(self, forKeyPath: profile.settings.titleSelector, context: nil)
}
// MARK: -
// MARK: Instance Functions
func updateTitle() {
guard let profile = self.profile else { return }
self.textFieldTitle.stringValue = profile.settings.title
let frame = NSRect(x: 0.0, y: 0.0, width: self.textFieldTitle.intrinsicContentSize.width, height: self.toolbarItemHeight)
self.frame = frame
self.toolbarItem.minSize = frame.size
self.toolbarItem.maxSize = frame.size
self.centerTitle()
}
func centerTitle() {
guard
let items = self.toolbarItem.toolbar?.items,
let index = items.firstIndex(where: { $0.itemIdentifier == .adaptiveSpace }),
let adaptiveSpace = items[index] as? AdaptiveSpaceItem else { return }
adaptiveSpace.updateWidth()
}
// MARK: -
// MARK: Notification Functions
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard let profile = self.profile else { return }
if keyPath == profile.settings.titleSelector { self.updateTitle() }
}
}
// MARK: -
// MARK: Setup NSLayoutConstraints
extension ProfileEditorWindowToolbarItemTitle {
func setupTextFieldTitle(constraints: inout [NSLayoutConstraint]) {
// ---------------------------------------------------------------------
// Add TextField to TableCellView
// ---------------------------------------------------------------------
self.addSubview(self.textFieldTitle)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Leading
constraints.append(NSLayoutConstraint(item: self.textFieldTitle,
attribute: .leading,
relatedBy: .equal,
toItem: self,
attribute: .leading,
multiplier: 1,
constant: 0))
// Trailing
constraints.append(NSLayoutConstraint(item: self.textFieldTitle,
attribute: .trailing,
relatedBy: .equal,
toItem: self,
attribute: .trailing,
multiplier: 1,
constant: 0))
// Center Vertically
constraints.append(NSLayoutConstraint(item: self.textFieldTitle,
attribute: .centerY,
relatedBy: .equal,
toItem: self,
attribute: .centerY,
multiplier: 1,
constant: 0))
}
}
| mit | 8d38732072c6f53fb29e4007e1e161b3 | 40.213873 | 150 | 0.430575 | 6.942551 | false | false | false | false |
takehaya/ArcherySocket | ach_1/Organization_detailsViewController.swift | 1 | 7688 | //
// Organization_detailsViewController.swift
// ach_1
//
// Created by 早坂彪流 on 2015/07/20.
// Copyright © 2015年 早坂彪流. All rights reserved.
//
import UIKit
class Organization_detailsViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
@IBOutlet weak var tableview: UITableView!
@IBOutlet weak var OrganizatonName_Label: UILabel!//ユーザーが所属している団体名
@IBOutlet weak var Create_for_days_Organizaton_Label: UILabel!//団体設立日
@IBOutlet weak var OrganizationMen_values_Label: UILabel!//メンバー数
@IBOutlet weak var OrganizationRootName_Label: UILabel!//責任者名
@IBOutlet weak var OrganizationField_Label: UILabel!//活動場所
@IBOutlet weak var OrganizaitonEmail_Label: UILabel!//連絡用のメール
@IBOutlet weak var GotoOrganizationMa_button: UIButton!
/*MyVariables*/
var OrganizationName:String!//ユーザーが所属している団体名
var Establish:String!//団体設立日
var Membars:Int!//メンバー数
var admin:String!//責任者名
var place:String!//活動場所
var email:String!//連絡用のメール
var status:Int!// ユーザが団体に所属しているか 1: 所属している, 0: 所属していない
private var indicator:MBProgressHUD! = nil
// メンバーデータの一覧
var memberList:Array<memberListData!> = Array<memberListData!>()
struct memberListData {
var p_id:Int// 選手ID(非表示、削除時に使用)
var playerName:String// 選手名
var birth:String// 生年月日
var email:String// E-mail
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableview.allowsSelection = false
self.GotoOrganizationMa_button.addTarget(self, action: "GotoOrganizationMa_buttonEvent:", forControlEvents: UIControlEvents.TouchUpInside)
HttpRes()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// --tabelViewDatasouce
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell {
print("cell")
let cell: OrganizationDetaillsTableViewCell = self.tableview.dequeueReusableCellWithIdentifier("OrganizationDetaillsCell",forIndexPath: indexPath) as! OrganizationDetaillsTableViewCell
cell.PlayName_Label.text = String(self.memberList[indexPath.row].playerName)
cell.Birth_Label.text = String(self.memberList[indexPath.row].birth)
cell.EmailLLabel.text = String(self.memberList[indexPath.row].email)
print(indexPath.row)
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("count")
return memberList.count
}
//buttonEvent
func GotoOrganizationMa_buttonEvent(sender:UIButton!){
self.performSegueWithIdentifier("Organization_details_to_Organization_management", sender: self)
}
//値渡しする為のovarride
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "Organization_details_to_Organization_management") {
}
}
//http
func HttpRes(){
if memberList.count != 0{
memberList.removeAll()
}
//スレッドの設定((UIKitのための
let q_main: dispatch_queue_t = dispatch_get_main_queue();
// アニメーションを開始する.
self.indicator = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
self.indicator.dimBackground = true
self.indicator.labelText = "Loading..."
self.indicator.labelColor = UIColor.whiteColor()
//Request
let URLStr = "/app/organization"
let loginRequest = NSMutableURLRequest(URL: NSURL(string:Utility_inputs_limit().URLdataSet+URLStr)!)
// set the method(HTTP-GET)
loginRequest.HTTPMethod = "GET"
//GET 付属情報
//set requestbody on data(JSON)
loginRequest.allHTTPHeaderFields = ["cookie":"sessionID="+Utility_inputs_limit().keych_access]
// use NSURLSession
let task = NSURLSession.sharedSession().dataTaskWithRequest(loginRequest, completionHandler: { data, response, error in
if (error == nil) {
//convert json data to dictionary
do{
let dict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
print(dict);//かくにんよう
self.OrganizationName = dict["organizationName"] as? String
self.Establish = dict["establish"] as? String
self.email = dict["email"] as? String
self.admin = dict["admin"] as? String
self.Membars = dict["members"] as? Int
self.place = dict["place"] as? String
self.status = dict["status"] as? Int
let arrMembar:NSArray = (dict["memberList"] as? NSArray)!
for var j = 0;j<arrMembar.count;j++ {
let i = arrMembar[j] as! NSDictionary
let oj:memberListData! = memberListData(p_id: Int((i["p_id"] as? NSNumber)!), playerName: (i["playerName"] as? String)!, birth: ( i["birth"] as? String)!, email: (i["email"] as? String)!)
self.memberList.append(oj)
}
dispatch_async(q_main, {
self.OrganizatonName_Label.text = self.OrganizationName
self.Create_for_days_Organizaton_Label.text = self.Establish
self.OrganizationMen_values_Label.text = String(self.Membars)
self.OrganizationRootName_Label.text = self.admin
self.OrganizationField_Label.text = self.place
self.OrganizaitonEmail_Label.text = self.email
self.tableview.reloadData()
})
} catch{
}
dispatch_async(q_main, {
MBProgressHUD.hideHUDForView(self.view, animated: true)
})
} else {
print(error)
//login出来ない時の処理
let alert = UIAlertController(title: "エラー", message: "サーバーに到達できません。管理者に連絡または時間をおいて再度アクセスしてください", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:{ action in print(action.title)}))
// アラートを表示
self.presentViewController(alert,
animated: true,
completion: {
print("Alert displayed")
MBProgressHUD.hideHUDForView(self.view, animated: true)
})
}
})
task.resume()
}
@IBAction func returnMenuOrganization_details_to_Organization_management(segue:UIStoryboardSegue){
HttpRes()
self.setNeedsStatusBarAppearanceUpdate()
}
}
class OrganizationDetaillsTableViewCell: UITableViewCell {
@IBOutlet weak var PlayName_Label: UILabel!
@IBOutlet weak var Birth_Label: UILabel!
@IBOutlet weak var EmailLLabel: UILabel!
}
| mit | d5636b7f010b410ccca8339892357d9d | 41.382353 | 211 | 0.617071 | 4.4613 | false | false | false | false |
kaltura/playkit-ios | Classes/Player/Ads/AdsEnabledPlayerController.swift | 1 | 8029 | // ===================================================================================================
// Copyright (C) 2017 Kaltura Inc.
//
// Licensed under the AGPLv3 license,
// unless a different license for a particular library is specified in the applicable library path.
//
// You may obtain a copy of the License at
// https://www.gnu.org/licenses/agpl-3.0.html
// ===================================================================================================
import Foundation
import UIKit
import AVFoundation
import AVKit
/// `AdsPlayerState` represents `AdsEnabledPlayerController` state machine states.
enum AdsPlayerState: Int, StateProtocol {
/// initial state.
case start = 0
/// when prepare was requested for the first time and it is stalled until ad started (preroll) / faliure or content resume
case waitingForPrepare
/// a moment before we called prepare until prepare() was finished (the sychornos code only not async tasks)
case preparing
/// Indicates when prepare() was finished (the sychornos code only not async tasks)
case prepared
}
public class AdsEnabledPlayerController : PlayerDecoratorBase, AdsPluginDelegate, AdsPluginDataSource {
/// The ads player state machine.
private var stateMachine = BasicStateMachine(initialState: AdsPlayerState.start, allowTransitionToInitialState: true)
/// The media config to prepare the player with.
/// Uses @NSCopying in order to make a copy whenever set with new value.
@NSCopying private var prepareMediaConfig: MediaConfig!
/// indicates if play was used, if `play()` or `resume()` was called we set this to true.
private var isPlayEnabled = false
/// a semaphore to make sure prepare calling will not be reached from 2 threads by mistake.
private let prepareSemaphore = DispatchSemaphore(value: 1)
/// when playing post roll google sends content resume when finished.
/// In our case we need to prevent sending play/resume to the player because the content already ended.
var shouldPreventContentResume = false
var adsPlugin: AdsPlugin!
weak var messageBus: MessageBus?
public init(adsPlugin: AdsPlugin) {
super.init()
self.adsPlugin = adsPlugin
AppStateSubject.shared.add(observer: self)
self.adsPlugin.delegate = self
self.adsPlugin.dataSource = self
}
override public var isPlaying: Bool {
get {
if self.adsPlugin.isAdPlaying {
return isPlayEnabled
}
return super.isPlaying
}
}
override public func prepare(_ config: MediaConfig) {
self.stateMachine.set(state: .start)
self.adsPlugin.destroyManager()
self.isPlayEnabled = false
self.shouldPreventContentResume = false
self.stateMachine.set(state: .waitingForPrepare)
self.prepareMediaConfig = config
do {
try self.adsPlugin.requestAds()
} catch {
self.preparePlayerIfNeeded()
}
}
override public func play() {
self.isPlayEnabled = true
self.adsPlugin.didRequestPlay(ofType: .play)
}
override public func resume() {
self.isPlayEnabled = true
self.adsPlugin.didRequestPlay(ofType: .resume)
}
override public func pause() {
self.isPlayEnabled = false
if self.adsPlugin.isAdPlaying {
self.adsPlugin.pause()
} else {
super.pause()
}
}
override public func stop() {
self.stateMachine.set(state: .start)
super.stop()
self.adsPlugin.destroyManager()
self.isPlayEnabled = false
self.shouldPreventContentResume = false
}
override public func destroy() {
AppStateSubject.shared.remove(observer: self)
super.destroy()
}
/************************************************************/
// MARK: - AdsPluginDataSource
/************************************************************/
public var playAdsAfterTime: TimeInterval {
return self.prepareMediaConfig?.startTime ?? 0
}
/************************************************************/
// MARK: - AdsPluginDelegate
/************************************************************/
public func adsPlugin(_ adsPlugin: AdsPlugin, loaderFailedWith error: String) {
if self.isPlayEnabled {
self.preparePlayerIfNeeded()
super.play()
self.adsPlugin.didPlay()
}
}
public func adsPlugin(_ adsPlugin: AdsPlugin, managerFailedWith error: String) {
self.preparePlayerIfNeeded()
super.play()
self.adsPlugin.didPlay()
}
public func adsPlugin(_ adsPlugin: AdsPlugin, didReceive event: PKEvent) {
switch event {
case is AdEvent.AdDidRequestContentPause:
super.pause()
case is AdEvent.AdDidRequestContentResume:
if !self.shouldPreventContentResume {
self.preparePlayerIfNeeded()
super.resume()
}
case is AdEvent.AdPaused:
self.isPlayEnabled = false
case is AdEvent.AdResumed:
self.isPlayEnabled = true
case is AdEvent.AdStarted:
// when starting to play pre roll start preparing the player.
if event.adInfo?.positionType == .preRoll {
self.preparePlayerIfNeeded()
}
case is AdEvent.AdBreakReady, is AdEvent.AdLoaded:
if self.shouldPreventContentResume == true { return } // no need to handle twice if already true
if event.adInfo?.positionType == .postRoll {
self.shouldPreventContentResume = true
}
case is AdEvent.AllAdsCompleted:
self.shouldPreventContentResume = false
default:
break
}
}
public func adsRequestTimedOut(shouldPlay: Bool) {
if shouldPlay {
self.preparePlayerIfNeeded()
self.play()
}
}
public func play(_ playType: PlayType) {
self.preparePlayerIfNeeded()
playType == .play ? super.play() : super.resume()
self.adsPlugin.didPlay()
}
/************************************************************/
// MARK: - Private
/************************************************************/
/// prepare the player only if wasn't prepared yet.
private func preparePlayerIfNeeded() {
self.prepareSemaphore.wait() // use semaphore to make sure will not be called from more than one thread by mistake.
if self.stateMachine.getState() == .waitingForPrepare {
self.stateMachine.set(state: .preparing)
PKLog.debug("will prepare player")
super.prepare(self.prepareMediaConfig)
self.stateMachine.set(state: .prepared)
}
self.prepareSemaphore.signal()
}
}
/************************************************************/
// MARK: - AppStateObservable
/************************************************************/
extension AdsEnabledPlayerController: AppStateObservable {
public var observations: Set<NotificationObservation> {
return [
NotificationObservation(name: UIApplication.didEnterBackgroundNotification) { [weak self] in
guard let self = self else { return }
// when we enter background make sure to pause if we were playing.
self.pause()
// notify the ads plugin we are entering to the background.
self.adsPlugin.didEnterBackground()
},
NotificationObservation(name: UIApplication.willEnterForegroundNotification) { [weak self] in
guard let self = self else { return }
self.adsPlugin.willEnterForeground()
}
]
}
}
| agpl-3.0 | 6cb925de9d3b8a9f5a46904de6f89eb4 | 35.004484 | 126 | 0.573297 | 5.114013 | false | false | false | false |
lugearma/LAMenuBar | Example/LAMenuBar/ViewController.swift | 1 | 2373 | //
// ViewController.swift
// LAMenuBar
//
// Created by Luis Arias on 06/11/2017.
// Copyright (c) 2017 Luis Arias. All rights reserved.
//
import UIKit
import LAMenuBar
@available(iOS 9.0, *)
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .gray
configurateNavigationBar()
setupMenuView()
}
private func setupMenuView() {
// Create array of view controller that are going to be presented in each section
let viewControllers = [
FirstViewController(),
SecondViewController(),
ThirdViewController(),
FourthViewController()
]
// Create a model which has the information to present
let images = [
UIImage(named: "home"),
UIImage(named: "trending"),
UIImage(named: "subscriptions"),
UIImage(named: "account")
]
let model = LAMenuModel(images: images, backgroundColor: .white, barColor: .black, tintColorWhenSelected: .black, tintColorWhenDiselected: .lightGray, viewControllers: viewControllers, isCurrentSectionBarHidden: false, menuBarPosition: .top)
// Create LAMenuView and add to your view
let frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
let menuView = LAMenuView(frame: frame, model: model)
menuView.translatesAutoresizingMaskIntoConstraints = false
// Set the model
menuView.delegate = self
view.addSubview(menuView)
menuView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
menuView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
menuView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
menuView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
}
func configurateNavigationBar() {
navigationController?.navigationBar.isTranslucent = false
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
}
}
// MARK: - LAMenuViewDelegate
@available(iOS 9.0, *)
extension ViewController: LAMenuViewDelegate {
func menuView(_ view: LAMenuView, didScrollWithIndex index: IndexPath) {
print(#function)
}
func menuView(_ view: LAMenuView, didSelectMenuItemAtIndex index: IndexPath) {
print("Index:", index.item)
}
}
| mit | 28844c429cfc4bd54b19f9e9fe4bdcba | 30.223684 | 245 | 0.710493 | 4.589942 | false | false | false | false |
ujell/YUTableView-Swift | YUTableView-Swift/YUTableView/YUTableView.swift | 1 | 10213 | //
// YUTableView.swift
// YUTableView-Swift
//
// Created by yücel uzun on 22/07/15.
// Copyright © 2015 Yücel Uzun. All rights reserved.
//
import UIKit
public protocol YUTableViewDelegate {
/** Called inside "cellForRowAtIndexPath:" method. Edit your cell in this funciton. */
func setContentsOfCell (_ cell: UITableViewCell, node: YUTableViewNode)
/** Uses the returned value as cell height if implemented */
func heightForIndexPath (_ indexPath: IndexPath) -> CGFloat?
/** Uses the returned value as cell height if heightForIndexPath is not implemented */
func heightForNode (_ node: YUTableViewNode) -> CGFloat?
/** Called whenever a node is selected. You should check if it's a leaf. */
func didSelectNode (_ node: YUTableViewNode, indexPath: IndexPath)
/** Determines if swipe actions should be shown */
func canEditNode (_ node: YUTableViewNode, indexPath: IndexPath) -> Bool
/** Called when a node is removed with a swipe */
func didRemoveNode (_ node: YUTableViewNode, indexPath: IndexPath)
}
extension YUTableViewDelegate {
public func heightForNode (_ node: YUTableViewNode) -> CGFloat? { return nil }
public func heightForIndexPath (_ indexPath: IndexPath) -> CGFloat? { return nil }
public func didSelectNode (_ node: YUTableViewNode, indexPath: IndexPath) {}
public func canEditNode (_ node: YUTableViewNode, indexPath: IndexPath) -> Bool { return false }
public func didRemoveNode (_ node: YUTableViewNode, indexPath: IndexPath) {}
}
public class YUTableView: UITableView
{
fileprivate var yuTableViewDelegate : YUTableViewDelegate!
fileprivate var firstLevelNodes: [YUTableViewNode]!
fileprivate var rootNode : YUTableViewNode! {
willSet {
if rootNode != nil {
disableNodeAndChildNodes(rootNode)
}
}
}
fileprivate var nodesToDisplay: [YUTableViewNode]!
/** If "YUTableViewNode"s don't have individual identifiers, this one is used */
public var defaultCellIdentifier: String!
public var insertRowAnimation: UITableViewRowAnimation = .right
public var deleteRowAnimation: UITableViewRowAnimation = .left
public var animationCompetitionHandler: () -> Void = {}
/** Removes other open items before opening a new one */
public var allowOnlyOneActiveNodeInSameLevel: Bool = false
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeDefaultValues ()
}
public required override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
initializeDefaultValues ()
}
private func initializeDefaultValues () {
self.delegate = self
self.dataSource = self
}
public func setDelegate (_ delegate: YUTableViewDelegate) {
yuTableViewDelegate = delegate
}
public func setNodes (_ nodes: [YUTableViewNode]) {
rootNode = YUTableViewNode(childNodes: nodes)
self.firstLevelNodes = nodes
self.nodesToDisplay = self.firstLevelNodes
reloadData()
}
public func selectNodeAtIndex (_ index: Int) {
let node = nodesToDisplay [index]
openNodeAtIndexRow(index)
yuTableViewDelegate?.didSelectNode(node, indexPath: IndexPath(row: index, section: 0))
}
public func selectNode (_ node: YUTableViewNode) {
var index = nodesToDisplay.index(of: node)
if index == nil {
selectNode(node.getParent()!)
index = nodesToDisplay.index(of: node)
}
openNodeAtIndexRow(index!)
yuTableViewDelegate?.didSelectNode(node, indexPath: IndexPath(row: index!, section: 0))
}
public func closeAllNodes () {
for subNode in nodesToDisplay {
closeNode (subNode);
}
}
public func closeNode (_ node: YUTableViewNode) {
if let index = nodesToDisplay.index(of: node) {
closeNodeAtIndexRow(index)
}
}
}
extension YUTableView: UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if nodesToDisplay != nil {
return nodesToDisplay.count
}
return 0
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let node = nodesToDisplay[(indexPath as NSIndexPath).row]
let cellIdentifier = node.cellIdentifier != nil ? node.cellIdentifier : defaultCellIdentifier
let cell = self.dequeueReusableCell(withIdentifier: cellIdentifier!, for: indexPath)
yuTableViewDelegate?.setContentsOfCell(cell, node: node)
return cell
}
public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if let canEdit = yuTableViewDelegate?.canEditNode(nodesToDisplay[(indexPath as NSIndexPath).row], indexPath: indexPath) {
return canEdit;
}
return false;
}
public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let node = nodesToDisplay[(indexPath as NSIndexPath).row]
removeNodeAtIndexPath (indexPath)
yuTableViewDelegate?.didRemoveNode(node, indexPath: indexPath)
}
}
}
extension YUTableView: UITableViewDelegate {
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if let height = yuTableViewDelegate?.heightForIndexPath(indexPath) {
return height
}
if let height = yuTableViewDelegate?.heightForNode(nodesToDisplay[(indexPath as NSIndexPath).row]) {
return height
}
return tableView.rowHeight
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let node = nodesToDisplay [(indexPath as NSIndexPath).row]
yuTableViewDelegate.didSelectNode(node, indexPath: indexPath)
if node.isActive {
closeNodeAtIndexRow((indexPath as NSIndexPath).row)
} else if node.hasChildren() {
openNodeAtIndexRow((indexPath as NSIndexPath).row)
}
}
}
private extension YUTableView {
func openNodeAtIndexRow (_ indexRow: Int) {
var indexRow = indexRow
let node = nodesToDisplay [indexRow]
if allowOnlyOneActiveNodeInSameLevel {
closeNodeAtSameLevelWithNode(node, indexRow: indexRow)
indexRow = nodesToDisplay.index(of: node)!
}
if let newNodes = node.childNodes {
nodesToDisplay.insert(newNodes, atIndex: indexRow + 1)
let indexesToInsert = indexesFromRow(indexRow + 1, count: newNodes.count)!
updateTableRows(insertRows: indexesToInsert, removeRows: nil)
node.isActive = true
}
}
func closeNodeAtSameLevelWithNode (_ node: YUTableViewNode, indexRow: Int) {
if let siblings = node.getParent()?.childNodes {
if let activeNode = siblings.filter( { $0.isActive }).first {
closeNodeAtIndexRow (nodesToDisplay.index(of: activeNode)!)
}
}
}
func closeNodeAtIndexRow (_ indexRow: Int, shouldReloadClosedRow: Bool = false ) {
let node = nodesToDisplay [indexRow]
let numberOfDisplayedChildren = getNumberOfDisplayedChildrenAndDeactivateEveryNode(node)
if (indexRow + 1 > indexRow+numberOfDisplayedChildren) { return }
nodesToDisplay.removeSubrange(indexRow + 1...indexRow+numberOfDisplayedChildren )
updateTableRows(removeRows: indexesFromRow(indexRow + 1, count: numberOfDisplayedChildren))
if shouldReloadClosedRow {
self.reloadRows(at: [IndexPath(row: indexRow, section: 0)], with: .fade)
}
}
func getNumberOfDisplayedChildrenAndDeactivateEveryNode (_ node: YUTableViewNode) -> Int {
if !node.isActive { return 0 }
var count = 0
node.isActive = false;
if let children = node.childNodes {
count += children.count
for child in children.filter ({$0.isActive }) {
count += getNumberOfDisplayedChildrenAndDeactivateEveryNode(child)
}
}
return count
}
func indexesFromRow (_ from: Int, count: Int) -> [IndexPath]? {
var indexes = [IndexPath] ()
for i in 0 ..< count {
indexes.append(IndexPath(row: i + from, section: 0))
}
if (indexes.count == 0) { return nil }
return indexes
}
func updateTableRows ( insertRows indexesToInsert: [IndexPath]? = nil, removeRows indexesToRemove: [IndexPath]? = nil) {
CATransaction.begin()
CATransaction.setCompletionBlock { () -> Void in
self.animationCompetitionHandler ()
}
self.beginUpdates()
if indexesToRemove != nil && indexesToRemove!.count > 0 {
self.deleteRows(at: indexesToRemove!, with: self.deleteRowAnimation)
}
if indexesToInsert != nil && indexesToInsert!.count > 0 {
self.insertRows(at: indexesToInsert!, with: self.insertRowAnimation)
}
self.endUpdates()
CATransaction.commit()
}
func removeNodeAtIndexPath (_ indexPath: IndexPath) {
if nodesToDisplay[(indexPath as NSIndexPath).row].isActive {
closeNodeAtIndexRow((indexPath as NSIndexPath).row)
}
nodesToDisplay.remove(at: (indexPath as NSIndexPath).row)
updateTableRows(removeRows: [indexPath])
}
func disableNodeAndChildNodes (_ node: YUTableViewNode) {
node.isActive = false
for child in node.childNodes ?? [YUTableViewNode]() {
disableNodeAndChildNodes(child)
}
}
}
private extension Array {
mutating func insert (_ items: [Element], atIndex: Int) {
var counter = 0
for item in items {
insert(item, at: atIndex + counter)
counter += 1
}
}
}
| mit | f4dac1a8c1af74e8207ccd88f205bc60 | 36.814815 | 134 | 0.651322 | 4.896882 | false | false | false | false |
brunomorgado/ScrollableAnimation | ScrollableAnimation/Source/Animation/Interpolators/BasicInterpolator/BasicNumberInterpolator.swift | 1 | 2844 | //
// BasicNumberInterpolator.swift
// ScrollableMovie
//
// Created by Bruno Morgado on 25/12/14.
// Copyright (c) 2014 kocomputer. All rights reserved.
//
// 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
class BasicNumberInterpolator: BasicInterpolator {
var animatable: CALayer
required init(animatable: CALayer) {
self.animatable = animatable
}
}
extension BasicNumberInterpolator: BasicInterpolatorProtocol {
func interpolateAnimation(animation: ScrollableAnimation, forAnimatable animatable: CALayer, forOffset offset: Float) {
if let animation = animation as? ScrollableBasicAnimation {
let offsetPercentage = BasicInterpolator.getPercentageForOffset(offset, animation: animation)
if let fromValue = animation.fromValue as Float? {
if let toValue = animation.toValue as Float? {
var number: Float
if (offsetPercentage <= 0) {
number = fromValue
} else if (offsetPercentage > 1) {
number = toValue
} else {
let verticalDelta = Double(toValue - fromValue)
var tween = animation.offsetFunction
if let tween = tween as TweenBlock? {
number = fromValue + Float(tween(Double(offsetPercentage))) * Float(verticalDelta)
} else {
number = fromValue + Float(offsetPercentage * Float(verticalDelta))
}
}
self.animatable.setValue(number, forKeyPath: animation.keyPath)
}
}
}
}
} | mit | b9c735d1bd863e75c9862dd71f174e7c | 43.453125 | 123 | 0.63045 | 5.170909 | false | false | false | false |
Grimoire-project/Grimoire | Tests/GrimoireKitTests/FileSpec.swift | 1 | 773 | import Quick
import Nimble
@testable import GrimoireKit
final class FileSpec: QuickSpec {
override func spec() {
describe("read") {
context("when file path is faulty") {
let path = "Sources /Commands/Help.swift"
it("throws the correct error") {
expect { try File.read(path) }.to(throwError { error in
let expected = "The file “Help.swift” couldn’t be opened because there is no such file."
expect(error.localizedDescription) == expected
})
}
}
context("when file path is valid") {
let path = Fixture.path("FileSpecFixture.txt")
it("fetch the correct file") {
expect { try File.read(path) } == "some text content\n"
}
}
}
}
}
| mit | 9bfee77ba6d701e3a45de76186cc0700 | 26.392857 | 100 | 0.585398 | 4.123656 | false | false | false | false |
ricardopereira/PremierKit | Source/Premier+KVO.swift | 1 | 4652 | //
// Premier+KVO.swift
// PremierKit
//
// Created by Ricardo Pereira on 08/10/2019.
// Copyright © 2019 Ricardo Pereira. All rights reserved.
//
import Foundation
/**
Probably, this will be replaced with the Swift standard KVO observation object which has been unstable in older versions.
Example:
#if swift(>=5.1)
layerBoundsObserver = self.observe(\.layer.bounds, options: [.old, .new]) { [weak self] sender, change in
guard change.oldValue?.size.width != change.newValue?.size.width else {
return
}
self?.repositionViews()
}
#else
... this solution
#endif
*/
public class KeyValueObserverToken<Sender: NSObject, Value>: NSObject {
public typealias Block = (_ sender: Sender, _ change: KeyValueObservedChange<Value>) -> Void
private(set) var sender: Sender?
public let keyPath: String
public let options: NSKeyValueObservingOptions
private let block: Block
public init(_ object: Sender, keyPath: String, options: NSKeyValueObservingOptions, block: @escaping Block) {
self.sender = object
self.keyPath = keyPath
self.options = options
self.block = block
super.init()
object.addObserver(self, forKeyPath: keyPath, options: options, context: nil)
}
deinit {
invalidate()
}
/**
Remove observer. Should always be called or a leak will occur because this is holding a strong reference to the sender.
*/
public func invalidate() {
if let object = sender {
object.removeObserver(self, forKeyPath: keyPath, context: nil)
}
sender = nil
}
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if self.keyPath == keyPath {
guard let sender = sender else {
// Ignore since sender has been probably deallocated.
return
}
guard let change = change else {
assertionFailure("Expected change dictionary")
return
}
// The change dictionary always contains an NSKeyValueChangeKindKey entry whose value is an NSNumber wrapping an NSKeyValueChange (use -[NSNumber unsignedIntegerValue]).
guard let kindKey = change[NSKeyValueChangeKey.kindKey] as? NSNumber,
let kind = NSKeyValueChange(rawValue: kindKey.uintValue) else {
assertionFailure("Expected NSKeyValueChangeKindKey value")
return
}
let newValue = change[.newKey] as? Value
let oldValue = change[.oldKey] as? Value
let indexes = change[.indexesKey] as? IndexSet
let isPrior = change[.notificationIsPriorKey] as? Bool
let safeChange = KeyValueObservedChange<Value>(
kind: kind,
newValue: newValue,
oldValue: oldValue,
indexes: indexes,
isPrior: isPrior ?? false
)
block(sender, safeChange)
}
else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
}
/**
Same as NSKeyValueObservedChange.
*/
public struct KeyValueObservedChange<Value> {
public let kind: NSKeyValueChange
public let newValue: Value?
public let oldValue: Value?
///indexes will be nil unless the observed KeyPath refers to an ordered to-many property
public let indexes: IndexSet?
///'isPrior' will be true if this change observation is being sent before the change happens, due to .prior being passed to `observe()`
public let isPrior: Bool
}
extension NSKeyValueChange: CustomStringConvertible {
public var description: String {
switch self {
case .insertion:
return "Insertion"
case .removal:
return "Removal"
case .replacement:
return "Replacement"
case .setting:
return "Setting"
@unknown default:
fatalError("NSKeyValueChange missing case for description")
}
}
}
extension NSObjectProtocol where Self: NSObject {
public func addObserver<Value>(for keyPath: KeyPath<Self, Value>, options: NSKeyValueObservingOptions, block: @escaping KeyValueObserverToken<Self, Value>.Block) -> KeyValueObserverToken<Self, Value> {
let objcKeyPathString = NSExpression(forKeyPath: keyPath).keyPath
return KeyValueObserverToken<Self, Value>(self, keyPath: objcKeyPathString, options: options, block: block)
}
}
| mit | a3c9355047e0cadd90a57f5d063cb6d4 | 31.075862 | 205 | 0.642227 | 5.03355 | false | false | false | false |
Raizlabs/SketchyCode | SketchyCode/Generation/NamingStrategy.swift | 1 | 3404 | //
// NamingStrategy.swift
// SketchyCode
//
// Created by Brian King on 10/5/17.
// Copyright © 2017 Brian King. All rights reserved.
//
import Foundation
// A naming strategy is resposible for creating names for declarations.
protocol NamingStrategy {
func name(for variable: VariableRef, in scope: Scope) throws -> String
}
class SwiftUIKitNamingStrategy: NamingStrategy {
func name(for variable: VariableRef) -> String {
if variable.isSelf {
return "self"
}
if let hint = variable.userVariableName {
return hint
}
let typeName = variable.type.name
var name = typeName
if name.hasPrefix("UI") {
name.removeFirst()
name.removeFirst()
}
if let first = name.indices.first {
name.replaceSubrange(first...first, with: String(name[first]).lowercased())
}
return name
}
func lookupName(for variable: VariableRef, in scope: Scope) -> String {
var searchScope: Scope? = scope
var name: String? = nil
while let currentScope = searchScope, name == nil {
name = currentScope.registeredVariables[variable.identifier]
searchScope = currentScope.parent
}
if let name = name {
return name
}
// Register a new name with this scope
let generatedName = self.name(for: variable)
var counter = 1
var newName = generatedName
// Add a counter if needed
while scope.registeredVariables.values.contains(newName) {
counter += 1
newName = "\(generatedName)\(counter)"
}
scope.registeredVariables[variable.identifier] = newName
return newName
}
func name(for variable: VariableRef, in scope: Scope) throws -> String {
var path: [VariableRef] = scope.path(for: variable)
var nextScope = scope.parent
while path.count == 0 {
if let scope = nextScope {
path = scope.path(for: variable)
nextScope = scope.parent
} else {
_ = scope.path(for: variable)
throw UnregisteredVariableRefError(variable: variable)
}
}
assert(path.last == variable)
var variableNames: [String] = []
for variable in path {
guard !variable.isImplicitSelf else { continue }
variableNames.append(lookupName(for: variable, in: scope))
}
var name = variableNames.joined(separator: ".")
if variable.isLeading && variableNames.count > 0 {
name.append(".")
}
return name
}
}
extension SyntaxPart {
func code(in scope: Scope, with namingStrategy: NamingStrategy) throws -> String {
switch self {
case .v(let variable):
return try namingStrategy.name(for: variable, in: scope)
case .s(let string):
return string
case .c(let type, let string):
if type.name == "String" {
return "\"\(string)\""
} else {
return string
}
case .p(let variable):
return "(\(try namingStrategy.name(for: variable, in: scope)))"
case .debug(let part):
return try part.code(in: scope, with: namingStrategy)
}
}
}
| mit | 2ebfa3534ccd51814a69440d2f2f3c4c | 30.803738 | 87 | 0.571848 | 4.573925 | false | false | false | false |
SmallPlanetSwift/Saturn | Source/TypeExtensions/UIColor+String.swift | 1 | 2083 | //
// UIColor+String.swift
// Saturn
//
// Created by Quinn McHenry on 11/14/15.
// Copyright © 2015 Small Planet. All rights reserved.
//
extension UIColor {
public convenience init(stringLiteral value: String) {
var (r,g,b,a): (CGFloat, CGFloat, CGFloat, CGFloat) = (0.0, 0.0, 0.0, 1.0)
if value.hasPrefix("#") {
let substring = value.substringFromIndex(value.startIndex.advancedBy(1))
var hexNumber:UInt32 = 0;
let _ = NSScanner(string: substring).scanHexInt(&hexNumber)
switch substring.characters.count {
case 8:
r = CGFloat((hexNumber & 0xFF000000) >> 24) / 255.0
g = CGFloat((hexNumber & 0x00FF0000) >> 16) / 255.0
b = CGFloat((hexNumber & 0x0000FF00) >> 8) / 255.0
a = CGFloat(hexNumber & 0x000000FF) / 255.0
case 6:
r = CGFloat((hexNumber & 0xFF0000) >> 16) / 255.0
g = CGFloat((hexNumber & 0x00FF00) >> 8) / 255.0
b = CGFloat(hexNumber & 0x0000FF) / 255.0
default: break
}
} else {
switch value {
case "red": r = 1.0
case "green": g = 1.0
case "blue": b = 1.0
case "white": r = 1.0; g = 1.0; b = 1.0
default: break
}
}
self.init(red: r, green:g, blue:b, alpha:a)
}
convenience init(red: Int, green: Int, blue: Int) {
let newRed = CGFloat(Double(red) / 255.0)
let newGreen = CGFloat(Double(green) / 255.0)
let newBlue = CGFloat(Double(blue) / 255.0)
self.init(red: newRed, green: newGreen, blue: newBlue, alpha: CGFloat(1.0))
}
public var string: String? {
var r:CGFloat = 0, g:CGFloat = 0, b:CGFloat = 0, a:CGFloat = 0
guard getRed(&r, green:&g , blue: &b, alpha: &a) else { return nil }
let hexNumber = Int(r*255) << 24 + Int(g*255) << 16 + Int(b*255) << 8 + Int(a*255)
return NSString(format:"#%08X", hexNumber) as String
}
}
| mit | 2f56ebeb4bcbf910af8dd3fe56f5b9dd | 36.854545 | 90 | 0.523055 | 3.44702 | false | false | false | false |
Breinify/brein-api-library-ios | BreinifyApi/api/BreinActivity.swift | 1 | 7448 | //
// Created by Marco Recchioni
// Copyright (c) 2020 Breinify. All rights reserved.
//
import Foundation
/**
Sends an activity to the engine utilizing the API. The call is done asynchronously as a POST request.
It is important, that a valid API-key is configured prior to use this.
*/
open class BreinActivity: BreinBase, ISecretStrategy {
/// ActivityType of the activity
var activityType: String?
/// Category of the activity
var category: String?
/// Description of the activity
var desc: String?
/// tags dictionary
var tagsDic: [String: Any]?
/// activity dictionary
var activityDic: [String: Any]?
/// returns activity type
///
/// - Returns: the BreinActivity itself
public func getActivityType() -> String! {
activityType
}
/// sets the activity type
///
/// - Parameter activityType: an activityType as String
/// - Returns: the BreinActivity itself
@discardableResult
@objc
public func setActivityType(_ activityType: String?) -> BreinActivity {
self.activityType = activityType
return self
}
/// Provides the category
///
/// - Returns: the category as String
@discardableResult
public func getCategory() -> String! {
category
}
/// Sets the category.
///
/// - Parameter category:
/// - Returns: the BreinActivity itself
@discardableResult
@objc
public func setCategory(_ category: String?) -> BreinActivity {
self.category = category
return self
}
/// Provides the description of the activity
///
/// - Returns: the description as String
public func getDescription() -> String! {
desc
}
@discardableResult
@objc
public func setDescription(_ description: String!) -> BreinActivity {
desc = description
return self
}
/// Provides the Activity Endpoint for HTTP requests to the Breinify Engine
///
/// - Returns: the HTTP endpoint as String
override public func getEndPoint() -> String! {
getConfig()?.getActivityEndpoint()
}
@discardableResult
@objc
public func setTagsDic(_ tagsDic: [String: Any]?) -> BreinActivity {
self.tagsDic = tagsDic
return self
}
public func getTagsDic() -> [String: Any]? {
tagsDic
}
@discardableResult
@objc
public func setTag(_ key: String, _ value: AnyObject) -> BreinActivity {
if tagsDic == nil {
tagsDic = [String: Any]()
}
tagsDic?[key] = value
return self
}
@discardableResult
public func setActivityDic(_ activityDic: [String: Any]) -> BreinActivity {
self.activityDic = activityDic
return self
}
public func getActivityDic() -> [String: Any]? {
activityDic
}
/// Sends an activity to the Breinify server.
///
/// - Parameters:
/// - breinUser: the user-information
/// - breinActivityType: the type of activity
/// - breinCategoryType: the category (can be null or undefined)
/// - description: the description for the activity
/// - success: a callback function that is invoked in case of success.
/// - failure: a callback function that is invoked in case of an error.
/// - Throws: BreinRuntimeError
public func activity(_ breinUser: BreinUser!,
breinActivityType: String!,
_ breinCategoryType: String! = nil,
_ description: String! = nil,
_ success: @escaping BreinEngine.apiSuccess = { _ in
},
_ failure: @escaping BreinEngine.apiFailure = { _ in
}) throws {
// set the values for further usage
setUser(breinUser)
setActivityType(breinActivityType)
setCategory(breinCategoryType)
setDescription(description)
// invoke the request, "self" has all necessary information
if nil == getBreinEngine() {
throw BreinError.BreinRuntimeError("Rest engine not initialized. You have to configure BreinConfig with a valid engine.")
}
do {
try getBreinEngine()?.sendActivity(self, success: success, failure: failure)
} catch {
BreinLogger.shared.log(error.localizedDescription)
}
}
/// Creates a dictionary that will be used for the request.
///
/// - Returns: Dictionary
override public func prepareJsonRequest() -> [String: Any]! {
// call base class
super.prepareJsonRequest()
var requestData = [String: Any]()
if let breinUser = getUser() {
var userData = [String: Any]()
breinUser.prepareUserRequest(&userData, breinConfig: getConfig())
requestData["user"] = userData as Any?
}
// activity data
var activityData = [String: Any]()
if let activityType = getActivityType() {
activityData["type"] = activityType as Any?
}
if let description = getDescription() {
activityData["description"] = description as Any?
}
if let category = getCategory() {
activityData["category"] = category as Any?
}
// add tags
if tagsDic?.isEmpty == false {
activityData["tags"] = tagsDic as Any?
}
// activity dic
if let aActivityDic = getActivityDic() {
if aActivityDic.count > 0 {
BreinMapUtil.fillMap(aActivityDic, requestStructure: &activityData)
}
}
// add all to the activity dictionary
requestData["activity"] = activityData as Any?
// add base stuff
prepareBaseRequestData(&requestData)
return requestData
}
/// Used to create a clone of an activity. This is important in order to prevent
/// concurrency issues.
///
/// - Returns: the clone of the activity object
public func clone() -> BreinActivity {
// create a new activity object
let clonedBreinActivity = BreinActivity()
.setActivityType(getActivityType())
.setCategory(getCategory())
.setDescription(getDescription())
// clone dictionaries => simple copy is enough
if let clonedActivityDic = getActivityDic() {
clonedBreinActivity.setActivityDic(clonedActivityDic)
}
if let clonedTagsDic = getTagsDic() {
clonedBreinActivity.setTagsDic(clonedTagsDic)
}
// clone from base class
clonedBreinActivity.cloneBase(self)
return clonedBreinActivity
}
override
public func clear() {
super.clear()
activityDic?.removeAll()
tagsDic?.removeAll()
category = ""
desc = ""
activityType = ""
}
/// Generates the signature for the request
///
/// - Returns: full signature
/// - Throws: BreinRuntimeError
public override func createSignature() throws -> String! {
let breinActivityType = getActivityType() ?? ""
let unixTimestamp = getUnixTimestamp()
let message = breinActivityType + String(unixTimestamp) + "1"
return try BreinUtil.generateSignature(message, secret: getConfig()?.getSecret())
}
}
| mit | 53ac1f0b1126ce7c4f69ca51bb78c60a | 27.980545 | 133 | 0.597476 | 4.789711 | false | false | false | false |
khizkhiz/swift | validation-test/compiler_crashers_fixed/00237-swift-declrefexpr-setspecialized.swift | 1 | 2826 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func b(c) -> <d>(() -> d) {
}
struct d<f : e, g: e where g.h == f.h> {
}
protocol e {
typealias h
}
struct c<d : Sequence> {
var b: d
}
func a<d>() -> [c<d>] {
return []
}
func i(c: () -> ()) {
}
class a {
var _ = i() {
}
}
protocol A {
typealias E
}
struct B<T : A> {
let h: T
let i: T.E
}
protocol C {
typealias F
func g<T where T.E == F>(f: B<T>)
}
struct D : C {
typealias F = Int
func g<T where T.E == F>(f: B<T>) {
}
}
protocol A {
func c() -> String
}
class B {
func d() -> String {
return ""
B) {
}
}
func ^(a: Boolean, Bool) -> Bool {
return !(a)
}
func f<T : Boolean>(b: T) {
}
f(true as Boolean)
var f = 1
var e: Int -> Int = {
return $0
}
let d: Int = { c, b in
}(f, e)
func d<b: Sequence, e where Optional<e> == b.Iterator.Element>(c : b) -> e? {
for (mx : e?) in c {
}
}
protocol a {
}
protocol b : a {
}
protocol c : a {
}
protocol d {
typealias f = a
}
struct e : d {
typealias f = b
}
func i<j : b, k : d where k.f == j> (n: k) {
}
func i<l : d where l.f == c> (n: l) {
}
i(e(ass func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicType.c()
class a<f : b, g : b where f.d == g> {
}
protocol b {
typealias d
typealias e
}
struct c<h : b> : b {
typealias d = h
typealias e = a<c<h>, d>
}
class a {
typealias b = b
}
func a(b: Int = 0) {
}
let c = a
c()
enum S<T> {
case C(T, () -> ())
}
func f() {
({})
}
enum S<T> : P {
func f<T>() -> T -> T {
return { x in x }
}
}
protocol P {
func f<T>()(T) -> T
}
protocol A {
typealias B
func b(B)
}
struct X<Y> : A {
func b(b: X.Type) {
}
}
class A<T : A> {
}
protocol a {
typealias d
typealias e = d
typealias f = d
}
class b<h : c, i : c where h.g == i> : a {
}
class b<h, i> {
}
protocol c {
typealias g
}
struct A<T> {
let a: [(T, () -> ())] = []
}
struct c<d, e: b where d.c == e> {
}
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) {
return {
(m: (Any, Any) -> Any) -> Any in
return m(x, y)
}
}
func b(z: (((Any, Any) -> Any) -> Any)) -> Any {
return z({
(p: Any, q:Any) -> Any in
return p
})
}
b(a(1, a(2, 3)))
func a<T>() -> (T, T -> T) -> T {
var b: ((T, T -> T) -> T)!
return b
}
protocol b {
class func e()
}
struct c {
var d: b.Type
func e() {
d.e()
}
}
import Foundation
class d<c>: NSObject {
var b: c
init(b: c) {
self.b = b
}
}
func a<T>() {
enum b {
case c
}
}
protocol a : a {
}
class A : A {
}
class B : C {
}
typealias C = B
| apache-2.0 | 0891bb7fa677c657378712c13be9ae3f | 13.795812 | 87 | 0.471338 | 2.505319 | false | false | false | false |
davefoxy/SwiftBomb | Example/SwiftBomb/DataProviders/GameResourcePaginator.swift | 1 | 3087 | //
// GameResourcePaginator.swift
// GBAPI
//
// Created by David Fox on 26/04/2016.
// Copyright © 2016 David Fox. All rights reserved.
//
import Foundation
import UIKit
import SwiftBomb
class GameResourcePaginator: ResourcePaginator {
var searchTerm: String?
var pagination: PaginationDefinition
var sort: SortDefinition
var isLoading = false
var hasMore: Bool = true
var resourceType = ResourceType.game
let dateFormatter = DateFormatter()
var games = [GameResource]()
init(searchTerm: String? = nil, pagination: PaginationDefinition = PaginationDefinition(offset: 0, limit: 30), sort: SortDefinition = SortDefinition(field: "name", direction: .ascending)) {
dateFormatter.dateStyle = .medium
self.searchTerm = searchTerm
self.pagination = pagination
self.sort = sort
}
func loadMore(completion: @escaping (_ cellPresenters: [ResourceItemCellPresenter]?, _ error: SwiftBombRequestError?) -> Void) {
if isLoading {
return
}
isLoading = true
SwiftBomb.fetchGames(searchTerm, pagination: pagination, sort: sort) { results, error in
self.isLoading = false
if error == nil {
if let games = results?.resources {
self.games.append(contentsOf: games)
let cellPresenters = self.cellPresentersForResources(games)
self.pagination = PaginationDefinition(self.pagination.offset + games.count, self.pagination.limit)
self.hasMore = (results?.hasMoreResults)!
completion(cellPresenters, nil)
}
}
else {
completion(nil, error)
}
}
}
func cellPresentersForResources(_ games: [GameResource]) -> [ResourceItemCellPresenter] {
var cellPresenters = [ResourceItemCellPresenter]()
for game in games {
var subtitle = ""
if let originalReleaseDate = game.original_release_date {
subtitle = "Release date: \(dateFormatter.string(from: originalReleaseDate))"
}
let cellPresenter = ResourceItemCellPresenter(imageURL: game.image?.small, title: game.name, subtitle: subtitle)
cellPresenters.append(cellPresenter)
}
return cellPresenters
}
func resetPagination() {
self.games.removeAll()
self.pagination = PaginationDefinition(0, self.pagination.limit)
self.hasMore = true
}
func detailViewControllerForResourceAtIndexPath(indexPath: IndexPath) -> UIViewController {
let viewController = GameViewController(style: .grouped)
viewController.game = games[(indexPath as NSIndexPath).row]
return viewController
}
}
| mit | c859a153e9d1941db9f7c64929b30efa | 31.145833 | 193 | 0.581983 | 5.471631 | false | false | false | false |
jorjuela33/OperationKit | OperationKit/Operations/DataRequestOperation.swift | 1 | 4528 | //
// URLDataRequestOperation.swift
//
// Copyright © 2016. All rights reserved.
//
// 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
open class DataRequestOperation: URLRequestOperation {
/// the data returned for the server
public fileprivate(set) var data = Data()
// MARK: Initialization
public init(request: URLRequest, sessionConfiguration: URLSessionConfiguration = URLSessionConfiguration.default) {
super.init(request: request, configuration: sessionConfiguration)
sessionTask = session.dataTask(with: request)
}
}
extension DataRequestOperation {
// MARK: Response Serialization
/// Returns a object contained in a result type constructed from the response serializer passed as parameter.
@discardableResult
public func response<Serializer: ResponseSerializer, T>(data: Data,
responseSerializer: Serializer,
completionHandler: @escaping ((Result<Serializer.SerializedValue>) -> ())) -> Self where Serializer.SerializedValue == T {
let blockOperation = BlockOperation { [unowned self] in
let result = responseSerializer.serialize(request: self.sessionTask.originalRequest, response: self.response, data: self.data)
DispatchQueue.main.async {
completionHandler(result)
}
}
addSubOperation(blockOperation)
return self
}
/// Adds a handler to be called once the request has finished.
@discardableResult
public func responseData(_ completionHandler: @escaping ((Result<Data>) -> ())) -> Self {
return response(data: data, responseSerializer: DataResponseSerializer(), completionHandler: completionHandler)
}
/// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization`
/// with the specified reading options.
@discardableResult
public func responseJSON(readingOptions: JSONSerialization.ReadingOptions = .allowFragments, completionHandler: @escaping ((Result<Any>) -> ())) -> Self {
return response(data: data, responseSerializer: JSONResponseSerializer(readingOptions: readingOptions), completionHandler: completionHandler)
}
/// Returns a string object contained in a result type constructed from the response data using `String.Encoding`
/// with the specified encoding options.
@discardableResult
public func responseString(encoding: String.Encoding = .utf8, completionHandler: @escaping ((Result<String>) -> ())) -> Self {
return response(data: data, responseSerializer: StringResponseSerializer(encoding: .utf8), completionHandler: completionHandler)
}
}
extension DataRequestOperation: URLSessionDataDelegate {
// MARK: NSURLSessionDataDelegate
public func urlSession(_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
guard isCancelled == false else {
finish()
sessionTask?.cancel()
return
}
completionHandler(.allow)
}
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
self.data.append(data)
}
}
| mit | bc0296ee6e07015be322b84fc0cd5079 | 42.951456 | 158 | 0.691628 | 5.467391 | false | false | false | false |
bryan1anderson/iMessage-to-Day-One-Importer | iMessage Importer/ContactsProtocol.swift | 1 | 6829 | //
// ContactsProtocol.swift
// iMessage Importer
//
// Created by Bryan on 8/8/17.
// Copyright © 2017 Bryan Lloyd Anderson. All rights reserved.
//
import Foundation
import Contacts
import SQLite
protocol ContactsProtocol {
}
extension ContactsProtocol {
func getNameString(for contacts: [CNContact]) -> String? {
if contacts.count > 0 {
// print(contacts)
let names = contacts.flatMap({ "\($0.givenName.capitalized) \($0.familyName.capitalized)" }).removeDuplicates()
let nameString = names.joined(separator: " ")
return nameString
} else {
return nil
}
}
func requestForAccess(completionHandler: @escaping (_ accessGranted: Bool) -> Void) {
// Get authorization
let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts)
// Find out what access level we have currently
switch authorizationStatus {
case .authorized:
completionHandler(true)
case .denied, .notDetermined:
CNContactStore().requestAccess(for: CNEntityType.contacts, completionHandler: { (access, accessError) -> Void in
if access {
completionHandler(access)
}
else {
if authorizationStatus == CNAuthorizationStatus.denied {
// DispatchQueue.main.async(execute: { () -> Void in
// let message = "\(accessError!.localizedDescription)\n\nPlease allow the app to access your contacts through the Settings."
// self.showMessage(message)
// })
}
}
})
default:
completionHandler(false)
}
}
func getContacts(for phoneNumbers: [String], completion: @escaping ([CNContact]) -> ()) {
var contacts = [CNContact]()
let group = DispatchGroup()
group.notify(queue: .main) {
print("Finished all requests.")
completion(contacts)
}
for phoneNumber in phoneNumbers {
group.enter()
getContacts(phoneNumber: phoneNumber, completion: { (contactArray) in
contacts += contactArray
group.leave()
})
}
}
func getContacts(phoneNumber: String, completion: @escaping ([CNContact]) -> ()) {
self.requestForAccess { (accessGranted) -> Void in
if accessGranted {
let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactImageDataKey, CNContactPhoneNumbersKey]
var contacts = [CNContact]()
var message: String!
let contactsStore = CNContactStore()
do {
try contactsStore.enumerateContacts(with: CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])) {
(contact, cursor) -> Void in
if (!contact.phoneNumbers.isEmpty) {
let phoneNumberToCompareAgainst = phoneNumber.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")
for phoneNumber in contact.phoneNumbers {
if let phoneNumberStruct = phoneNumber.value as? CNPhoneNumber {
let phoneNumberString = phoneNumberStruct.stringValue
let phoneNumberToCompare = phoneNumberString.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")
if phoneNumberToCompare.contains(phoneNumberToCompareAgainst) || phoneNumberToCompareAgainst.contains(phoneNumberToCompare)
&& phoneNumberString.characters.count > 5 {
contacts.append(contact)
}
}
}
}
}
if contacts.count == 0 {
message = "No contacts were found matching the given phone number."
}
}
catch {
message = "Unable to fetch contacts."
completion([])
}
if message != nil {
// dispatch_async(dispatch_get_main_queue(), { () -> Void in
// self.showMessage(message)
// })
completion([])
}
else {
// Success
// dispatch_async(dispatch_get_main_queue(), { () -> Void in
// Do someting with the contacts in the main queue, for example
/*
self.delegate.didFetchContacts(contacts) <= which extracts the required info and puts it in a tableview
*/
// print(contacts.count)
completion(contacts)
// guard let contact = contacts.first else { return }
// print(contacts) // Will print all contact info for each contact (multiple line is, for example, there are multiple phone numbers or email addresses)
// print(contact.givenName) // Print the "first" name
// print(contact.familyName) // Print the "last" name
// if contact.isKeyAvailable(CNContactImageDataKey) {
// if let contactImageData = contact.imageData {
// print(UIImage(data: contactImageData)) // Print the image set on the contact
// }
// } else {
// // No Image available
//
// }
// })
}
} else {
completion([])
}
}
}
}
| mit | 15faae69b744621da912147472a5e66b | 41.409938 | 194 | 0.454013 | 6.642023 | false | false | false | false |
STShenZhaoliang/iOS-GuidesAndSampleCode | 精通Swift设计模式/Chapter 19/SportsStore/SportsStore/ViewController.swift | 1 | 4032 | import UIKit
class ProductTableCell : UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var stockStepper: UIStepper!
@IBOutlet weak var stockField: UITextField!
var product:Product?;
}
var handler = { (p:Product) in
println("Change: \(p.name) \(p.stockLevel) items in stock");
};
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var totalStockLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
var productStore = ProductDataStore();
override func viewDidLoad() {
super.viewDidLoad();
displayStockTotal();
let bridge = EventBridge(callback: updateStockLevel);
productStore.callback = bridge.inputCallback;
}
func updateStockLevel(name:String, level:Int) {
for cell in self.tableView.visibleCells() {
if let pcell = cell as? ProductTableCell {
if pcell.product?.name == name {
pcell.stockStepper.value = Double(level);
pcell.stockField.text = String(level);
}
}
}
self.displayStockTotal();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return productStore.products.count;
}
func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let product = productStore.products[indexPath.row];
let cell = tableView.dequeueReusableCellWithIdentifier("ProductCell")
as ProductTableCell;
cell.product = productStore.products[indexPath.row];
cell.nameLabel.text = product.name;
cell.descriptionLabel.text = product.productDescription;
cell.stockStepper.value = Double(product.stockLevel);
cell.stockField.text = String(product.stockLevel);
CellFormatter.createChain().formatCell(cell);
return cell;
}
@IBAction func stockLevelDidChange(sender: AnyObject) {
if var currentCell = sender as? UIView {
while (true) {
currentCell = currentCell.superview!;
if let cell = currentCell as? ProductTableCell {
if let product = cell.product? {
if let stepper = sender as? UIStepper {
product.stockLevel = Int(stepper.value);
} else if let textfield = sender as? UITextField {
if let newValue = textfield.text.toInt()? {
product.stockLevel = newValue;
}
}
cell.stockStepper.value = Double(product.stockLevel);
cell.stockField.text = String(product.stockLevel);
productLogger.logItem(product);
StockServerFactory.getStockServer()
.setStockLevel(product.name, stockLevel: product.stockLevel);
}
break;
}
}
displayStockTotal();
}
}
func displayStockTotal() {
let finalTotals:(Int, Double) = productStore.products.reduce((0, 0.0),
{(totals, product) -> (Int, Double) in
return (
totals.0 + product.stockLevel,
totals.1 + product.stockValue
);
});
let formatted = StockTotalFacade.formatCurrencyAmount(finalTotals.1,
currency: StockTotalFacade.Currency.EUR);
totalStockLabel.text = "\(finalTotals.0) Products in Stock. "
+ "Total Value: \(formatted!)";
}
}
| mit | fb0f4b22ba984e8e04ed28db5bc59bbc | 35.990826 | 89 | 0.559524 | 5.340397 | false | false | false | false |
zpz1237/NirWebImage | ImageDownloader.swift | 1 | 9840 | //
// ImageDownloader.swift
// NirWebImage
//
// Created by Nirvana on 11/15/15.
// Copyright © 2015 NSNirvana. All rights reserved.
//
import UIKit
public typealias ImageDownloaderProgressBlock = DownloadProgressBlock
public typealias ImageDownloaderCompletionHandler = ((image: UIImage?, error: NSError?, imageURL: NSURL?, originalData: NSData?) -> ())
public typealias RetrieveImageDownloadTask = NSURLSessionDataTask
private let defaultDownloaderName = "default"
private let downloaderBarrierName = "com.NirWebImage.ImageDownloader.Barrier"
private let imageProcessQueueName = "com.NirWebImage.ImageDownloader.Process"
public enum NirWebImageError: Int {
case BadData = 10000
case NotModified = 10001
case InvalidURL = 20000
}
@objc public protocol ImageDownloaderDelegate {
optional func imageDownloader(downloader: ImageDownloader, didDownloadImage image: UIImage, forURL: NSURL, withResponse reponse: NSURLResponse)
}
public class ImageDownloader: NSObject {
class ImageFetchLoad {
var callbacks: [CallbackPair] = []
var responseData = NSMutableData()
var shouldDecode = false
var scale = NirWebImageManager.DefaultOptions.scale
}
public var requestModifier: (NSMutableURLRequest -> Void)?
public var downloadTimeout: NSTimeInterval = 15.0
public var trustedHosts: Set<String>?
public var sessionConfiguration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
public weak var deleagte: ImageDownloaderDelegate?
let barrierQueue: dispatch_queue_t
let processQueue: dispatch_queue_t
typealias CallbackPair = (progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?)
var fetchLoads: [NSURL: ImageFetchLoad] = [:]
static let defaultDownloader = ImageDownloader(name: defaultDownloaderName)
public init(name: String) {
if name.isEmpty {
fatalError()
}
barrierQueue = dispatch_queue_create(downloaderBarrierName + name, DISPATCH_QUEUE_CONCURRENT)
processQueue = dispatch_queue_create(imageProcessQueueName + name, DISPATCH_QUEUE_SERIAL)
}
func fetchLoadForKey(key: NSURL) -> ImageFetchLoad? {
var fetchLoad: ImageFetchLoad?
dispatch_sync(barrierQueue) { () -> Void in
fetchLoad = self.fetchLoads[key]
}
return fetchLoad
}
}
public extension ImageDownloader {
public func downloadImageWithURL(URL: NSURL, progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) {
downloadImageWithURL(URL, options: NirWebImageManager.DefaultOptions, progressBlock: progressBlock, completionHandler: completionHandler)
}
public func downloadImageWithURL(URL: NSURL, options: NirWebImageManager.Options, progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) {
downloadImageWithURL(URL,
retrieveImageTask: nil,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
internal func downloadImageWithURL(URL: NSURL, retrieveImageTask: RetrieveImageTask?, options: NirWebImageManager.Options, progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) {
if let retrieveImageTask = retrieveImageTask where retrieveImageTask.cancelled{
return
}
let timeout = self.downloadTimeout == 0.0 ? 15.0 : self.downloadTimeout
let request = NSMutableURLRequest(URL: URL, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: timeout)
request.HTTPShouldUsePipelining = true
self.requestModifier?(request)
if request.URL == nil {
completionHandler?(image: nil, error: NSError(domain: NirWebImageErrorDomain, code: NirWebImageError.InvalidURL.rawValue, userInfo: nil), imageURL: nil, originalData: nil)
return
}
setupProgressBlock(progressBlock, completionHandler: completionHandler, forURL: request.URL!) { (session, fetchLoad) -> Void in
let task = session.dataTaskWithRequest(request)
task.priority = options.lowPriority ? NSURLSessionTaskPriorityLow : NSURLSessionTaskPriorityDefault
task.resume()
fetchLoad.shouldDecode = options.shouldDecode
fetchLoad.scale = options.scale
retrieveImageTask?.downloadTask = task
}
}
internal func setupProgressBlock(progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?, forURL URL: NSURL, started: ((NSURLSession, ImageFetchLoad) -> Void)) {
dispatch_barrier_sync(barrierQueue) { () -> Void in
var create = false
var loadObjectForURL = self.fetchLoads[URL]
if loadObjectForURL == nil {
create = true
loadObjectForURL = ImageFetchLoad()
}
let callbackPair = (progressBlock: progressBlock, completionHandler: completionHandler)
loadObjectForURL!.callbacks.append(callbackPair)
self.fetchLoads[URL] = loadObjectForURL!
if create {
let session = NSURLSession(configuration: self.sessionConfiguration, delegate: self, delegateQueue:NSOperationQueue.mainQueue())
started(session, loadObjectForURL!)
}
}
}
func cleanForURL(URL: NSURL) {
dispatch_barrier_sync(barrierQueue) { () -> Void in
self.fetchLoads.removeValueForKey(URL)
return
}
}
}
extension ImageDownloader: NSURLSessionDataDelegate {
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
completionHandler(NSURLSessionResponseDisposition.Allow)
}
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if let URL = dataTask.originalRequest?.URL, fetchLoad = fetchLoadForKey(URL) {
fetchLoad.responseData.appendData(data)
for callbackPair in fetchLoad.callbacks {
callbackPair.progressBlock?(receivedSize: Int64(fetchLoad.responseData.length), totalSize: dataTask.response!.expectedContentLength)
}
}
}
private func callBackWithImage(image: UIImage?, error: NSError?, imageURL: NSURL, originalData: NSData?) {
if let callbackPairs = fetchLoadForKey(imageURL)?.callbacks {
self.cleanForURL(imageURL)
for callbackPair in callbackPairs {
callbackPair.completionHandler?(image: image, error: error, imageURL: imageURL, originalData: originalData)
}
}
}
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let URL = task.originalRequest?.URL {
if let error = error {
callBackWithImage(nil, error: error, imageURL: URL, originalData: nil)
} else {
dispatch_async(processQueue, { () -> Void in
if let fetchLoad = self.fetchLoadForKey(URL) {
if let image = UIImage.nir_imageWithData(fetchLoad.responseData, scale: fetchLoad.scale) {
self.deleagte?.imageDownloader?(self, didDownloadImage: image, forURL: URL, withResponse: task.response!)
if fetchLoad.shouldDecode {
self.callBackWithImage(image.nir_decodeImage(), error: error, imageURL: URL, originalData: fetchLoad.responseData)
} else {
self.callBackWithImage(image, error: error, imageURL: URL, originalData: fetchLoad.responseData)
}
} else {
if let res = task.response as? NSHTTPURLResponse where res.statusCode == 304 {
self.callBackWithImage(nil, error: NSError(domain: NirWebImageErrorDomain, code: NirWebImageError.NotModified.rawValue, userInfo: nil), imageURL: URL, originalData: nil)
return
}
self.callBackWithImage(nil, error: NSError(domain: NirWebImageErrorDomain, code: NirWebImageError.BadData.rawValue, userInfo: nil), imageURL: URL, originalData: nil)
}
} else {
self.callBackWithImage(nil, error: NSError(domain: NirWebImageErrorDomain, code: NirWebImageError.BadData.rawValue, userInfo: nil), imageURL: URL, originalData: nil)
}
})
}
}
}
public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
if let trustedHosts = trustedHosts where trustedHosts.contains(challenge.protectionSpace.host) {
let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)
completionHandler(.UseCredential, credential)
return
}
}
completionHandler(.PerformDefaultHandling, nil)
}
} | mit | 67a45f151db67d403dd2da7cd0008311 | 45.415094 | 228 | 0.659925 | 5.811577 | false | false | false | false |
jpush/jchat-swift | JChat/Src/UserModule/View/JCJChatInfoCell.swift | 1 | 2157 | //
// JCJChatInfoCell.swift
// JChat
//
// Created by JIGUANG on 2017/5/24.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
class JCJChatInfoCell: UITableViewCell {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
_init()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
_init()
}
override func awakeFromNib() {
super.awakeFromNib()
_init()
}
private lazy var avatorView: UIImageView = UIImageView()
private lazy var nameLabel: UILabel = {
let nameLabel = UILabel()
let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")
nameLabel.textAlignment = .center
nameLabel.text = "JChat v\(String(describing: version!))"
nameLabel.font = UIFont.systemFont(ofSize: 15)
nameLabel.textColor = UIColor(netHex: 0x999999)
nameLabel.backgroundColor = .white
nameLabel.layer.masksToBounds = true
return nameLabel
}()
//MARK: - private func
private func _init() {
avatorView.image = UIImage.loadImage("com_icon_about")
contentView.addSubview(avatorView)
contentView.addSubview(nameLabel)
addConstraint(_JCLayoutConstraintMake(avatorView, .top, .equal, contentView, .top, 27))
addConstraint(_JCLayoutConstraintMake(avatorView, .centerX, .equal, contentView, .centerX))
addConstraint(_JCLayoutConstraintMake(avatorView, .width, .equal, nil, .notAnAttribute, 56))
addConstraint(_JCLayoutConstraintMake(avatorView, .height, .equal, nil, .notAnAttribute, 56))
addConstraint(_JCLayoutConstraintMake(nameLabel, .top, .equal, avatorView, .bottom, 9))
addConstraint(_JCLayoutConstraintMake(nameLabel, .right, .equal, contentView, .right))
addConstraint(_JCLayoutConstraintMake(nameLabel, .left, .equal, contentView, .left))
addConstraint(_JCLayoutConstraintMake(nameLabel, .height, .equal, nil, .notAnAttribute, 22.5))
}
}
| mit | a6b7c2af5001af65345894a15d973341 | 36.137931 | 102 | 0.671309 | 4.592751 | false | false | false | false |
LeonardoCardoso/SwiftLinkPreview | Example/SwiftLinkPreviewExample/Controllers/ViewController.swift | 1 | 8809 | //
// ViewController.swift
// SwiftLinkPreviewExample
//
// Created by Leonardo Cardoso on 09/06/2016.
// Copyright © 2016 leocardz.com. All rights reserved.
//
import UIKit
import SwiftyDrop
import ImageSlideshow
import SwiftLinkPreview
class ViewController: UIViewController {
// MARK: - Properties
@IBOutlet private weak var centerLoadingActivityIndicatorView: UIActivityIndicatorView?
@IBOutlet private weak var textField: UITextField?
@IBOutlet private weak var randomTextButton: UIButton?
@IBOutlet private weak var submitButton: UIButton?
@IBOutlet private weak var openWithButton: UIButton?
@IBOutlet private weak var indicator: UIActivityIndicatorView?
@IBOutlet private weak var previewArea: UIView?
@IBOutlet private weak var previewAreaLabel: UILabel?
@IBOutlet private weak var slideshow: ImageSlideshow?
@IBOutlet private weak var previewTitle: UILabel?
@IBOutlet private weak var previewCanonicalUrl: UILabel?
@IBOutlet private weak var previewDescription: UILabel?
@IBOutlet private weak var detailedView: UIView?
@IBOutlet private weak var favicon: UIImageView?
// MARK: - Vars
private var randomTexts: [String] = [
"blinkist.com",
"uber.com",
"tw.yahoo.com",
"https://www.linkedin.com/",
"www.youtube.com",
"www.google.com",
"facebook.com",
"https://github.com/LeonardoCardoso/SwiftLinkPreview",
"https://www.jbhifi.com.au/products/playstation-4-biomutant",
"https://leocardz.com/swift-link-preview-5a9860c7756f",
"NASA! 🖖🏽 https://www.nasa.gov/",
"https://www.theverge.com/2016/6/21/11996280/tesla-offer-solar-city-buy",
"Shorten URL http://bit.ly/14SD1eR",
"Tweet! https://twitter.com",
"A Gallery https://www.nationalgallery.org.uk",
"www.dji.com/matrice600-pro/info#specs",
"A Brazilian website http://globo.com",
"Another Brazilian website https://uol.com.br",
"Some Vietnamese chars https://vnexpress.net/",
"Japan!!! https://www3.nhk.or.jp/",
"A Russian website >> https://habrahabr.ru",
"Youtube?! It does! https://www.youtube.com/watch?v=cv2mjAgFTaI",
"Also Vimeo https://vimeo.com/67992157",
"Well, it's a gif! https://goo.gl/jKCPgp"
]
private var result = Response()
private let placeholderImages = [ImageSource(image: UIImage(named: "Placeholder")!)]
private let slp = SwiftLinkPreview(cache: InMemoryCache())
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.showHideAll(hide: true)
self.setUpSlideshow()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func getRandomText() -> String {
return randomTexts[Int(arc4random_uniform(UInt32(randomTexts.count)))]
}
private func startCrawling() {
self.centerLoadingActivityIndicatorView?.startAnimating()
self.updateUI(enabled: false)
self.showHideAll(hide: true)
self.textField?.resignFirstResponder()
self.indicator?.isHidden = false
}
private func endCrawling() {
self.updateUI(enabled: true)
}
// Update UI
private func showHideAll(hide: Bool) {
self.slideshow?.isHidden = hide
self.detailedView?.isHidden = hide
self.openWithButton?.isHidden = hide
self.previewAreaLabel?.isHidden = !hide
}
private func updateUI(enabled: Bool) {
self.indicator?.isHidden = enabled
self.textField?.isEnabled = enabled
self.randomTextButton?.isEnabled = enabled
self.submitButton?.isEnabled = enabled
}
private func setData() {
if let value = self.result.images {
if !value.isEmpty {
var images: [InputSource] = []
for image in value {
if let source = AlamofireSource(urlString: image) {
images.append(source)
}
}
self.setImage(images: images)
} else {
self.setImage(image: self.result.image)
}
} else {
self.setImage(image: self.result.image)
}
if let value: String = self.result.title {
self.previewTitle?.text = value.isEmpty ? "No title" : value
} else {
self.previewTitle?.text = "No title"
}
if let value: String = self.result.canonicalUrl {
self.previewCanonicalUrl?.text = value
}
if let value: String = self.result.description {
self.previewDescription?.text = value.isEmpty ? "No description" : value
} else {
self.previewTitle?.text = "No description"
}
if let value: String = self.result.icon, let url = URL(string: value) {
self.favicon?.af.setImage(withURL: url)
}
self.showHideAll(hide: false)
self.endCrawling()
}
private func setImage(image: String?) {
if let image: String = image {
if !image.isEmpty {
if let source = AlamofireSource(urlString: image) {
self.setImage(images: [source])
} else {
self.slideshow?.setImageInputs(placeholderImages)
}
} else {
self.slideshow?.setImageInputs(placeholderImages)
}
} else {
self.slideshow?.setImageInputs(placeholderImages)
}
self.centerLoadingActivityIndicatorView?.stopAnimating()
}
private func setImage(images: [InputSource]?) {
if let images = images {
self.slideshow?.setImageInputs(images)
} else {
self.slideshow?.setImageInputs(placeholderImages)
}
self.centerLoadingActivityIndicatorView?.stopAnimating()
}
private func setUpSlideshow() {
self.slideshow?.backgroundColor = UIColor.white
self.slideshow?.slideshowInterval = 7.0
self.slideshow?.pageIndicatorPosition = .init(horizontal: .center, vertical: .bottom)
self.slideshow?.contentScaleMode = .scaleAspectFill
}
// MARK: - Actions
@IBAction func randomTextAction(_ sender: AnyObject) {
textField?.text = getRandomText()
}
@IBAction func submitAction(_ sender: AnyObject) {
func printResult(_ result: Response) {
print("url: ", result.url ?? "no url")
print("finalUrl: ", result.finalUrl ?? "no finalUrl")
print("canonicalUrl: ", result.canonicalUrl ?? "no canonicalUrl")
print("title: ", result.title ?? "no title")
print("images: ", result.images ?? "no images")
print("image: ", result.image ?? "no image")
print("video: ", result.video ?? "no video")
print("icon: ", result.icon ?? "no icon")
print("description: ", result.description ?? "no description")
print("baseURL: ", result.baseURL ?? "no baseURL")
}
guard textField?.text?.isEmpty == false else {
Drop.down("Please, enter a text", state: .warning)
return
}
self.startCrawling()
let textFieldText = textField?.text ?? String()
if let url = self.slp.extractURL(text: textFieldText),
let cached = self.slp.cache.slp_getCachedResponse(url: url.absoluteString) {
self.result = cached
self.setData()
printResult(result)
} else {
self.slp.preview(
textFieldText,
onSuccess: { result in
printResult(result)
self.result = result
self.setData()
},
onError: { error in
print(error)
self.endCrawling()
Drop.down(error.description, state: .error)
}
)
}
}
@IBAction func openWithAction(_ sender: UIButton) {
if let url = self.result.finalUrl {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
}
// MARK: - UITextFieldDelegate
extension ViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.submitAction(textField)
self.textField?.resignFirstResponder()
return true
}
}
| mit | c74b917467e36ae4eeca20d08597b04d | 24.812317 | 93 | 0.591684 | 4.562986 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK | AviasalesSDKTemplate/Source/CommonSource/CurrencyPicker/CurrencyPickerViewController.swift | 1 | 4898 | //
// CurrencyPickerViewController.swift
// AviasalesSDKTemplate
//
// Created by Dim on 11.09.17.
// Copyright © 2017 Go Travel Un Limited. All rights reserved.
//
import UIKit
class CurrencyPickerViewController: UIViewController {
let presenter: CurrencyPickerPresenter
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
var sectionModels = [CurrencyPickerSectionModel]()
init(selection: @escaping () -> Void) {
presenter = CurrencyPickerPresenter(selection: selection)
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setup()
presenter.attach(self)
}
// MARK: - Setup
private func setup() {
setupNavigationItem()
setupSearchBar()
setupTableView()
}
private func setupNavigationItem() {
navigationItem.title = NSLS("HL_LOC_ABOUT_CURRENCY")
}
private func setupSearchBar() {
searchBar.placeholder = NSLS("LOC_CURRENCY_SEARCH_PLACEHOLDER")
searchBar.returnKeyType = .done
searchBar.enablesReturnKeyAutomatically = false
searchBar.tintColor = JRColorScheme.darkTextColor()
}
private func setupTableView() {
tableView.register(UINib(nibName: CurrencyCell.identifier, bundle: nil), forCellReuseIdentifier: CurrencyCell.identifier)
}
// MARK: - Update
fileprivate func updateVisibleCells() {
guard let indexPaths = tableView.indexPathsForVisibleRows else {
return
}
for indexPath in indexPaths {
let cellModel = sectionModels[indexPath.section].cellModels[indexPath.row]
let cell = tableView.cellForRow(at: indexPath) as? CurrencyCell
cell?.update(cellModel)
}
}
fileprivate func updateCell(at indexPath: IndexPath) {
let cellModel = sectionModels[indexPath.section].cellModels[indexPath.row]
let cell = tableView.cellForRow(at: indexPath) as? CurrencyCell
cell?.update(cellModel)
}
}
extension CurrencyPickerViewController: CurrencyPickerViewProtocol {
func set(sectionModels: [CurrencyPickerSectionModel]) {
self.sectionModels = sectionModels
tableView.reloadData()
tableView.contentOffset = .zero
}
func update(sectionModels: [CurrencyPickerSectionModel]) {
self.sectionModels = sectionModels
updateVisibleCells()
}
func showCurrencyAlert() {
showAlert(title: NSLS("CHANGE_CURRENCY_ALERT_TITLE"), message: NSLS("CHANGE_CURRENCY_ALERT_DESCRIPTION"), cancelButtonTitle: NSLS("HL_LOC_ALERT_CLOSE_BUTTON"))
}
}
extension CurrencyPickerViewController: UISearchBarDelegate {
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(false, animated: true)
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
presenter.search(searchText)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = String()
presenter.search(String())
searchBar.resignFirstResponder()
}
}
extension CurrencyPickerViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return sectionModels.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sectionModels[section].cellModels.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellModel = sectionModels[indexPath.section].cellModels[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: CurrencyCell.identifier, for: indexPath) as! CurrencyCell
cell.setup(cellModel)
return cell
}
}
extension CurrencyPickerViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return tableView.sectionHeaderHeight
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return tableView.sectionFooterHeight
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let cellModel = sectionModels[indexPath.section].cellModels[indexPath.row]
presenter.select(cellModel)
}
}
| mit | 23688bcf3a7dd09062560feb6c0c920d | 29.993671 | 167 | 0.696753 | 5.299784 | false | false | false | false |
silence0201/Swift-Study | GuidedTour/23Generics.playground/Contents.swift | 1 | 4979 | //: Playground - noun: a place where people can play
func swapTwoInts(_ a: inout Int, _ b:inout Int){
let temp = a
a = b
b = temp
}
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
func swapTwoStrings(_ a: inout String, _ b: inout String) {
let temporaryA = a
a = b
b = temporaryA
}
// 泛型
func swapTwoValue<T>(_ a: inout T, _ b: inout T){
let temp = a
a = b
b = temp
}
swapTwoValue(&someInt, &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
var someString = "hello"
var anotherString = "world"
swapTwoValue(&someString, &anotherString)
print("someString is now \(someString), and anotherString is now \(anotherString)")
// 不带泛型的结构体
struct IntStack {
var items = [Int]()
mutating func push(_ item: Int) {
items.append(item)
}
mutating func pop() -> Int {
return items.removeLast()
}
}
// 带泛型的结构体
struct Stack<Element>{
var items = [Element]()
mutating func push(_ item: Element){
items.append(item)
}
mutating func pop() -> Element{
return items.removeLast()
}
}
var stackOfStrings = Stack<String>()
stackOfStrings.push("uno")
stackOfStrings.push("dos")
stackOfStrings.push("tres")
stackOfStrings.push("cuatro")
print(stackOfStrings)
let fromTheTop = stackOfStrings.pop()
extension Stack{
var topItem: Element?{
return items.isEmpty ? nil : items[items.count - 1]
}
}
if let topItem = stackOfStrings.topItem{
print("The top item on the stack is \(topItem).")
}
func findIndex(ofString valueToFind: String, in array: [String]) -> Int?{
for (index,value) in array.enumerated(){
if value == valueToFind{
return index
}
}
return nil
}
let strings = ["cat", "dog", "llama", "parakeet", "terrapin"]
if let foundIndex = findIndex(ofString: "llama", in: strings) {
print("The index of llama is \(foundIndex)")
}
func findIndex<T:Equatable>(of valueToFind: T,in array:[T]) -> Int?{
for (index, value) in array.enumerated() {
if value == valueToFind {
return index
}
}
return nil
}
let doubleIndex = findIndex(of: 9.3, in: [3.14159, 0.1, 0.25])
let stringIndex = findIndex(of: "Andrea", in: ["Mike", "Malcolm", "Andrea"])
// 类型关联
protocol Container{
associatedtype Item
mutating func append(_ item: Item)
var count: Int{get}
subscript(i: Int) -> Item {get}
}
struct IntStack2: Container {
// original IntStack implementation
var items = [Int]()
mutating func push(_ item: Int) {
items.append(item)
}
mutating func pop() -> Int {
return items.removeLast()
}
// conformance to the Container protocol
typealias Item = Int
mutating func append(_ item: Int) {
self.push(item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> Int {
return items[i]
}
}
struct Stack2<Element>: Container {
// original Stack<T> implementation
var items = [Element]()
mutating func push(_ item: Element) {
items.append(item)
}
mutating func pop() -> Element {
return items.removeLast()
}
// conformance to the Container protocol
mutating func append(_ item: Element) {
self.push(item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> Element {
return items[i]
}
}
extension Array: Container {}
func allItemsMatch<C1: Container, C2: Container>(_ someContainer: C1, _ anotherContainer: C2) -> Bool
where C1.Item == C2.Item, C1.Item: Equatable {
// check that both containers contain the same number of items
if someContainer.count != anotherContainer.count {
return false
}
// check each pair of items it see if they are equivilent
for i in 0..<someContainer.count {
if someContainer[i] != anotherContainer[i] {
return false
}
}
// all items match, so return true
return true
}
var stackOfStrings2 = Stack2<String>()
stackOfStrings2.push("uno")
stackOfStrings2.push("dos")
stackOfStrings2.push("tres")
var arrayOfStrings = ["uno", "dos", "tres"]
if allItemsMatch(stackOfStrings2, arrayOfStrings){
print("Match")
}else{
print("Not all Match")
}
extension Stack2 where Element:Equatable{
func isTop(_ item: Element) -> Bool{
guard let topItem = items.last else{
return false
}
return topItem == item
}
}
if stackOfStrings2.isTop("tres") {
print("Top element is tres.")
} else {
print("Top element is something else.")
}
struct NotEquatable { }
var notEquatableStack = Stack2<NotEquatable>()
let notEquatableValue = NotEquatable()
notEquatableStack.push(notEquatableValue)
| mit | 74cfc92143f4df31c8f68d1e7ea7f34b | 22.966019 | 101 | 0.623861 | 3.786043 | false | false | false | false |
DarielChen/DemoCode | iOS动画指南/iOS动画指南 - 6.可以很酷的转场动画/2.reveal/1.reveal/reveal/RWLogoLayer.swift | 1 | 1250 | //
// RWLogoLayer.swift
// reveal
//
// Created by Dariel on 16/7/26.
// Copyright © 2016年 Dariel. All rights reserved.
//
import UIKit
class RWLogoLayer {
class func logoLayer() -> CAShapeLayer {
let layer = CAShapeLayer()
layer.geometryFlipped = true
let bezier = UIBezierPath()
bezier.moveToPoint(CGPoint(x: 0.0, y: 0.0))
bezier.addCurveToPoint(CGPoint(x: 0.0, y: 66.97), controlPoint1:CGPoint(x: 0.0, y: 0.0), controlPoint2:CGPoint(x: 0.0, y: 57.06))
bezier.addCurveToPoint(CGPoint(x: 16.0, y: 39.0), controlPoint1: CGPoint(x: 27.68, y: 66.97), controlPoint2:CGPoint(x: 42.35, y: 52.75))
bezier.addCurveToPoint(CGPoint(x: 26.0, y: 17.0), controlPoint1: CGPoint(x: 17.35, y: 35.41), controlPoint2:CGPoint(x: 26, y: 17))
bezier.addLineToPoint(CGPoint(x: 38.0, y: 34.0))
bezier.addLineToPoint(CGPoint(x: 49.0, y: 17.0))
bezier.addLineToPoint(CGPoint(x: 67.0, y: 51.27))
bezier.addLineToPoint(CGPoint(x: 67.0, y: 0.0))
bezier.addLineToPoint(CGPoint(x: 0.0, y: 0.0))
bezier.closePath()
layer.path = bezier.CGPath
layer.bounds = CGPathGetBoundingBox(layer.path)
return layer
}
}
| mit | aafa2d057c6f631b38a43743cb3f44d2 | 35.676471 | 144 | 0.618284 | 3.247396 | false | false | false | false |
jlecomte/iOSTipCalculator | TipCalculator/ViewController.swift | 1 | 1681 | //
// ViewController.swift
// TipCalculator
//
// Created by Julien Lecomte on 9/7/14.
// Copyright (c) 2014 Julien Lecomte. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tfCheckAmount: UITextField!
@IBOutlet weak var scTipPercentage: UISegmentedControl!
@IBOutlet weak var lbTipAmount: UILabel!
@IBOutlet weak var lbTotalAmount: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
computeTipAndTotalAmount()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func onTap(sender: AnyObject) {
view.endEditing(true)
}
@IBAction func checkAmountChanged(sender: AnyObject) {
computeTipAndTotalAmount();
}
@IBAction func onTipPercentageChanged(sender: AnyObject) {
computeTipAndTotalAmount();
}
func computeTipAndTotalAmount() {
let tipPercentages = [0.15, 0.2, 0.25]
var defaults = NSUserDefaults.standardUserDefaults()
let roundup = defaults.boolForKey("roundup")
var checkAmount = NSString(string: tfCheckAmount.text).doubleValue
var tipPercentage = tipPercentages[scTipPercentage.selectedSegmentIndex]
var tipAmount = checkAmount * tipPercentage
var totalAmount = checkAmount + tipAmount
if roundup {
totalAmount = ceil(totalAmount)
tipAmount = totalAmount - checkAmount
}
lbTipAmount.text = String(format: "$%.2f", tipAmount)
lbTotalAmount.text = String(format: "$%.2f", totalAmount)
}
}
| mit | 6909429981fcc63a9f94d9e6103175b4 | 26.557377 | 80 | 0.672219 | 4.72191 | false | false | false | false |
manhpro/website | iOSQuiz-master/iOSQuiz-master/LeoiOSQuiz/Classes/Models/Restaurant.swift | 1 | 1345 | //
// Restaurant.swift
// LeoiOSQuiz
//
// Created by framgia on 4/17/17.
// Copyright © 2017 Leo LE. All rights reserved.
//
import UIKit
import ObjectMapper
class Restaurant: Mappable {
var id: String
var name: String
var rating: Float
var price: String
var phone: String
var imageUrl: String
var url: String
var reviewCount: Int
var coordinates : Coordinate
var categories: [Category]
var location: Location
var reviews: [Review]
init() {
self.id = ""
self.name = ""
self.rating = 0.0
self.price = ""
self.phone = ""
self.imageUrl = ""
self.url = ""
self.reviewCount = 0
self.coordinates = Coordinate()
self.categories = [Category]()
self.location = Location()
self.reviews = [Review]()
}
convenience required init?(map: Map) {
self.init()
}
func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
rating <- map["rating"]
price <- map["price"]
phone <- map["phone"]
imageUrl <- map["image_url"]
url <- map["url"]
reviewCount <- map["review_count"]
coordinates <- map["coordinates"]
categories <- map["categories"]
location <- map["location"]
}
}
| cc0-1.0 | e8003a4595913d85337a250684479f8c | 21.779661 | 49 | 0.540923 | 4.148148 | false | false | false | false |
Lohann/OpencvSwift | OpencvSwift/Operators.swift | 1 | 5616 | //
// Operators.swift
// OpencvSwift
//
// Created by Lohann Paterno Coutinho Ferreira on 21/09/15.
// Copyright © 2015 Lohann Paterno Coutinho Ferreira. All rights reserved.
//
import Foundation
public func + (left:CvMat, right: CvMat) -> CvMat {
let result:CvMat = CvMat()
Cv3.add(left, src2: right, dst: result)
return result;
}
public func - (left:CvMat, right: CvMat) -> CvMat {
let result:CvMat = CvMat()
Cv3.subtract(left, src2: right, dst: result)
return result;
}
public func / (left:CvMat, right: CvMat) -> CvMat {
let result:CvMat = CvMat()
Cv3.divide(left, src2: right, dst: result)
return result;
}
public func * (left:CvMat, right: CvMat) -> CvMat {
let result:CvMat = CvMat()
Cv3.multiply(left, src2: right, dst: result)
return result;
}
public func + (left:CvMat, right: Double) -> CvMat {
let result:CvMat = CvMat()
OperatorsOverloading.add(left, double: right, result: result)
return result;
}
public func - (left:CvMat, right: Double) -> CvMat {
let result:CvMat = CvMat()
OperatorsOverloading.subtract(left, double: right, result: result)
return result;
}
public func / (left:CvMat, right: Double) -> CvMat {
let result:CvMat = CvMat()
OperatorsOverloading.divide(left, double: right, result: result)
return result;
}
public func * (left:CvMat, right: Double) -> CvMat {
let result:CvMat = CvMat()
OperatorsOverloading.multiply(left, double: right, result: result)
return result;
}
public func ^ (left:CvMat, right: Double) -> CvMat {
let result:CvMat = CvMat()
Cv3.pow(left, power: right, dst:result)
return result;
}
public func + (left:CvMat, right: Int) -> CvMat {
let result:CvMat = CvMat()
OperatorsOverloading.add(left, int: right, result: result)
return result;
}
public func - (left:CvMat, right: Int) -> CvMat {
let result:CvMat = CvMat()
OperatorsOverloading.subtract(left, int: right, result: result)
return result;
}
public func / (left:CvMat, right: Int) -> CvMat {
let result:CvMat = CvMat()
OperatorsOverloading.divide(left, int: right, result: result)
return result;
}
public func * (left:CvMat, right: Int) -> CvMat {
let result:CvMat = CvMat()
OperatorsOverloading.multiply(left, int: right, result: result)
return result;
}
public func + (left:Double, right: CvMat) -> CvMat {
let result:CvMat = CvMat()
OperatorsOverloading.add(right, double: left, result: result)
return result;
}
public func - (left:Double, right: CvMat) -> CvMat {
let result:CvMat = CvMat()
OperatorsOverloading.subtract(right, double: left, result: result)
return result;
}
public func / (left:Double, right: CvMat) -> CvMat {
let result:CvMat = CvMat()
OperatorsOverloading.divide(right, double: left, result: result)
return result;
}
public func * (left:Double, right: CvMat) -> CvMat {
let result:CvMat = CvMat()
OperatorsOverloading.multiply(right, double: left, result: result)
return result;
}
public func ^ (left:Double, right: CvMat) -> CvMat {
let result:CvMat = CvMat()
Cv3.pow(right, power: left, dst:result)
return result;
}
public func + (left:Int, right: CvMat) -> CvMat {
let result:CvMat = CvMat()
OperatorsOverloading.add(right, int: left, result: result)
return result;
}
public func - (left:Int, right: CvMat) -> CvMat {
let result:CvMat = CvMat()
OperatorsOverloading.subtract(right, int: left, result: result)
return result;
}
public func / (left:Int, right: CvMat) -> CvMat {
let result:CvMat = CvMat()
OperatorsOverloading.divide(right, int: left, result: result)
return result;
}
public func * (left:Int, right: CvMat) -> CvMat {
let result:CvMat = CvMat()
OperatorsOverloading.multiply(right, int: left, result: result)
return result;
}
public func += (left:CvMat, right: CvMat) {
Cv3.add(left, src2: right, dst: left)
}
public func -= (left:CvMat, right: CvMat) {
Cv3.subtract(left, src2: right, dst: left)
}
public func /= (left:CvMat, right: CvMat) {
Cv3.divide(left, src2: right, dst: left)
}
public func *= (left:CvMat, right: CvMat) {
Cv3.multiply(left, src2: right, dst: left)
}
public func += (left:CvMat, right: Double) {
OperatorsOverloading.addTo(left, double: right)
}
public func -= (left:CvMat, right: Double) {
OperatorsOverloading.subtractTo(left, double: right)
}
public func /= (left:CvMat, right: Double) {
OperatorsOverloading.divideTo(left, double: right)
}
public func *= (left:CvMat, right: Double) {
OperatorsOverloading.multiplyTo(left, double: right)
}
public func += (left:CvMat, right: Int) {
OperatorsOverloading.addTo(left, int: right)
}
public func -= (left:CvMat, right: Int) {
OperatorsOverloading.subtractTo(left, int: right)
}
public func /= (left:CvMat, right: Int) {
OperatorsOverloading.divideTo(left, int: right)
}
public func *= (left:CvMat, right: Int) {
OperatorsOverloading.multiplyTo(left, int: right)
}
public func + (left:CvMat, right: [NSNumber]) -> CvMat {
let result:CvMat = CvMat()
OperatorsOverloading.add(left, array: right, result: result)
return result;
}
public func - (left:CvMat, right: [NSNumber]) -> CvMat {
let result:CvMat = CvMat()
OperatorsOverloading.subtract(left, array: right, result: result)
return result;
}
public func += (left:CvMat, right: [NSNumber]) {
OperatorsOverloading.addTo(left, array: right)
}
public func -= (left:CvMat, right: [NSNumber]) {
OperatorsOverloading.subtractTo(left, array: right)
}
| mit | 45faea7b5d09430852ca4bd02133d8b0 | 24.875576 | 75 | 0.669991 | 3.020441 | false | false | false | false |
thoughtbot/DeltaTodoExample | Source/Views/FooterView.swift | 1 | 1033 | import UIKit
class FooterView: UIView {
var stackView: UIStackView? {
return self.subviews.first as? UIStackView
}
var itemsLeftLabel: UILabel? {
return stackView?.subviews.first as? UILabel
}
var clearCompletedButton: UIButton? {
return stackView?.subviews.last as? UIButton
}
override func awakeFromNib() {
self.clearCompletedButton?.addTarget(self, action: "clearCompletedTapped", forControlEvents: .TouchUpInside)
self.subscribeToStoreChanges()
}
func subscribeToStoreChanges() {
store.todoStats.startWithNext { todosCount, incompleteCount in
self.clearCompletedButton?.hidden = todosCount == incompleteCount
if incompleteCount == 1 {
self.itemsLeftLabel?.text = "1 todo left"
} else {
self.itemsLeftLabel?.text = "\(incompleteCount) todos left"
}
}
}
func clearCompletedTapped() {
store.dispatch(ClearCompletedTodosAction())
}
}
| mit | 95cd040c6504774d1c6b46f1665dfc7b | 27.694444 | 116 | 0.638916 | 4.919048 | false | false | false | false |
WickedColdfront/Slide-iOS | Slide for Reddit/OverlayPresentationController.swift | 1 | 2385 | //
// Copyright 2014 Scott Logic
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
class OverlayPresentationController: UIPresentationController {
let dimmingView = UIView()
override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController!) {
super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
dimmingView.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
}
override func adaptivePresentationStyle(for traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .pageSheet
}
override func presentationTransitionWillBegin() {
dimmingView.frame = (containerView?.bounds)!
dimmingView.alpha = 0.0
containerView?.insertSubview(dimmingView, at: 0)
presentedViewController.transitionCoordinator?.animate(alongsideTransition: {
context in
self.dimmingView.alpha = 1.0
}, completion: nil)
}
override func dismissalTransitionWillBegin() {
presentedViewController.transitionCoordinator?.animate(alongsideTransition: {
context in
self.dimmingView.alpha = 0.0
}, completion: {
context in
self.dimmingView.removeFromSuperview()
})
}
override var frameOfPresentedViewInContainerView : CGRect {
let boundHeight = containerView?.bounds.height
let boundWidth = containerView?.bounds.width
let bound = CGRect.init(x: 0, y: 40, width: boundWidth!, height: boundHeight! - 40.0)
return bound
}
override func containerViewWillLayoutSubviews() {
dimmingView.frame = (containerView?.bounds)!
print("Getting frame")
presentedView?.frame = frameOfPresentedViewInContainerView
}
}
| apache-2.0 | 61534d0626228846400ab67d61e2452d | 36.857143 | 118 | 0.698113 | 5.533643 | false | false | false | false |
EugeneVegner/sws-copyleaks-sdk-test | Example/PlagiarismChecker/AppDelegate.swift | 1 | 2376 | /*
* The MIT License(MIT)
*
* Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import UIKit
import PlagiarismChecker
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(
application: UIApplication,
didFinishLaunchingWithOptions
launchOptions: [NSObject: AnyObject]?) -> Bool {
// CopyleaksSDK Configure.
Copyleaks.configure(
sandboxMode: true,
product: .Businesses)
return true
}
}
// Utilities
func Alert(title : String, message: String?) {
let alert = UIAlertController(
title: title,
message: message,
preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
var topController = UIApplication.sharedApplication().keyWindow!.rootViewController! as UIViewController
while ((topController.presentedViewController) != nil) {
topController = topController.presentedViewController!;
}
let app = UIApplication.sharedApplication().delegate as! AppDelegate
app.window?.rootViewController?.presentViewController(alert, animated:true, completion:nil)
}
| mit | d74853dda536c51305e187f02d7c6b48 | 31.547945 | 108 | 0.719276 | 5.002105 | false | false | false | false |
wgywgy/SimpleActionSheet | Source/ActionSheetItemView.swift | 2 | 1057 | //
// ActionSheetItemView.swift
// CustomSheet
//
// Created by wuguanyu on 16/9/23.
// Copyright © 2016年 wuguanyu. All rights reserved.
//
import UIKit
class ActionSheetItemView: UIView {
lazy var titleLabel: UILabel = {
let aLabel = UILabel()
aLabel.textAlignment = .center
aLabel.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
self.addSubview(aLabel)
return aLabel
}()
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.setting()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setting()
}
init() {
super.init(frame: CGRect.zero)
self.setting()
}
func setting() {
self.clipsToBounds = true
}
func setStyle(_ item: ActionSheetItemModel) {
backgroundColor = item.backGroundColor
titleLabel.text = item.title
titleLabel.textColor = item.fontColor
titleLabel.font = item.font
}
}
| mit | 73f290309a017aa82d63db114ab06dd5 | 20.958333 | 103 | 0.608159 | 3.977358 | false | false | false | false |
Flying-Osterich/Counter | Counter/Counter/CounterController.swift | 1 | 1512 | //
// CounterController.swift
// Counter
//
// Created by Justin.Dombecki on 12/10/15.
// Copyright © 2015 Justin.Dombecki. All rights reserved.
//
import UIKit
class CounterController : UIViewController {
@IBOutlet weak var column : UIView!
@IBOutlet weak var display : UILabel!
@IBOutlet weak var toggle : UIButton!
func reset () {
counter = defaultCounter
column.hidden = true
}
var defaultCounter : Int { get { return 0 } }
var _counter : Int = 0
var counter : Int {
get {
return _counter
}
set (newVal) {
_counter = newVal
display.text = "\(_counter)"
}
}
func reduceCounterBy(value: Int) {
counter -= value
}
func increaseCounterBy(value: Int) {
counter += value
}
@IBAction func counterMinusButtonTapped(sender: AnyObject) {
reduceCounterBy(1)
}
@IBAction func counterPlusButtonTapped(sender: AnyObject) {
increaseCounterBy(1)
}
@IBOutlet weak var plusCounterButton: UIButton!
@IBOutlet weak var minusCounterButton: UIButton!
var isDisplayed : Bool { get { return column.hidden == false } }
func toggleDisplay() {
column.hidden = !column.hidden
}
@IBAction func toggleTapped(sender: AnyObject) {
toggleDisplay()
}
override func viewDidLoad() {
super.viewDidLoad()
reset()
}
} | mit | 826d2aa48aa98d42382bf375b2260e83 | 20.6 | 68 | 0.578425 | 4.48368 | false | false | false | false |
smartystreets/smartystreets-ios-sdk | Tests/SmartyStreetsTests/Mocks/MockStatusCodeSender.swift | 1 | 747 | import Foundation
@testable import SmartyStreets
class MockStatusCodeSender: StatusCodeSender {
var statusCode:Int
var payload:Data
init(statusCode:Int) {
self.statusCode = statusCode
self.payload = Data()
super.init(inner: SmartySender())
}
init(statusCode:Int, payload: String) {
self.statusCode = statusCode
self.payload = payload.data(using: .utf8)!
super.init(inner: SmartySender())
}
override func sendRequest(request: SmartyRequest, error: inout NSError!) -> SmartyResponse! {
if self.statusCode == 0 {
return nil
}
return SmartyResponse(statusCode: self.statusCode, payload: self.payload)
}
}
| apache-2.0 | a9b46c7668003a70f02ef714f49f1982 | 25.678571 | 97 | 0.627845 | 4.446429 | false | false | false | false |
1yvT0s/Nuke | Nuke/Source/Core/ImageManaging.swift | 5 | 1042 | // The MIT License (MIT)
//
// Copyright (c) 2015 Alexander Grebenyuk (github.com/kean).
import Foundation
// MARK: - ImageManaging
public protocol ImageManaging {
func taskWithRequest(request: ImageRequest) -> ImageTask
func invalidateAndCancel()
func removeAllCachedImages()
}
// MARK: - ImagePreheating
public protocol ImagePreheating {
func startPreheatingImages(requests: [ImageRequest])
func stopPreheatingImages(requests: [ImageRequest])
func stopPreheatingImages()
}
// MARK: - ImageManaging (Convenience)
public extension ImageManaging {
func taskWithURL(URL: NSURL, completion: ImageTaskCompletion? = nil) -> ImageTask {
let task = self.taskWithURL(URL)
if completion != nil { task.completion(completion!) }
return task
}
func taskWithRequest(request: ImageRequest, completion: ImageTaskCompletion? = nil) -> ImageTask {
let task = self.taskWithRequest(request)
if completion != nil { task.completion(completion!) }
return task
}
}
| mit | 2b87b3672c1d0e9681d3e93322492764 | 27.162162 | 102 | 0.702495 | 4.570175 | false | false | false | false |
allbto/WayThere | ios/WayThere/WayThere/Classes/Models/CoreData/Coordinates.swift | 2 | 560 | //
// CD_Coordinates.swift
//
//
// Created by Allan BARBATO on 5/18/15.
//
//
import Foundation
import SwiftyJSON
import CoreData
public typealias SimpleCoordinates = (latitude: Double, longitude: Double)
@objc(Coordinates)
public class Coordinates: AModel {
@NSManaged public var latitude: NSNumber?
@NSManaged public var longitude: NSNumber?
public override func fromJson(json: JSON)
{
if let lat = json["lat"].double, lon = json["lon"].double {
latitude = lat
longitude = lon
}
}
}
| mit | fc38f536df3099446fe00cb178084cfa | 18.310345 | 74 | 0.641071 | 3.971631 | false | false | false | false |
jl322137/JLPlaceholderTextView | JLPlaceholderTextView/JLPlaceholderTextView/JLPlaceholderTextView.swift | 1 | 2328 | //
// JLPlaceholderTextView.swift
// JLPlaceholderTextView
//
// Created by Aimy on 15/2/25.
// Copyright (c) 2015年 Aimy. All rights reserved.
//
import UIKit
@IBDesignable
class JLPlaceholderTextView: UITextView {
override func prepareForInterfaceBuilder() {
awakeFromNib()
}
let label: UILabel
required init(coder aDecoder: NSCoder) {
label = UILabel()
super.init(coder: aDecoder)
let string: NSString = placeholder
placeholder = string
label.font = UIFont.systemFontOfSize(placeholderFontSize)
label.text = placeholder
label.textColor = placeholderFontColor
label.hidden = true
addSubview(label)
NSNotificationCenter.defaultCenter().addObserverForName(UITextViewTextDidChangeNotification, object: self, queue: NSOperationQueue.mainQueue()) { (notification) -> Void in
let string: NSString = self.text
if (string.length > 0) {
self.label.hidden = true;
}
else {
self.label.hidden = false;
}
}
}
@IBInspectable var placeholder: NSString = "a placeholdera placeholdera placeholdera placeholdera placeholdera placeholdera placeholder" {
didSet {
label.text = placeholder
let string: NSString = label.text!
let s: CGSize = CGSize(width: self.bounds.size.width, height: 0)
var size: CGSize = string.boundingRectWithSize(s, options:OCUtils.stringDrawingOptions(), attributes:self.font.fontDescriptor().fontAttributes(), context: nil).size
self.label.frame = CGRect(origin: CGPoint(x: 6, y: 6), size: size)
}
}
@IBInspectable var placeholderFontSize: CGFloat = 14.0 {
didSet {
label.font = UIFont.systemFontOfSize(placeholderFontSize)
}
}
@IBInspectable var placeholderFontColor: UIColor = UIColor.lightGrayColor() {
didSet {
label.textColor = placeholderFontColor
}
}
override func layoutSubviews() {
super.layoutSubviews()
let string: NSString = placeholder
placeholder = string
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
| mit | 2e16b46868f7498c4b346b4eab17b597 | 30.013333 | 179 | 0.622528 | 5.089716 | false | false | false | false |
cheeyi/ProjectSora | Pods/PKHUD/PKHUD/PKHUDTextView.swift | 4 | 1176 | //
// PKHUDTextView.swift
// PKHUD
//
// Created by Philip Kluz on 6/12/15.
// Copyright (c) 2015 NSExceptional. All rights reserved.
//
import UIKit
/// PKHUDTextView provides a wide, three line text view, which you can use to display information.
public class PKHUDTextView: PKHUDWideBaseView {
public init(text: String?) {
super.init()
commonInit(text)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit("")
}
func commonInit(text: String?) {
titleLabel.text = text
addSubview(titleLabel)
}
public override func layoutSubviews() {
super.layoutSubviews()
let padding: CGFloat = 10.0
titleLabel.frame = CGRectInset(bounds, padding, padding)
}
public let titleLabel: UILabel = {
let label = UILabel()
label.textAlignment = .Center
label.font = UIFont.boldSystemFontOfSize(17.0)
label.textColor = UIColor.blackColor().colorWithAlphaComponent(0.85)
label.adjustsFontSizeToFitWidth = true
label.numberOfLines = 3
return label
}()
}
| mit | e17c69a8ee132e41b8f31407d0e9bfe2 | 25.133333 | 98 | 0.627551 | 4.648221 | false | false | false | false |
146BC/RomeBuild | RomeBuild/Commands/BuildCommand.swift | 1 | 2624 | import Foundation
import RomeKit
struct BuildCommand {
func build(platforms: String?) {
if !Cartfile().exists() {
Carthage(["update", "--no-build", "--no-checkout"])
}
var dependenciesToBuild = [String:String]()
let dependencies = Cartfile().load()
for (name, revision) in dependencies {
print(name, revision)
if let asset = Rome().getLatestByRevison(name, revision: revision) {
self.downloadAndExtractAsset(asset)
print("Asset extracted to Carthage directory")
print("")
} else {
dependenciesToBuild[name] = revision
}
}
let dependenciesToBuildArray = Array(dependenciesToBuild.keys.map { $0 })
if dependenciesToBuildArray.count > 0 {
var checkoutCommand = ["checkout"]
checkoutCommand.appendContentsOf(dependenciesToBuildArray)
Carthage(checkoutCommand)
var buildCommand = ["build"]
if let selectedPlatforms = platforms {
buildCommand.append("--platform")
buildCommand.append(selectedPlatforms)
}
buildCommand.appendContentsOf(dependenciesToBuildArray)
Carthage(buildCommand)
}
print("Build complete")
}
private func downloadAndExtractAsset(asset: Asset) {
if let serverUrl = Environment().downloadServer() {
let downloadUrl = "\(serverUrl)\(asset.name!)/\(asset.revision!)/\(asset.id!).\(asset.file_extension!)"
print("Downloading asset from:", downloadUrl)
do
{
let data = try NSData(contentsOfURL: NSURL(string: downloadUrl)!, options: NSDataReadingOptions())
let filePath = "\(Environment().currentDirectory()!)/Carthage/tmp/"
try NSFileManager.defaultManager().createDirectoryAtPath(filePath, withIntermediateDirectories: true, attributes: nil)
let zipFile = "\(filePath)\(asset.id!).zip"
try data.writeToFile(zipFile, options: NSDataWritingOptions.DataWritingAtomic)
Unzip(zipFile, destination: Environment().currentDirectory()!)
try NSFileManager.defaultManager().removeItemAtPath(zipFile)
} catch {
print(error)
}
} else {
print("Error fetching download server URL")
}
}
} | mit | dd3dbb2c7a4ff3ae48aa991117b7c0cf | 34.958904 | 134 | 0.556021 | 5.831111 | false | false | false | false |
ImaginarySenseHackatons/TrolleySense | Software/PublicAppiOS/Carthage/Checkouts/MapboxDirections.swift/MapboxDirections/MBRouteOptions.swift | 2 | 22155 | /**
A `RouteShapeFormat` indicates the format of a route’s shape in the raw HTTP response.
*/
@objc(MBRouteShapeFormat)
public enum RouteShapeFormat: UInt, CustomStringConvertible {
/**
The route’s shape is delivered in [GeoJSON](http://geojson.org/) format.
This standard format is human-readable and can be parsed straightforwardly, but it is far more verbose than `polyline`.
*/
case geoJSON
/**
The route’s shape is delivered in [encoded polyline algorithm](https://developers.google.com/maps/documentation/utilities/polylinealgorithm) format.
This machine-readable format is considerably more compact than `geoJSON`.
*/
case polyline
public init?(description: String) {
let format: RouteShapeFormat
switch description {
case "geojson":
format = .geoJSON
case "polyline":
format = .polyline
default:
return nil
}
self.init(rawValue: format.rawValue)
}
public var description: String {
switch self {
case .geoJSON:
return "geojson"
case .polyline:
return "polyline"
}
}
}
/**
A `RouteShapeResolution` indicates the level of detail in a route’s shape, or whether the shape is present at all.
*/
@objc(MBRouteShapeResolution)
public enum RouteShapeResolution: UInt, CustomStringConvertible {
/**
The route’s shape is omitted.
Specify this resolution if you do not intend to show the route line to the user or analyze the route line in any way.
*/
case none
/**
The route’s shape is simplified.
This resolution considerably reduces the size of the response. The resulting shape is suitable for display at a low zoom level, but it lacks the detail necessary for focusing on individual segments of the route.
*/
case low
/**
The route’s shape is as detailed as possible.
The resulting shape is equivalent to concatenating the shapes of all the route’s consitituent steps. You can focus on individual segments of this route while faithfully representing the path of the route. If you only intend to show a route overview and do not need to analyze the route line in any way, consider specifying `low` instead to considerably reduce the size of the response.
*/
case full
public init?(description: String) {
let granularity: RouteShapeResolution
switch description {
case "false":
granularity = .none
case "simplified":
granularity = .low
case "full":
granularity = .full
default:
return nil
}
self.init(rawValue: granularity.rawValue)
}
public var description: String {
switch self {
case .none:
return "false"
case .low:
return "simplified"
case .full:
return "full"
}
}
}
/**
A `RouteOptions` object is a structure that specifies the criteria for results returned by the Mapbox Directions API.
Pass an instance of this class into the `Directions.calculate(_:completionHandler:)` method.
*/
@objc(MBRouteOptions)
open class RouteOptions: NSObject, NSSecureCoding {
// MARK: Creating a Route Options Object
/**
Initializes a route options object for routes between the given waypoints and an optional profile identifier.
- parameter waypoints: An array of `Waypoint` objects representing locations that the route should visit in chronological order. The array should contain at least two waypoints (the source and destination) and at most 25 waypoints. (Some profiles, such as `MBDirectionsProfileIdentifierAutomobileAvoidingTraffic`, [may have lower limits](https://www.mapbox.com/api-documentation/#directions).)
- parameter profileIdentifier: A string specifying the primary mode of transportation for the routes. This parameter, if set, should be set to `MBDirectionsProfileIdentifierAutomobile`, `MBDirectionsProfileIdentifierAutomobileAvoidingTraffic`, `MBDirectionsProfileIdentifierCycling`, or `MBDirectionsProfileIdentifierWalking`. `MBDirectionsProfileIdentifierAutomobile` is used by default.
*/
public init(waypoints: [Waypoint], profileIdentifier: MBDirectionsProfileIdentifier? = nil) {
assert(waypoints.count >= 2, "A route requires at least a source and destination.")
assert(waypoints.count <= 25, "A route may not have more than 25 waypoints.")
self.waypoints = waypoints
self.profileIdentifier = profileIdentifier ?? .automobile
self.allowsUTurnAtWaypoint = ![MBDirectionsProfileIdentifier.automobile.rawValue, MBDirectionsProfileIdentifier.automobileAvoidingTraffic.rawValue].contains(self.profileIdentifier.rawValue)
}
/**
Initializes a route options object for routes between the given locations and an optional profile identifier.
- note: This initializer is intended for `CLLocation` objects created using the `CLLocation.init(latitude:longitude:)` initializer. If you intend to use a `CLLocation` object obtained from a `CLLocationManager` object, consider increasing the `horizontalAccuracy` or set it to a negative value to avoid overfitting, since the `Waypoint` class’s `coordinateAccuracy` property represents the maximum allowed deviation from the waypoint.
- parameter locations: An array of `CLLocation` objects representing locations that the route should visit in chronological order. The array should contain at least two locations (the source and destination) and at most 25 locations. Each location object is converted into a `Waypoint` object. This class respects the `CLLocation` class’s `coordinate` and `horizontalAccuracy` properties, converting them into the `Waypoint` class’s `coordinate` and `coordinateAccuracy` properties, respectively.
- parameter profileIdentifier: A string specifying the primary mode of transportation for the routes. This parameter, if set, should be set to `MBDirectionsProfileIdentifierAutomobile`, `MBDirectionsProfileIdentifierAutomobileAvoidingTraffic`, `MBDirectionsProfileIdentifierCycling`, or `MBDirectionsProfileIdentifierWalking`. `MBDirectionsProfileIdentifierAutomobile` is used by default.
*/
public convenience init(locations: [CLLocation], profileIdentifier: MBDirectionsProfileIdentifier? = nil) {
let waypoints = locations.map { Waypoint(location: $0) }
self.init(waypoints: waypoints, profileIdentifier: profileIdentifier)
}
/**
Initializes a route options object for routes between the given geographic coordinates and an optional profile identifier.
- parameter coordinates: An array of geographic coordinates representing locations that the route should visit in chronological order. The array should contain at least two locations (the source and destination) and at most 25 locations. Each coordinate is converted into a `Waypoint` object.
- parameter profileIdentifier: A string specifying the primary mode of transportation for the routes. This parameter, if set, should be set to `MBDirectionsProfileIdentifierAutomobile`, `MBDirectionsProfileIdentifierAutomobileAvoidingTraffic`, `MBDirectionsProfileIdentifierCycling`, or `MBDirectionsProfileIdentifierWalking`. `MBDirectionsProfileIdentifierAutomobile` is used by default.
*/
public convenience init(coordinates: [CLLocationCoordinate2D], profileIdentifier: MBDirectionsProfileIdentifier? = nil) {
let waypoints = coordinates.map { Waypoint(coordinate: $0) }
self.init(waypoints: waypoints, profileIdentifier: profileIdentifier)
}
public required init?(coder decoder: NSCoder) {
guard let waypoints = decoder.decodeObject(of: [NSArray.self, Waypoint.self], forKey: "waypoints") as? [Waypoint] else {
return nil
}
self.waypoints = waypoints
allowsUTurnAtWaypoint = decoder.decodeBool(forKey: "allowsUTurnAtWaypoint")
guard let profileIdentifier = decoder.decodeObject(of: NSString.self, forKey: "profileIdentifier") as String? else {
return nil
}
self.profileIdentifier = MBDirectionsProfileIdentifier(rawValue: profileIdentifier)
includesAlternativeRoutes = decoder.decodeBool(forKey: "includesAlternativeRoutes")
includesSteps = decoder.decodeBool(forKey: "includesSteps")
guard let shapeFormat = RouteShapeFormat(description: decoder.decodeObject(of: NSString.self, forKey: "shapeFormat") as String? ?? "") else {
return nil
}
self.shapeFormat = shapeFormat
guard let routeShapeResolution = RouteShapeResolution(description: decoder.decodeObject(of: NSString.self, forKey: "routeShapeResolution") as String? ?? "") else {
return nil
}
self.routeShapeResolution = routeShapeResolution
guard let descriptions = decoder.decodeObject(of: NSString.self, forKey: "attributeOptions") as String?,
let attributeOptions = AttributeOptions(descriptions: descriptions.components(separatedBy: ",")) else {
return nil
}
self.attributeOptions = attributeOptions
}
open static var supportsSecureCoding = true
public func encode(with coder: NSCoder) {
coder.encode(waypoints, forKey: "waypoints")
coder.encode(allowsUTurnAtWaypoint, forKey: "allowsUTurnAtWaypoint")
coder.encode(profileIdentifier, forKey: "profileIdentifier")
coder.encode(includesAlternativeRoutes, forKey: "includesAlternativeRoutes")
coder.encode(includesSteps, forKey: "includesSteps")
coder.encode(shapeFormat.description, forKey: "shapeFormat")
coder.encode(routeShapeResolution.description, forKey: "routeShapeResolution")
coder.encode(attributeOptions.description, forKey: "attributeOptions")
}
// MARK: Specifying the Path of the Route
/**
An array of `Waypoint` objects representing locations that the route should visit in chronological order.
A waypoint object indicates a location to visit, as well as an optional heading from which to approach the location.
The array should contain at least two waypoints (the source and destination) and at most 25 waypoints.
*/
open var waypoints: [Waypoint]
/**
A Boolean value that indicates whether a returned route may require a point U-turn at an intermediate waypoint.
If the value of this property is `true`, a returned route may require an immediate U-turn at an intermediate waypoint. At an intermediate waypoint, if the value of this property is `false`, each returned route may continue straight ahead or turn to either side but may not U-turn. This property has no effect if only two waypoints are specified.
Set this property to `true` if you expect the user to traverse each leg of the trip separately. For example, it would be quite easy for the user to effectively “U-turn” at a waypoint if the user first parks the car and patronizes a restaurant there before embarking on the next leg of the trip. Set this property to `false` if you expect the user to proceed to the next waypoint immediately upon arrival. For example, if the user only needs to drop off a passenger or package at the waypoint before continuing, it would be inconvenient to perform a U-turn at that location.
The default value of this property is `false` when the profile identifier is `MBDirectionsProfileIdentifierAutomobile` or `MBDirectionsProfileIdentifierAutomobileAvoidingTraffic` and `true` otherwise.
*/
open var allowsUTurnAtWaypoint: Bool
// MARK: Specifying Transportation Options
/**
A string specifying the primary mode of transportation for the routes.
This property should be set to `MBDirectionsProfileIdentifierAutomobile`, `MBDirectionsProfileIdentifierAutomobileAvoidingTraffic`, `MBDirectionsProfileIdentifierCycling`, or `MBDirectionsProfileIdentifierWalking`. The default value of this property is `MBDirectionsProfileIdentifierAutomobile`, which specifies driving directions.
*/
open var profileIdentifier: MBDirectionsProfileIdentifier
// MARK: Specifying the Response Format
/**
A Boolean value indicating whether alternative routes should be included in the response.
If the value of this property is `false`, the server only calculates a single route that visits each of the waypoints. If the value of this property is `true`, the server attempts to find additional reasonable routes that visit the waypoints. Regardless, multiple routes are only returned if it is possible to visit the waypoints by a different route without significantly increasing the distance or travel time. The alternative routes may partially overlap with the preferred route, especially if intermediate waypoints are specified.
Alternative routes may take longer to calculate and make the response significantly larger, so only request alternative routes if you intend to display them to the user or let the user choose them over the preferred route. For example, do not request alternative routes if you only want to know the distance or estimated travel time to a destination.
The default value of this property is `false`.
*/
open var includesAlternativeRoutes = false
/**
A Boolean value indicating whether `MBRouteStep` objects should be included in the response.
If the value of this property is `true`, the returned route contains turn-by-turn instructions. Each returned `MBRoute` object contains one or more `MBRouteLeg` object that in turn contains one or more `MBRouteStep` objects. On the other hand, if the value of this property is `false`, the `MBRouteLeg` objects contain no `MBRouteStep` objects.
If you only want to know the distance or estimated travel time to a destination, set this property to `false` to minimize the size of the response and the time it takes to calculate the response. If you need to display turn-by-turn instructions, set this property to `true`.
The default value of this property is `false`.
*/
open var includesSteps = false
/**
Format of the data from which the shapes of the returned route and its steps are derived.
This property has no effect on the returned shape objects, although the choice of format can significantly affect the size of the underlying HTTP response.
The default value of this property is `polyline`.
*/
open var shapeFormat = RouteShapeFormat.polyline
/**
Resolution of the shape of the returned route.
This property has no effect on the shape of the returned route’s steps.
The default value of this property is `low`, specifying a low-resolution route shape.
*/
open var routeShapeResolution = RouteShapeResolution.low
/**
AttributeOptions for the route. Any combination of `AttributeOptions` can be specified.
By default, no attribute options are specified. It is recommended that `routeShapeResolution` be set to `.full`.
*/
open var attributeOptions: AttributeOptions = []
// MARK: Constructing the Request URL
/**
The path of the request URL, not including the hostname or any parameters.
*/
internal var path: String {
assert(!queries.isEmpty, "No query")
let queryComponent = queries.joined(separator: ";")
return "directions/v5/\(profileIdentifier.rawValue)/\(queryComponent).json"
}
/**
An array of geocoding query strings to include in the request URL.
*/
internal var queries: [String] {
return waypoints.map { "\($0.coordinate.longitude),\($0.coordinate.latitude)" }
}
/**
An array of URL parameters to include in the request URL.
*/
internal var params: [URLQueryItem] {
var params: [URLQueryItem] = [
URLQueryItem(name: "alternatives", value: String(includesAlternativeRoutes)),
URLQueryItem(name: "geometries", value: String(describing: shapeFormat)),
URLQueryItem(name: "overview", value: String(describing: routeShapeResolution)),
URLQueryItem(name: "steps", value: String(includesSteps)),
URLQueryItem(name: "continue_straight", value: String(!allowsUTurnAtWaypoint)),
]
// Include headings and heading accuracies if any waypoint has a nonnegative heading.
if !waypoints.filter({ $0.heading >= 0 }).isEmpty {
let headings = waypoints.map { $0.headingDescription }.joined(separator: ";")
params.append(URLQueryItem(name: "bearings", value: headings))
}
// Include location accuracies if any waypoint has a nonnegative coordinate accuracy.
if !waypoints.filter({ $0.coordinateAccuracy >= 0 }).isEmpty {
let accuracies = waypoints.map {
$0.coordinateAccuracy >= 0 ? String($0.coordinateAccuracy) : "unlimited"
}.joined(separator: ";")
params.append(URLQueryItem(name: "radiuses", value: accuracies))
}
if !attributeOptions.isEmpty {
let attributesStrings = String(describing:attributeOptions)
params.append(URLQueryItem(name: "annotations", value: attributesStrings))
}
return params
}
/**
Returns response objects that represent the given JSON dictionary data.
- parameter json: The API response in JSON dictionary format.
- returns: A tuple containing an array of waypoints and an array of routes.
*/
internal func response(from json: JSONDictionary) -> ([Waypoint]?, [Route]?) {
var namedWaypoints: [Waypoint]
if let waypoints = (json["waypoints"] as? [JSONDictionary]) {
namedWaypoints = zip(waypoints, self.waypoints).map { (json, waypoint) -> Waypoint in
let location = json["location"] as! [Double]
let coordinate = CLLocationCoordinate2D(geoJSON: location)
return Waypoint(coordinate: coordinate, name: waypoint.name ?? json["name"] as? String)
}
} else {
namedWaypoints = self.waypoints
}
let routes = (json["routes"] as? [JSONDictionary])?.map {
Route(json: $0, waypoints: namedWaypoints, routeOptions: self)
}
return (waypoints, routes)
}
}
// MARK: Support for Directions API v4
/**
A `RouteShapeFormat` indicates the format of a route’s shape in the raw HTTP response.
*/
@objc(MBInstructionFormat)
public enum InstructionFormat: UInt, CustomStringConvertible {
/**
The route steps’ instructions are delivered in plain text format.
*/
case text
/**
The route steps’ instructions are delivered in HTML format.
Key phrases are boldfaced.
*/
case html
public init?(description: String) {
let format: InstructionFormat
switch description {
case "text":
format = .text
case "html":
format = .html
default:
return nil
}
self.init(rawValue: format.rawValue)
}
public var description: String {
switch self {
case .text:
return "text"
case .html:
return "html"
}
}
}
/**
A `RouteOptionsV4` object is a structure that specifies the criteria for results returned by the Mapbox Directions API v4.
Pass an instance of this class into the `Directions.calculate(_:completionHandler:)` method.
*/
@objc(MBRouteOptionsV4)
open class RouteOptionsV4: RouteOptions {
// MARK: Specifying the Response Format
/**
The format of the returned route steps’ instructions.
By default, the value of this property is `text`, specifying plain text instructions.
*/
open var instructionFormat: InstructionFormat = .text
/**
A Boolean value indicating whether the returned routes and their route steps should include any geographic coordinate data.
If the value of this property is `true`, the returned routes and their route steps include coordinates; if the value of this property is `false, they do not.
The default value of this property is `true`.
*/
open var includesShapes: Bool = true
override var path: String {
assert(!queries.isEmpty, "No query")
let profileIdentifier = self.profileIdentifier.rawValue.replacingOccurrences(of: "/", with: ".")
let queryComponent = queries.joined(separator: ";")
return "v4/directions/\(profileIdentifier)/\(queryComponent).json"
}
override var params: [URLQueryItem] {
return [
URLQueryItem(name: "alternatives", value: String(includesAlternativeRoutes)),
URLQueryItem(name: "instructions", value: String(describing: instructionFormat)),
URLQueryItem(name: "geometry", value: includesShapes ? String(describing: shapeFormat) : String(false)),
URLQueryItem(name: "steps", value: String(includesSteps)),
]
}
override func response(from json: JSONDictionary) -> ([Waypoint]?, [Route]?) {
let sourceWaypoint = Waypoint(geoJSON: json["origin"] as! JSONDictionary)!
let destinationWaypoint = Waypoint(geoJSON: json["destination"] as! JSONDictionary)!
let intermediateWaypoints = (json["waypoints"] as! [JSONDictionary]).flatMap { Waypoint(geoJSON: $0) }
let waypoints = [sourceWaypoint] + intermediateWaypoints + [destinationWaypoint]
let routes = (json["routes"] as? [JSONDictionary])?.map {
RouteV4(json: $0, waypoints: waypoints, routeOptions: self)
}
return (waypoints, routes)
}
}
| apache-2.0 | 507dded11259595ffcaabb899b66b1b6 | 49.5 | 578 | 0.6975 | 4.988498 | false | false | false | false |
nathawes/swift | test/Sema/enum_conformance_synthesis.swift | 3 | 12183 | // RUN: %target-swift-frontend -typecheck -verify -primary-file %s %S/Inputs/enum_conformance_synthesis_other.swift -verify-ignore-unknown -swift-version 4
var hasher = Hasher()
enum Foo: CaseIterable {
case A, B
}
func foo() {
if Foo.A == .B { }
var _: Int = Foo.A.hashValue
Foo.A.hash(into: &hasher)
_ = Foo.allCases
Foo.A == Foo.B // expected-warning {{result of operator '==' is unused}}
}
enum Generic<T>: CaseIterable {
case A, B
static func method() -> Int {
// Test synthesis of == without any member lookup being done
if A == B { }
return Generic.A.hashValue
}
}
func generic() {
if Generic<Foo>.A == .B { }
var _: Int = Generic<Foo>.A.hashValue
Generic<Foo>.A.hash(into: &hasher)
_ = Generic<Foo>.allCases
}
func localEnum() -> Bool {
enum Local {
case A, B
}
return Local.A == .B
}
enum CustomHashable {
case A, B
func hash(into hasher: inout Hasher) {}
}
func ==(x: CustomHashable, y: CustomHashable) -> Bool {
return true
}
func customHashable() {
if CustomHashable.A == .B { }
var _: Int = CustomHashable.A.hashValue
CustomHashable.A.hash(into: &hasher)
}
// We still synthesize conforming overloads of '==' and 'hashValue' if
// explicit definitions don't satisfy the protocol requirements. Probably
// not what we actually want.
enum InvalidCustomHashable {
case A, B
var hashValue: String { return "" } // expected-error {{invalid redeclaration of synthesized implementation for protocol requirement 'hashValue'}}
}
func ==(x: InvalidCustomHashable, y: InvalidCustomHashable) -> String {
return ""
}
func invalidCustomHashable() {
if InvalidCustomHashable.A == .B { }
var s: String = InvalidCustomHashable.A == .B
s = InvalidCustomHashable.A.hashValue
_ = s
var _: Int = InvalidCustomHashable.A.hashValue
InvalidCustomHashable.A.hash(into: &hasher)
}
// Check use of an enum's synthesized members before the enum is actually declared.
struct UseEnumBeforeDeclaration {
let eqValue = EnumToUseBeforeDeclaration.A == .A
let hashValue = EnumToUseBeforeDeclaration.A.hashValue
}
enum EnumToUseBeforeDeclaration {
case A
}
func getFromOtherFile() -> AlsoFromOtherFile { return .A }
func overloadFromOtherFile() -> YetAnotherFromOtherFile { return .A }
func overloadFromOtherFile() -> Bool { return false }
func useEnumBeforeDeclaration() {
// Check enums from another file in the same module.
if FromOtherFile.A == .A {}
let _: Int = FromOtherFile.A.hashValue
if .A == getFromOtherFile() {}
if .A == overloadFromOtherFile() {}
}
// Complex enums are not automatically Equatable, Hashable, or CaseIterable.
enum Complex {
case A(Int)
case B
}
func complex() {
if Complex.A(1) == .B { } // expected-error{{cannot convert value of type 'Complex' to expected argument type 'CustomHashable'}}
}
// Enums with equatable payloads are equatable if they explicitly conform.
enum EnumWithEquatablePayload: Equatable {
case A(Int)
case B(String, Int)
case C
}
func enumWithEquatablePayload() {
if EnumWithEquatablePayload.A(1) == .B("x", 1) { }
if EnumWithEquatablePayload.A(1) == .C { }
if EnumWithEquatablePayload.B("x", 1) == .C { }
}
// Enums with hashable payloads are hashable if they explicitly conform.
enum EnumWithHashablePayload: Hashable {
case A(Int)
case B(String, Int)
case C
}
func enumWithHashablePayload() {
_ = EnumWithHashablePayload.A(1).hashValue
_ = EnumWithHashablePayload.B("x", 1).hashValue
_ = EnumWithHashablePayload.C.hashValue
EnumWithHashablePayload.A(1).hash(into: &hasher)
EnumWithHashablePayload.B("x", 1).hash(into: &hasher)
EnumWithHashablePayload.C.hash(into: &hasher)
// ...and they should also inherit equatability from Hashable.
if EnumWithHashablePayload.A(1) == .B("x", 1) { }
if EnumWithHashablePayload.A(1) == .C { }
if EnumWithHashablePayload.B("x", 1) == .C { }
}
// Enums with non-hashable payloads don't derive conformance.
struct NotHashable {}
enum EnumWithNonHashablePayload: Hashable { // expected-error 2 {{does not conform}}
case A(NotHashable) //expected-note {{associated value type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'EnumWithNonHashablePayload' to 'Hashable'}}
// expected-note@-1 {{associated value type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'EnumWithNonHashablePayload' to 'Equatable'}}
}
// Enums should be able to derive conformances based on the conformances of
// their generic arguments.
enum GenericHashable<T: Hashable>: Hashable {
case A(T)
case B
}
func genericHashable() {
if GenericHashable<String>.A("a") == .B { }
var _: Int = GenericHashable<String>.A("a").hashValue
}
// But it should be an error if the generic argument doesn't have the necessary
// constraints to satisfy the conditions for derivation.
enum GenericNotHashable<T: Equatable>: Hashable { // expected-error 2 {{does not conform to protocol 'Hashable'}}
case A(T) //expected-note 2 {{associated value type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'GenericNotHashable<T>' to 'Hashable'}}
case B
}
func genericNotHashable() {
if GenericNotHashable<String>.A("a") == .B { }
let _: Int = GenericNotHashable<String>.A("a").hashValue // No error. hashValue is always synthesized, even if Hashable derivation fails
GenericNotHashable<String>.A("a").hash(into: &hasher) // expected-error {{value of type 'GenericNotHashable<String>' has no member 'hash'}}
}
// An enum with no cases should also derive conformance.
enum NoCases: Hashable {}
// rdar://19773050
private enum Bar<T> {
case E(Unknown<T>) // expected-error {{cannot find type 'Unknown' in scope}}
mutating func value() -> T {
switch self {
// FIXME: Should diagnose here that '.' needs to be inserted, but E has an ErrorType at this point
case E(let x):
return x.value
}
}
}
// Equatable extension -- rdar://20981254
enum Instrument {
case Piano
case Violin
case Guitar
}
extension Instrument : Equatable {}
extension Instrument : CaseIterable {}
enum UnusedGeneric<T> {
case a, b, c
}
extension UnusedGeneric : CaseIterable {}
// Explicit conformance should work too
public enum Medicine {
case Antibiotic
case Antihistamine
}
extension Medicine : Equatable {}
public func ==(lhs: Medicine, rhs: Medicine) -> Bool {
return true
}
// No explicit conformance; but it can be derived, for the same-file cases.
enum Complex2 {
case A(Int)
case B
}
extension Complex2 : Hashable {}
extension Complex2 : CaseIterable {} // expected-error {{type 'Complex2' does not conform to protocol 'CaseIterable'}}
extension FromOtherFile: CaseIterable {} // expected-error {{extension outside of file declaring enum 'FromOtherFile' prevents automatic synthesis of 'allCases' for protocol 'CaseIterable'}}
extension CaseIterableAcrossFiles: CaseIterable {
public static var allCases: [CaseIterableAcrossFiles] {
return [ .A ]
}
}
// No explicit conformance and it cannot be derived.
enum NotExplicitlyHashableAndCannotDerive {
case A(NotHashable) //expected-note {{associated value type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Hashable'}}
// expected-note@-1 {{associated value type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Equatable'}}
}
extension NotExplicitlyHashableAndCannotDerive : Hashable {} // expected-error 2 {{does not conform}}
extension NotExplicitlyHashableAndCannotDerive : CaseIterable {} // expected-error {{does not conform}}
// Verify that conformance (albeit manually implemented) can still be added to
// a type in a different file.
extension OtherFileNonconforming: Hashable {
static func ==(lhs: OtherFileNonconforming, rhs: OtherFileNonconforming) -> Bool {
return true
}
func hash(into hasher: inout Hasher) {}
}
// ...but synthesis in a type defined in another file doesn't work yet.
extension YetOtherFileNonconforming: Equatable {} // expected-error {{extension outside of file declaring enum 'YetOtherFileNonconforming' prevents automatic synthesis of '==' for protocol 'Equatable'}}
extension YetOtherFileNonconforming: CaseIterable {} // expected-error {{does not conform}}
// Verify that an indirect enum doesn't emit any errors as long as its "leaves"
// are conformant.
enum StringBinaryTree: Hashable {
indirect case tree(StringBinaryTree, StringBinaryTree)
case leaf(String)
}
// Add some generics to make it more complex.
enum BinaryTree<Element: Hashable>: Hashable {
indirect case tree(BinaryTree, BinaryTree)
case leaf(Element)
}
// Verify mutually indirect enums.
enum MutuallyIndirectA: Hashable {
indirect case b(MutuallyIndirectB)
case data(Int)
}
enum MutuallyIndirectB: Hashable {
indirect case a(MutuallyIndirectA)
case data(Int)
}
// Verify that it works if the enum itself is indirect, rather than the cases.
indirect enum TotallyIndirect: Hashable {
case another(TotallyIndirect)
case end(Int)
}
// Check the use of conditional conformances.
enum ArrayOfEquatables : Equatable {
case only([Int])
}
struct NotEquatable { }
enum ArrayOfNotEquatables : Equatable { // expected-error{{type 'ArrayOfNotEquatables' does not conform to protocol 'Equatable'}}
case only([NotEquatable]) //expected-note {{associated value type '[NotEquatable]' does not conform to protocol 'Equatable', preventing synthesized conformance of 'ArrayOfNotEquatables' to 'Equatable'}}
}
// Conditional conformances should be able to be synthesized
enum GenericDeriveExtension<T> {
case A(T)
}
extension GenericDeriveExtension: Equatable where T: Equatable {}
extension GenericDeriveExtension: Hashable where T: Hashable {}
// Incorrectly/insufficiently conditional shouldn't work
enum BadGenericDeriveExtension<T> {
case A(T) //expected-note {{associated value type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Hashable'}}
//expected-note@-1 {{associated value type 'T' does not conform to protocol 'Equatable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Equatable'}}
}
extension BadGenericDeriveExtension: Equatable {} //
// expected-error@-1 {{type 'BadGenericDeriveExtension<T>' does not conform to protocol 'Equatable'}}
extension BadGenericDeriveExtension: Hashable where T: Equatable {}
// expected-error@-1 {{type 'BadGenericDeriveExtension' does not conform to protocol 'Hashable'}}
// But some cases don't need to be conditional, even if they look similar to the
// above
struct AlwaysHashable<T>: Hashable {}
enum UnusedGenericDeriveExtension<T> {
case A(AlwaysHashable<T>)
}
extension UnusedGenericDeriveExtension: Hashable {}
// Cross-file synthesis is disallowed for conditional cases just as it is for
// non-conditional ones.
extension GenericOtherFileNonconforming: Equatable where T: Equatable {}
// expected-error@-1{{extension outside of file declaring generic enum 'GenericOtherFileNonconforming' prevents automatic synthesis of '==' for protocol 'Equatable'}}
// rdar://problem/41852654
// There is a conformance to Equatable (or at least, one that implies Equatable)
// in the same file as the type, so the synthesis is okay. Both orderings are
// tested, to catch choosing extensions based on the order of the files, etc.
protocol ImplierMain: Equatable {}
enum ImpliedMain: ImplierMain {
case a(Int)
}
extension ImpliedOther: ImplierMain {}
// FIXME: Remove -verify-ignore-unknown.
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '(Foo, Foo) -> Bool'
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '<T> (Generic<T>, Generic<T>) -> Bool'
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '(InvalidCustomHashable, InvalidCustomHashable) -> Bool'
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '(EnumToUseBeforeDeclaration, EnumToUseBeforeDeclaration) -> Bool'
| apache-2.0 | bc3f561e14d8f8081bb9efe85f2ab064 | 34.938053 | 209 | 0.739063 | 4.047508 | false | false | false | false |
xedin/swift | stdlib/public/Darwin/Foundation/DataProtocol.swift | 13 | 12540 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2018 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
//
//===----------------------------------------------------------------------===//
#if os(macOS) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
//===--- DataProtocol -----------------------------------------------------===//
public protocol DataProtocol : RandomAccessCollection where Element == UInt8, SubSequence : DataProtocol {
// FIXME: Remove in favor of opaque type on `regions`.
associatedtype Regions: BidirectionalCollection where Regions.Element : DataProtocol & ContiguousBytes, Regions.Element.SubSequence : ContiguousBytes
/// A `BidirectionalCollection` of `DataProtocol` elements which compose a
/// discontiguous buffer of memory. Each region is a contiguous buffer of
/// bytes.
///
/// The sum of the lengths of the associated regions must equal `self.count`
/// (such that iterating `regions` and iterating `self` produces the same
/// sequence of indices in the same number of index advancements).
var regions: Regions { get }
/// Returns the first found range of the given data buffer.
///
/// A default implementation is given in terms of `self.regions`.
func firstRange<D: DataProtocol, R: RangeExpression>(of: D, in: R) -> Range<Index>? where R.Bound == Index
/// Returns the last found range of the given data buffer.
///
/// A default implementation is given in terms of `self.regions`.
func lastRange<D: DataProtocol, R: RangeExpression>(of: D, in: R) -> Range<Index>? where R.Bound == Index
/// Copies `count` bytes from the start of the buffer to the destination
/// buffer.
///
/// A default implementation is given in terms of `copyBytes(to:from:)`.
@discardableResult
func copyBytes(to: UnsafeMutableRawBufferPointer, count: Int) -> Int
/// Copies `count` bytes from the start of the buffer to the destination
/// buffer.
///
/// A default implementation is given in terms of `copyBytes(to:from:)`.
@discardableResult
func copyBytes<DestinationType>(to: UnsafeMutableBufferPointer<DestinationType>, count: Int) -> Int
/// Copies the bytes from the given range to the destination buffer.
///
/// A default implementation is given in terms of `self.regions`.
@discardableResult
func copyBytes<R: RangeExpression>(to: UnsafeMutableRawBufferPointer, from: R) -> Int where R.Bound == Index
/// Copies the bytes from the given range to the destination buffer.
///
/// A default implementation is given in terms of `self.regions`.
@discardableResult
func copyBytes<DestinationType, R: RangeExpression>(to: UnsafeMutableBufferPointer<DestinationType>, from: R) -> Int where R.Bound == Index
}
//===--- MutableDataProtocol ----------------------------------------------===//
public protocol MutableDataProtocol : DataProtocol, MutableCollection, RangeReplaceableCollection {
/// Replaces the contents of the buffer at the given range with zeroes.
///
/// A default implementation is given in terms of
/// `replaceSubrange(_:with:)`.
mutating func resetBytes<R: RangeExpression>(in range: R) where R.Bound == Index
}
//===--- DataProtocol Extensions ------------------------------------------===//
extension DataProtocol {
public func firstRange<D: DataProtocol>(of data: D) -> Range<Index>? {
return self.firstRange(of: data, in: self.startIndex ..< self.endIndex)
}
public func lastRange<D: DataProtocol>(of data: D) -> Range<Index>? {
return self.lastRange(of: data, in: self.startIndex ..< self.endIndex)
}
@discardableResult
public func copyBytes(to ptr: UnsafeMutableRawBufferPointer) -> Int {
return copyBytes(to: ptr, from: self.startIndex ..< self.endIndex)
}
@discardableResult
public func copyBytes<DestinationType>(to ptr: UnsafeMutableBufferPointer<DestinationType>) -> Int {
return copyBytes(to: ptr, from: self.startIndex ..< self.endIndex)
}
@discardableResult
public func copyBytes(to ptr: UnsafeMutableRawBufferPointer, count: Int) -> Int {
return copyBytes(to: ptr, from: self.startIndex ..< self.index(self.startIndex, offsetBy: count))
}
@discardableResult
public func copyBytes<DestinationType>(to ptr: UnsafeMutableBufferPointer<DestinationType>, count: Int) -> Int {
return copyBytes(to: ptr, from: self.startIndex ..< self.index(self.startIndex, offsetBy: count))
}
@discardableResult
public func copyBytes<R: RangeExpression>(to ptr: UnsafeMutableRawBufferPointer, from range: R) -> Int where R.Bound == Index {
precondition(ptr.baseAddress != nil)
let concreteRange = range.relative(to: self)
let slice = self[concreteRange]
// The type isn't contiguous, so we need to copy one region at a time.
var offset = 0
let rangeCount = distance(from: concreteRange.lowerBound, to: concreteRange.upperBound)
var amountToCopy = Swift.min(ptr.count, rangeCount)
for region in slice.regions {
guard amountToCopy > 0 else {
break
}
region.withUnsafeBytes { buffer in
let offsetPtr = UnsafeMutableRawBufferPointer(rebasing: ptr[offset...])
let buf = UnsafeRawBufferPointer(start: buffer.baseAddress, count: Swift.min(buffer.count, amountToCopy))
offsetPtr.copyMemory(from: buf)
offset += buf.count
amountToCopy -= buf.count
}
}
return offset
}
@discardableResult
public func copyBytes<DestinationType, R: RangeExpression>(to ptr: UnsafeMutableBufferPointer<DestinationType>, from range: R) -> Int where R.Bound == Index {
return self.copyBytes(to: UnsafeMutableRawBufferPointer(start: ptr.baseAddress, count: ptr.count * MemoryLayout<DestinationType>.stride), from: range)
}
public func firstRange<D: DataProtocol, R: RangeExpression>(of data: D, in range: R) -> Range<Index>? where R.Bound == Index {
let r = range.relative(to: self)
let rangeCount = distance(from: r.lowerBound, to: r.upperBound)
if rangeCount < data.count {
return nil
}
var haystackIndex = r.lowerBound
let haystackEnd = index(r.upperBound, offsetBy: -data.count)
while haystackIndex < haystackEnd {
var compareIndex = haystackIndex
var needleIndex = data.startIndex
let needleEnd = data.endIndex
var matched = true
while compareIndex < haystackEnd && needleIndex < needleEnd {
if self[compareIndex] != data[needleIndex] {
matched = false
break
}
needleIndex = data.index(after: needleIndex)
compareIndex = index(after: compareIndex)
}
if matched {
return haystackIndex..<compareIndex
}
haystackIndex = index(after: haystackIndex)
}
return nil
}
public func lastRange<D: DataProtocol, R: RangeExpression>(of data: D, in range: R) -> Range<Index>? where R.Bound == Index {
let r = range.relative(to: self)
let rangeCount = distance(from: r.lowerBound, to: r.upperBound)
if rangeCount < data.count {
return nil
}
var haystackIndex = r.upperBound
let haystackStart = index(r.lowerBound, offsetBy: data.count)
while haystackIndex > haystackStart {
var compareIndex = haystackIndex
var needleIndex = data.endIndex
let needleStart = data.startIndex
var matched = true
while compareIndex > haystackStart && needleIndex > needleStart {
if self[compareIndex] != data[needleIndex] {
matched = false
break
}
needleIndex = data.index(before: needleIndex)
compareIndex = index(before: compareIndex)
}
if matched {
return compareIndex..<haystackIndex
}
haystackIndex = index(before: haystackIndex)
}
return nil
}
}
extension DataProtocol where Self : ContiguousBytes {
public func copyBytes<DestinationType, R: RangeExpression>(to ptr: UnsafeMutableBufferPointer<DestinationType>, from range: R) where R.Bound == Index {
precondition(ptr.baseAddress != nil)
let concreteRange = range.relative(to: self)
withUnsafeBytes { fullBuffer in
let adv = distance(from: startIndex, to: concreteRange.lowerBound)
let delta = distance(from: concreteRange.lowerBound, to: concreteRange.upperBound)
memcpy(ptr.baseAddress!, fullBuffer.baseAddress?.advanced(by: adv), delta)
}
}
}
//===--- MutableDataProtocol Extensions -----------------------------------===//
extension MutableDataProtocol {
public mutating func resetBytes<R: RangeExpression>(in range: R) where R.Bound == Index {
let r = range.relative(to: self)
let count = distance(from: r.lowerBound, to: r.upperBound)
replaceSubrange(r, with: repeatElement(UInt8(0), count: count))
}
}
//===--- DataProtocol Conditional Conformances ----------------------------===//
extension Slice : DataProtocol where Base : DataProtocol {
public typealias Regions = [Base.Regions.Element.SubSequence]
public var regions: [Base.Regions.Element.SubSequence] {
let sliceLowerBound = startIndex
let sliceUpperBound = endIndex
var regionUpperBound = base.startIndex
return base.regions.compactMap { (region) -> Base.Regions.Element.SubSequence? in
let regionLowerBound = regionUpperBound
regionUpperBound = base.index(regionUpperBound, offsetBy: region.count)
/*
[------ Region ------]
[--- Slice ---] =>
OR
[------ Region ------]
<= [--- Slice ---]
*/
if sliceLowerBound >= regionLowerBound && sliceUpperBound <= regionUpperBound {
let regionRelativeSliceLowerBound = region.index(region.startIndex, offsetBy: base.distance(from: regionLowerBound, to: sliceLowerBound))
let regionRelativeSliceUpperBound = region.index(region.startIndex, offsetBy: base.distance(from: regionLowerBound, to: sliceUpperBound))
return region[regionRelativeSliceLowerBound..<regionRelativeSliceUpperBound]
}
/*
[--- Region ---] =>
[------ Slice ------]
OR
<= [--- Region ---]
[------ Slice ------]
*/
if regionLowerBound >= sliceLowerBound && regionUpperBound <= sliceUpperBound {
return region[region.startIndex..<region.endIndex]
}
/*
[------ Region ------]
[------ Slice ------]
*/
if sliceLowerBound >= regionLowerBound && sliceLowerBound <= regionUpperBound {
let regionRelativeSliceLowerBound = region.index(region.startIndex, offsetBy: base.distance(from: regionLowerBound, to: sliceLowerBound))
return region[regionRelativeSliceLowerBound..<region.endIndex]
}
/*
[------ Region ------]
[------ Slice ------]
*/
if regionLowerBound >= sliceLowerBound && regionLowerBound <= sliceUpperBound {
let regionRelativeSliceUpperBound = region.index(region.startIndex, offsetBy: base.distance(from: regionLowerBound, to: sliceUpperBound))
return region[region.startIndex..<regionRelativeSliceUpperBound]
}
/*
[--- Region ---]
[--- Slice ---]
OR
[--- Region ---]
[--- Slice ---]
*/
return nil
}
}
}
| apache-2.0 | 6af818608cb877b9437f0c73eb9568e3 | 40.939799 | 162 | 0.604944 | 5.09549 | false | false | false | false |
material-components/material-components-ios-codelabs | MDC-103/Swift/Complete/Shrine/Shrine/ApplicationScheme.swift | 1 | 2738 | /*
Copyright 2018-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import MaterialComponents
class ApplicationScheme: NSObject {
private static var singleton = ApplicationScheme()
static var shared: ApplicationScheme {
return singleton
}
override init() {
self.buttonScheme.colorScheme = self.colorScheme
self.buttonScheme.typographyScheme = self.typographyScheme
super.init()
}
public let buttonScheme = MDCButtonScheme()
public let colorScheme: MDCColorScheming = {
let scheme = MDCSemanticColorScheme(defaults: .material201804)
//TODO: Customize our app Colors after this line
scheme.primaryColor =
UIColor(red: 252.0/255.0, green: 184.0/255.0, blue: 171.0/255.0, alpha: 1.0)
scheme.primaryColorVariant =
UIColor(red: 68.0/255.0, green: 44.0/255.0, blue: 46.0/255.0, alpha: 1.0)
scheme.onPrimaryColor =
UIColor(red: 68.0/255.0, green: 44.0/255.0, blue: 46.0/255.0, alpha: 1.0)
scheme.secondaryColor =
UIColor(red: 254.0/255.0, green: 234.0/255.0, blue: 230.0/255.0, alpha: 1.0)
scheme.onSecondaryColor =
UIColor(red: 68.0/255.0, green: 44.0/255.0, blue: 46.0/255.0, alpha: 1.0)
scheme.surfaceColor =
UIColor(red: 255.0/255.0, green: 251.0/255.0, blue: 250.0/255.0, alpha: 1.0)
scheme.onSurfaceColor =
UIColor(red: 68.0/255.0, green: 44.0/255.0, blue: 46.0/255.0, alpha: 1.0)
scheme.backgroundColor =
UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0)
scheme.onBackgroundColor =
UIColor(red: 68.0/255.0, green: 44.0/255.0, blue: 46.0/255.0, alpha: 1.0)
scheme.errorColor =
UIColor(red: 197.0/255.0, green: 3.0/255.0, blue: 43.0/255.0, alpha: 1.0)
return scheme
}()
public let typographyScheme: MDCTypographyScheming = {
let scheme = MDCTypographyScheme()
//TODO: Add our custom fonts after this line
let fontName = "Rubik"
scheme.headline5 = UIFont(name: fontName, size: 24)!
scheme.headline6 = UIFont(name: fontName, size: 20)!
scheme.subtitle1 = UIFont(name: fontName, size: 16)!
scheme.button = UIFont(name: fontName, size: 14)!
return scheme
}()
}
| apache-2.0 | 8c7a495e64b48049f89d6bc49e154f74 | 36.506849 | 85 | 0.695763 | 3.388614 | false | false | false | false |
castillejoale/Bluefruit_LE_Connect_v2_Minimized_UART | bluefruitconnect/Common/InfoModuleManager.swift | 1 | 1509 | //
// InfoModuleManager.swift
// Bluefruit Connect
//
// Created by Antonio García on 18/07/16.
// Copyright © 2016 Adafruit. All rights reserved.
//
import Foundation
class InfoModuleManager: NSObject {
static func parseDescriptorValue(descriptor: CBDescriptor) -> NSData? {
var result: NSData?
let identifier = descriptor.UUID.UUIDString
switch identifier {
case CBUUIDCharacteristicExtendedPropertiesString, CBUUIDClientCharacteristicConfigurationString, CBUUIDServerCharacteristicConfigurationString: // is an NSNumber
// Note: according to the docs this should be an NSNumber, but it seems that is recognized as an NSData. So an NSData check is performed if the NSNumber check fails
if let value = descriptor.value as? NSNumber {
result = value.stringValue.dataUsingEncoding(NSUTF8StringEncoding)
}
else if let value = descriptor.value as? NSData {
result = value
}
case CBUUIDCharacteristicUserDescriptionString: // is an NSString
if let value = descriptor.value as? String {
result = value.dataUsingEncoding(NSUTF8StringEncoding)
}
case CBUUIDCharacteristicFormatString, CBUUIDCharacteristicAggregateFormatString:
result = descriptor.value as? NSData
default:
break
}
return result
}
} | mit | 601c5ed99bdb7f97ea99cfd62e264547 | 34.069767 | 176 | 0.641672 | 5.60223 | false | false | false | false |
jinMaoHuiHui/WhiteBoard | WhiteBoard/WhiteBoard/Canvas/Dot.swift | 1 | 1582 | //
// Dot.swift
// WhiteBoard
//
// Created by jinmao on 2016/12/14.
// Copyright © 2016年 jinmao. All rights reserved.
//
import UIKit
class Dot: Vertex {
override init(location: CGPoint) {
super.init(location: location)
}
override func drawWithContext(_ contenxt: CGContext) {
if let frameSize = size, let fillColor = color{
if let center = location {
let frame = CGRect(x: center.x - frameSize/2.0, y: center.y - frameSize/2.0, width: frameSize, height: frameSize)
contenxt.setFillColor(fillColor.cgColor)
contenxt.fillEllipse(in: frame)
contenxt.addLine(to: center)
}
}
}
override func acceptMarkVisitor(_ visitor: MarkVisitor) {
visitor.visitDot(self)
}
// MARK: Mark, NScopying
override func copy(with zone: NSZone? = nil) -> Any {
let dotLocation = location ?? CGPoint(x: 0, y: 0)
let dotCopy = Dot(location: dotLocation)
dotCopy.color = color
dotCopy.size = size
return dotCopy
}
// MARK: Mark, NSCoding
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
color = aDecoder.decodeObject(of: UIColor.self, forKey: "DotColor") as UIColor?
size = aDecoder.decodeObject(forKey: "DotSize") as! CGFloat?
}
override func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)
aCoder.encode(color, forKey: "DotColor")
aCoder.encode(size, forKey: "DotSize")
}
}
| mit | bef9e4f5735f5007fd556e0ec87c948d | 28.240741 | 129 | 0.597213 | 3.987374 | false | false | false | false |
tadija/AEAppVersion | Sources/AEAppVersion/State.swift | 1 | 1219 | /**
* https://github.com/tadija/AEAppVersion
* Copyright (c) Marko Tadić 2016-2019
* Licensed under the MIT license. See LICENSE file.
*/
import Foundation
/**
App version state
- New: Clean install
- Equal: Version not changed
- Update: Update from given version
- Rollback: Rollback from given version
*/
public enum State {
/// Clean install
case new
/// Version not changed
case equal
/// Update from given version
case update(previousVersion: String)
/// Rollback from given version
case rollback(previousVersion: String)
}
/// Conformance to `Equatable` protocol
extension State: Equatable {}
/**
Implementation of the `Equatable` protocol so that `State`
can be compared for value equality using operators == and !=.
*/
public func == (lhs: State, rhs: State) -> Bool {
switch (lhs, rhs) {
case (.new, .new):
return true
case (.equal, .equal):
return true
case (let .update(previous1), let .update(previous2)):
return previous1 == previous2
case (let .rollback(previous1), let .rollback(previous2)):
return previous1 == previous2
default:
return false
}
}
| mit | fd6b61cebe6a6074ecd88a1c14245ce7 | 22.882353 | 65 | 0.640394 | 4.156997 | false | false | false | false |
harri121/impressions | impressions/LocationService.swift | 1 | 1952 | //
// LocationService.swift
// impressions
//
// Created by Daniel Hariri on 25.08.17.
// Copyright © 2017 danielhariri. All rights reserved.
//
import Foundation
import CoreLocation
class LocationService: NSObject, CLLocationManagerDelegate {
typealias UpdateCallback = (CLLocation) -> Void
private let travelThreshold: Double = 100.0 //the travel threshold in meter
private let locationHorAccuracyThreshold: Double = 200.0 //the minimum horizontal accuracy in meter for a valid location
private lazy var locationManager: CLLocationManager = {
let manager = CLLocationManager()
manager.allowsBackgroundLocationUpdates = true
manager.distanceFilter = self.travelThreshold
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.pausesLocationUpdatesAutomatically = false
return manager
}()
private var updateCallback: UpdateCallback?
override init() {
super.init()
}
func startLocationUpdates(_ updateCallback: @escaping UpdateCallback) {
locationManager.requestAlwaysAuthorization()
print("Start location updates")
self.updateCallback = updateCallback
locationManager.startUpdatingLocation()
locationManager.delegate = self
}
func stopLocationUpdates() {
print("Stop location updates")
self.updateCallback = nil
locationManager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
for location in locations {
if location.horizontalAccuracy <= locationHorAccuracyThreshold {
updateCallback?(location)
return
}
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus){
}
}
| mit | 8d59bc7ed4357b21097f1255bb1d59d5 | 29.484375 | 124 | 0.6694 | 6.096875 | false | false | false | false |
KVTaniguchi/KTCarousel | Example/KTCarousel/Convenience.swift | 1 | 1336 | //
// Convenience.swift
// KTCarousel
//
// Created by Kevin Taniguchi on 6/13/16.
// Copyright © 2016 Kevin Taniguchi. All rights reserved.
//
import UIKit
import QuartzCore
extension UIColor {
static var colors: [UIColor] {
return [UIColor.red, UIColor.orange, UIColor.purple, UIColor.cyan, UIColor.blue, UIColor.green, UIColor.yellow]
}
static func colorForIndex(_ index: Int) -> UIColor {
return colors[index]
}
}
extension UIImage {
static func imageFromView(_ view: UIView) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0);
guard let ctx = UIGraphicsGetCurrentContext() else { return nil }
view.layer.render(in: ctx)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
static func testingImages() -> [UIImage] {
var data = [UIImage]()
for index in 0...6 {
let lbl = UILabel()
lbl.font = UIFont(name: "Avenir", size: 120)
lbl.text = "\(index)"
lbl.backgroundColor = UIColor.colors[index]
lbl.sizeToFit()
if let image = UIImage.imageFromView(lbl) {
data.append(image)
}
}
return data
}
}
| mit | c70177648675742383746515b77be5f1 | 27.404255 | 119 | 0.602247 | 4.435216 | false | false | false | false |
prisma-ai/torch2coreml | example/fast-neural-style/ios/StyleTransfer/ViewController.swift | 1 | 6684 | //
// ViewController.swift
// StyleTransfer
//
// Created by Oleg Poyaganov on 02/08/2017.
// Copyright © 2017 Prisma Labs, Inc. All rights reserved.
//
import UIKit
import MobileCoreServices
import Photos
import CoreML
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
let imageSize = 720
@IBOutlet weak var loadingView: UIView!
@IBOutlet var buttons: [UIButton]!
@IBOutlet weak var imageView: UIImageView!
private var inputImage = UIImage(named: "input")!
private let models = [
mosaic().model,
the_scream().model,
udnie().model,
candy().model
]
override func viewDidLoad() {
super.viewDidLoad()
loadingView.alpha = 0
for btn in buttons {
btn.imageView?.contentMode = .scaleAspectFill
}
}
// MARK: - Actions
@IBAction func saveResult(_ sender: Any) {
guard let image = imageView.image else {
return
}
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAsset(from: image)
}, completionHandler: nil)
}
@IBAction func takePhoto(_ sender: Any) {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let cameraAction = UIAlertAction(title: "Camera", style: .default) { (action) in
self.showImagePicker(camera: true)
}
alert.addAction(cameraAction)
let libraryAction = UIAlertAction(title: "Photo Library", style: .default) { (action) in
self.showImagePicker(camera: false)
}
alert.addAction(libraryAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
}
alert.addAction(cancelAction)
if UIDevice.current.userInterfaceIdiom == .pad {
alert.popoverPresentationController?.sourceView = self.view
}
present(alert, animated: true, completion: nil)
}
private func showImagePicker(camera: Bool) {
let imagePicker = UIImagePickerController()
if camera {
imagePicker.sourceType = .camera
imagePicker.showsCameraControls = true
} else {
imagePicker.sourceType = .photoLibrary
}
imagePicker.delegate = self
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.allowsEditing = true
present(imagePicker, animated: true, completion: nil)
}
@IBAction func styleButtonTouched(_ sender: UIButton) {
guard let image = inputImage.scaled(to: CGSize(width: imageSize, height: imageSize), scalingMode: .aspectFit).cgImage else {
print("Could not get a CGImage")
return
}
let model = models[sender.tag]
toggleLoading(show: true)
DispatchQueue.global(qos: .userInteractive).async {
let stylized = self.stylizeImage(cgImage: image, model: model)
DispatchQueue.main.async {
self.toggleLoading(show: false)
self.imageView.image = UIImage(cgImage: stylized)
}
}
}
private func toggleLoading(show: Bool) {
navigationItem.leftBarButtonItem?.isEnabled = !show
navigationItem.rightBarButtonItem?.isEnabled = !show
UIView.animate(withDuration: 0.25) { [weak self] in
if show {
self?.loadingView.alpha = 0.85
} else {
self?.loadingView.alpha = 0
}
}
}
// MARK: - UIImagePickerControllerDelegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
inputImage = image
imageView.image = image
}
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
// MARK: - Processing
private func stylizeImage(cgImage: CGImage, model: MLModel) -> CGImage {
let input = StyleTransferInput(input: pixelBuffer(cgImage: cgImage, width: imageSize, height: imageSize))
let outFeatures = try! model.prediction(from: input)
let output = outFeatures.featureValue(for: "outputImage")!.imageBufferValue!
CVPixelBufferLockBaseAddress(output, .readOnly)
let width = CVPixelBufferGetWidth(output)
let height = CVPixelBufferGetHeight(output)
let data = CVPixelBufferGetBaseAddress(output)!
let outContext = CGContext(data: data,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: CVPixelBufferGetBytesPerRow(output),
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageByteOrderInfo.order32Little.rawValue | CGImageAlphaInfo.noneSkipFirst.rawValue)!
let outImage = outContext.makeImage()!
CVPixelBufferUnlockBaseAddress(output, .readOnly)
return outImage
}
private func pixelBuffer(cgImage: CGImage, width: Int, height: Int) -> CVPixelBuffer {
var pixelBuffer: CVPixelBuffer? = nil
let status = CVPixelBufferCreate(kCFAllocatorDefault, width, height, kCVPixelFormatType_32BGRA , nil, &pixelBuffer)
if status != kCVReturnSuccess {
fatalError("Cannot create pixel buffer for image")
}
CVPixelBufferLockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags.init(rawValue: 0))
let data = CVPixelBufferGetBaseAddress(pixelBuffer!)
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.noneSkipFirst.rawValue)
let context = CGContext(data: data, width: width, height: height, bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!), space: rgbColorSpace, bitmapInfo: bitmapInfo.rawValue)
context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
CVPixelBufferUnlockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0))
return pixelBuffer!
}
}
| mit | 3066e6b47d7d20a62cafa4d280f89516 | 35.124324 | 205 | 0.621128 | 5.411336 | false | false | false | false |
kstaring/swift | test/IRGen/objc_methods.swift | 7 | 5430 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-os %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import Foundation
// Protocol methods require extended method type encodings to capture block
// signatures and parameter object types.
@objc protocol Fooable {
func block(_: (Int) -> Int)
func block2(_: (Int,Int) -> Int)
func takesString(_: String) -> String
func takesArray(_: [AnyObject]) -> [AnyObject]
func takesDict(_: [NSObject: AnyObject]) -> [NSObject: AnyObject]
func takesSet(_: Set<NSObject>) -> Set<NSObject>
}
class Foo: Fooable {
func bar() {}
@objc func baz() {}
@IBAction func garply(_: AnyObject?) {}
@objc func block(_: (Int) -> Int) {}
@objc func block2(_: (Int,Int) -> Int) {}
@objc func takesString(_ x: String) -> String { return x }
@objc func takesArray(_ x: [AnyObject]) -> [AnyObject] { return x }
@objc func takesDict(_ x: [NSObject: AnyObject]) -> [NSObject: AnyObject] { return x }
@objc func takesSet(_ x: Set<NSObject>) -> Set<NSObject> { return x }
@objc func fail() throws {}
}
// CHECK: [[BAZ_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00"
// CHECK: [[GARPLY_SIGNATURE:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00"
// CHECK: [[BLOCK_SIGNATURE_TRAD:@.*]] = private unnamed_addr constant [12 x i8] c"v24@0:8@?16\00"
// CHECK-macosx: [[FAIL_SIGNATURE:@.*]] = private unnamed_addr constant [12 x i8] c"c24@0:8^@16\00"
// CHECK-ios: [[FAIL_SIGNATURE:@.*]] = private unnamed_addr constant [12 x i8] c"B24@0:8^@16\00"
// CHECK-tvos: [[FAIL_SIGNATURE:@.*]] = private unnamed_addr constant [12 x i8] c"B24@0:8^@16\00"
// CHECK: @_INSTANCE_METHODS__TtC12objc_methods3Foo = private constant { {{.*}}] } {
// CHECK: i32 24,
// CHECK: i32 9,
// CHECK: [9 x { i8*, i8*, i8* }] [{
// CHECK: i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(baz)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[BAZ_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void (i8*, i8*)* @_TToFC12objc_methods3Foo3bazfT_T_ to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(garply:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[GARPLY_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void (i8*, i8*, i8*)* @_TToFC12objc_methods3Foo6garplyfGSqPs9AnyObject__T_ to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(block:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* [[BLOCK_SIGNATURE_TRAD]], i64 0, i64 0),
// CHECK: i8* bitcast (void (i8*, i8*, i64 (i64)*)* @_TToFC12objc_methods3Foo5blockfFSiSiT_ to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(block2:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* [[BLOCK_SIGNATURE_TRAD]], i64 0, i64 0),
// CHECK: i8* bitcast (void (i8*, i8*, i64 (i64, i64)*)* @_TToFC12objc_methods3Foo6block2fFTSiSi_SiT_ to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([20 x i8], [20 x i8]* @"\01L_selector_data(failAndReturnError:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* [[FAIL_SIGNATURE]], i64 0, i64 0),
// CHECK-macosx: i8* bitcast (i8 (i8*, i8*, %4**)* @_TToFC12objc_methods3Foo4failfzT_T_ to i8*)
// CHECK-ios: i8* bitcast (i1 (i8*, i8*, %4**)* @_TToFC12objc_methods3Foo4failfzT_T_ to i8*)
// CHECK: }]
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK: [[BLOCK_SIGNATURE_EXT_1:@.*]] = private unnamed_addr constant [18 x i8] c"v24@0:8@?<q@?q>16\00"
// CHECK: [[BLOCK_SIGNATURE_EXT_2:@.*]] = private unnamed_addr constant [19 x i8] c"v24@0:8@?<q@?qq>16\00"
// CHECK: [[STRING_SIGNATURE_EXT:@.*]] = private unnamed_addr constant [31 x i8] c"@\22NSString\2224@0:8@\22NSString\2216\00"
// CHECK: [[ARRAY_SIGNATURE_EXT:@.*]] = private unnamed_addr constant [29 x i8] c"@\22NSArray\2224@0:8@\22NSArray\2216\00"
// CHECK: [[DICT_SIGNATURE_EXT:@.*]] = private unnamed_addr constant [39 x i8] c"@\22NSDictionary\2224@0:8@\22NSDictionary\2216\00"
// CHECK: [[SET_SIGNATURE_EXT:@.*]] = private unnamed_addr constant [25 x i8] c"@\22NSSet\2224@0:8@\22NSSet\2216\00"
// CHECK: @_PROTOCOL_METHOD_TYPES__TtP12objc_methods7Fooable_ = private constant { [6 x i8*] } {
// CHECK: [6 x i8*] [
// CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* [[BLOCK_SIGNATURE_EXT_1]], i64 0, i64 0)
// CHECK: i8* getelementptr inbounds ([19 x i8], [19 x i8]* [[BLOCK_SIGNATURE_EXT_2]], i64 0, i64 0)
// CHECK: i8* getelementptr inbounds ([31 x i8], [31 x i8]* [[STRING_SIGNATURE_EXT]], i64 0, i64 0)
// CHECK: i8* getelementptr inbounds ([29 x i8], [29 x i8]* [[ARRAY_SIGNATURE_EXT]], i64 0, i64 0)
// CHECK: i8* getelementptr inbounds ([39 x i8], [39 x i8]* [[DICT_SIGNATURE_EXT]], i64 0, i64 0)
// CHECK: i8* getelementptr inbounds ([25 x i8], [25 x i8]* [[SET_SIGNATURE_EXT]], i64 0, i64 0)
// CHECK: ]
// CHECK: }
// rdar://16006333 - observing properties don't work in @objc classes
@objc
class ObservingAccessorTest : NSObject {
var bounds: Int = 0 {
willSet {}
didSet {}
}
}
| apache-2.0 | 219e2f6ab41998db4cd3fed48002a096 | 56.765957 | 157 | 0.62523 | 2.844421 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/FireTimerControl.swift | 1 | 10424 | //
// FireTimerControl.swift
// Telegram
//
// Created by Mikhail Filimonov on 14.01.2021.
// Copyright © 2021 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
private enum ContentState: Equatable {
case clock(NSColor)
case timeout(NSColor, CGFloat)
}
private struct ContentParticle {
var position: CGPoint
var direction: CGPoint
var velocity: CGFloat
var alpha: CGFloat
var lifetime: Double
var beginTime: Double
init(position: CGPoint, direction: CGPoint, velocity: CGFloat, alpha: CGFloat, lifetime: Double, beginTime: Double) {
self.position = position
self.direction = direction
self.velocity = velocity
self.alpha = alpha
self.lifetime = lifetime
self.beginTime = beginTime
}
}
class FireTimerControl: Control {
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.addSubview(self.contentView)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private struct Params: Equatable {
var color: NSColor
var timeout: Int32
var deadlineTimestamp: Int32?
}
private var animator: ConstantDisplayLinkAnimator?
private let contentView: ImageView = ImageView()
private var currentContentState: ContentState?
private var particles: [ContentParticle] = []
private var currentParams: Params?
var reachedTimeout: (() -> Void)?
var reachedHalf: (() -> Void)?
var updateValue: ((CGFloat) -> Void)?
private var reachedHalfNotified: Bool = false
deinit {
self.animator?.invalidate()
}
func updateColor(_ color: NSColor) {
if let params = self.currentParams {
self.currentParams = Params(
color: color,
timeout: params.timeout,
deadlineTimestamp: params.deadlineTimestamp
)
}
}
func update(color: NSColor, timeout: Int32, deadlineTimestamp: Int32?) {
let params = Params(
color: color,
timeout: timeout,
deadlineTimestamp: deadlineTimestamp
)
self.currentParams = params
self.reachedHalfNotified = false
self.updateValues()
}
override func viewWillMove(toWindow newWindow: NSWindow?) {
super.viewWillMove(toWindow: newWindow)
self.animator?.isPaused = newWindow == nil
}
private func updateValues() {
guard let params = self.currentParams else {
return
}
let fractionalTimeout: Double
if let deadlineTimestamp = params.deadlineTimestamp {
let fractionalTimestamp = CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970
fractionalTimeout = min(Double(params.timeout), max(0.0, Double(deadlineTimestamp) + 1.0 - fractionalTimestamp))
} else {
fractionalTimeout = Double(params.timeout)
}
let isTimer = true
let color = params.color
let contentState: ContentState
if isTimer {
var fraction: CGFloat = 1.0
fraction = CGFloat(fractionalTimeout) / CGFloat(params.timeout)
fraction = max(0.0, min(0.99, fraction))
contentState = .timeout(color, 1.0 - fraction)
self.updateValue?(fraction)
} else {
contentState = .clock(color)
}
if let deadlineTimestamp = params.deadlineTimestamp, Int32(Double(deadlineTimestamp) - (CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970)) < params.timeout / 2 {
if let reachedHalf = self.reachedHalf, !reachedHalfNotified {
reachedHalf()
reachedHalfNotified = true
}
}
if self.currentContentState != contentState {
self.currentContentState = contentState
let image: CGImage?
let diameter: CGFloat = 42
let inset: CGFloat = 7
let lineWidth: CGFloat = 2
switch contentState {
case let .clock(color):
image = generateImage(CGSize(width: diameter + inset, height: diameter + inset), rotatedContext: { size, context in
context.clear(CGRect(origin: CGPoint(), size: size))
context.setStrokeColor(color.cgColor)
context.setLineWidth(lineWidth)
context.setLineCap(.round)
let clockFrame = CGRect(origin: CGPoint(x: (size.width - diameter) / 2.0, y: (size.height - diameter) / 2.0), size: CGSize(width: diameter, height: diameter))
context.strokeEllipse(in: clockFrame.insetBy(dx: lineWidth / 2.0, dy: lineWidth / 2.0))
context.move(to: CGPoint(x: size.width / 2.0, y: size.height / 2.0))
context.addLine(to: CGPoint(x: size.width / 2.0, y: clockFrame.minY + 4.0))
context.strokePath()
let topWidth: CGFloat = 4.0
context.move(to: CGPoint(x: size.width / 2.0 - topWidth / 2.0, y: clockFrame.minY - 2.0))
context.addLine(to: CGPoint(x: size.width / 2.0 + topWidth / 2.0, y: clockFrame.minY - 2.0))
context.strokePath()
})
case let .timeout(color, fraction):
let timestamp = CACurrentMediaTime()
let center = CGPoint(x: (diameter + inset) / 2.0, y: (diameter + inset) / 2.0)
let radius: CGFloat = (diameter - lineWidth / 2.0) / 2.0
let startAngle: CGFloat = -CGFloat.pi / 2.0
let endAngle: CGFloat = -CGFloat.pi / 2.0 + 2.0 * CGFloat.pi * fraction
let v = CGPoint(x: sin(endAngle), y: -cos(endAngle))
let c = CGPoint(x: -v.y * radius + center.x, y: v.x * radius + center.y)
let dt: CGFloat = 1.0 / 60.0
var removeIndices: [Int] = []
for i in 0 ..< self.particles.count {
let currentTime = timestamp - self.particles[i].beginTime
if currentTime > self.particles[i].lifetime {
removeIndices.append(i)
} else {
let input: CGFloat = CGFloat(currentTime / self.particles[i].lifetime)
let decelerated: CGFloat = (1.0 - (1.0 - input) * (1.0 - input))
self.particles[i].alpha = 1.0 - decelerated
var p = self.particles[i].position
let d = self.particles[i].direction
let v = self.particles[i].velocity
p = CGPoint(x: p.x + d.x * v * dt, y: p.y + d.y * v * dt)
self.particles[i].position = p
}
}
for i in removeIndices.reversed() {
self.particles.remove(at: i)
}
let newParticleCount = 1
for _ in 0 ..< newParticleCount {
let degrees: CGFloat = CGFloat(arc4random_uniform(140)) - 40.0
let angle: CGFloat = degrees * CGFloat.pi / 180.0
let direction = CGPoint(x: v.x * cos(angle) - v.y * sin(angle), y: v.x * sin(angle) + v.y * cos(angle))
let velocity = (20.0 + (CGFloat(arc4random()) / CGFloat(UINT32_MAX)) * 4.0) * 0.3
let lifetime = Double(0.4 + CGFloat(arc4random_uniform(100)) * 0.01)
let particle = ContentParticle(position: c, direction: direction, velocity: velocity, alpha: 1.0, lifetime: lifetime, beginTime: timestamp)
self.particles.append(particle)
}
image = generateImage(CGSize(width: diameter + inset, height: diameter + inset), rotatedContext: { size, context in
let rect = CGRect(origin: CGPoint(), size: size)
context.clear(rect)
context.setStrokeColor(color.cgColor)
context.setFillColor(color.cgColor)
context.setLineWidth(lineWidth)
context.setLineCap(.round)
let path = CGMutablePath()
path.addArc(center: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
context.addPath(path)
context.strokePath()
for particle in self.particles {
let size: CGFloat = 1.15
context.setAlpha(particle.alpha)
context.fillEllipse(in: CGRect(origin: CGPoint(x: particle.position.x - size / 2.0, y: particle.position.y - size / 2.0), size: CGSize(width: size, height: size)))
}
// let image = NSImage(named: "Icon_ExportedInvitation_Fire")!.precomposed(color, flipVertical: true)
// context.draw(image, in: rect.focus(image.size.aspectFitted(NSMakeSize(30, 30))))
})
}
self.contentView.image = image
self.contentView.sizeToFit()
self.contentView.centerY(x: frame.width - contentView.frame.width)
}
if let reachedTimeout = self.reachedTimeout, fractionalTimeout <= .ulpOfOne {
reachedTimeout()
}
if fractionalTimeout <= .ulpOfOne {
self.animator?.invalidate()
self.animator = nil
} else {
if self.animator == nil {
let animator = ConstantDisplayLinkAnimator(update: { [weak self] in
self?.updateValues()
})
animator.isPaused = self.window == nil
self.animator = animator
}
}
}
}
| gpl-2.0 | fbc06b76ea2e3a83c2fb87e00c1f7dd7 | 38.934866 | 187 | 0.527583 | 4.866013 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/WMFKeychainCredentials.swift | 1 | 6070 | struct WMFKeychainCredentials {
// Based on:
// https://developer.apple.com/library/content/samplecode/GenericKeychain/Introduction/Intro.html
// Note from the example:
// "The KeychainPasswordItem struct provides a high-level interface to the Keychain Services API
// calls required to interface with the iOS keychain. The passwords for keychain item are not
// stored as properties of the struct, instead they are only ever read from the keychain on demand."
// Per the note userName and password are implemented as computed properties.
fileprivate let userNameKey = "org.wikimedia.wikipedia.username"
fileprivate let passwordKey = "org.wikimedia.wikipedia.password"
fileprivate let hostKey = "org.wikimedia.wikipedia.host"
public var userName: String? {
get {
do {
return try getValue(forKey: userNameKey)
} catch {
return nil
}
}
set(newUserName) {
do {
return try set(value: newUserName, forKey: userNameKey)
} catch let error {
assertionFailure("\(error)")
}
}
}
public var password: String? {
get {
do {
return try getValue(forKey: passwordKey)
} catch {
return nil
}
}
set(newPassword) {
do {
return try set(value: newPassword, forKey: passwordKey)
} catch {
assertionFailure("\(error)")
}
}
}
public var host: String? {
get {
do {
return try getValue(forKey: hostKey)
} catch {
return nil
}
}
set {
do {
return try set(value: newValue, forKey: hostKey)
} catch {
assertionFailure("\(error)")
}
}
}
fileprivate enum WMFKeychainCredentialsError: Error {
case noValue
case unexpectedData
case couldNotDeleteData
case unhandledError(status: OSStatus)
}
fileprivate func commonConfigurationDictionary(forKey key:String) -> [String : AnyObject] {
return [
kSecClass as String : kSecClassGenericPassword,
kSecAttrService as String : Bundle.main.bundleIdentifier as AnyObject,
kSecAttrGeneric as String : key as AnyObject,
kSecAttrAccount as String : key as AnyObject
]
}
fileprivate func getValue(forKey key:String) throws -> String {
var query = commonConfigurationDictionary(forKey: key)
query[kSecMatchLimit as String] = kSecMatchLimitOne
query[kSecReturnData as String] = kCFBooleanTrue
query[kSecReturnAttributes as String] = kCFBooleanTrue
var result: AnyObject?
let status = withUnsafeMutablePointer(to: &result) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
guard status != errSecItemNotFound else { throw WMFKeychainCredentialsError.noValue }
guard status == noErr else { throw WMFKeychainCredentialsError.unhandledError(status: status) }
guard
let dictionary = result as? [String: Any],
let data = dictionary[kSecValueData as String] as? Data,
let value = String(data: data, encoding: String.Encoding.utf8)
else {
throw WMFKeychainCredentialsError.unexpectedData
}
// update accessibility of value from kSecAttrAccessibleWhenUnlocked to kSecAttrAccessibleAfterFirstUnlock
if let attrAccessible = dictionary[kSecAttrAccessible as String] as? String, attrAccessible == (kSecAttrAccessibleWhenUnlocked as String) {
try? update(value: value, forKey: key)
}
return value
}
fileprivate func deleteValue(forKey key:String) throws {
let query = commonConfigurationDictionary(forKey: key)
let status = SecItemDelete(query as CFDictionary)
guard status == noErr || status == errSecItemNotFound else { throw WMFKeychainCredentialsError.unhandledError(status: status) }
}
fileprivate func set(value:String?, forKey key:String) throws {
// nil value causes the key/value pair to be removed from the keychain
guard let value = value else {
do {
try deleteValue(forKey: key)
} catch {
throw WMFKeychainCredentialsError.couldNotDeleteData
}
return
}
var query = commonConfigurationDictionary(forKey: key)
let valueData = value.data(using: String.Encoding.utf8)
query[kSecValueData as String] = valueData as AnyObject?
query[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
let status = SecItemAdd(query as CFDictionary, nil)
guard status != errSecSuccess else {
return
}
if status == errSecDuplicateItem {
do {
return try update(value: value, forKey: key)
} catch {
throw WMFKeychainCredentialsError.unhandledError(status: status)
}
} else {
throw WMFKeychainCredentialsError.unhandledError(status: status)
}
}
fileprivate func update(value:String, forKey key:String) throws {
let query = commonConfigurationDictionary(forKey: key)
var dataDict = [String : AnyObject]()
let valueData = value.data(using: String.Encoding.utf8)
dataDict[kSecValueData as String] = valueData as AnyObject?
dataDict[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
let status = SecItemUpdate(query as CFDictionary, dataDict as CFDictionary)
if status != errSecSuccess {
throw WMFKeychainCredentialsError.unhandledError(status: status)
}
}
}
| mit | 6e13d164d607cdfa0bd46750bfe8e454 | 36.9375 | 147 | 0.610379 | 5.568807 | false | false | false | false |
doctorn/hac-website | Sources/HaCTML/Attributes.swift | 1 | 1736 | private func stringAttribute(_ key: String) -> AttributeKey<String> {
return AttributeKey(key, apply: { .text($0) })
}
private func numberAttribute(_ key: String) -> AttributeKey<Int> {
return AttributeKey(key, apply: { .text(String($0)) })
}
private func CSSAttribute(_ key: String) -> AttributeKey<[String: String?]> {
return AttributeKey(key, apply: { dict in
.text(
// filter out the nil values
dict.flatMap {
$0 as? (String, String)
}.map {
"\($0): \($1);"
}.joined(separator: " ")
)
})
}
public enum Attributes {
// We are filling this list in incrementally,
// implementing attributes as we need them so that we can type them correctly
static public let alt = stringAttribute("alt")
static public let charset = stringAttribute("charset")
static public let className = stringAttribute("class")
static public let content = stringAttribute("content")
static public let height = numberAttribute("height")
static public let href = stringAttribute("href")
static public let id = stringAttribute("id")
static public let lang = stringAttribute("lang")
static public let name = stringAttribute("name")
static public let rel = stringAttribute("rel")
static public let src = stringAttribute("src")
static public let srcset = stringAttribute("srcset")
static public let style = CSSAttribute("style")
static public let target = stringAttribute("target")
static public let type = stringAttribute("type")
static public let tabIndex = numberAttribute("tab-index")
static public let width = numberAttribute("width")
}
// Creating a more concise namespace for expressivity
// swiftlint:disable:next identifier_name
public let Attr = Attributes.self
| mit | 43c4ff4dcdee60f5a0eb6159a05cf675 | 36.73913 | 79 | 0.706797 | 4.244499 | false | false | false | false |
jtbandes/swift | test/IRGen/objc_subclass.swift | 6 | 19934 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize %s
// REQUIRES: objc_interop
// CHECK: [[SGIZMO:T13objc_subclass10SwiftGizmoC]] = type
// CHECK: [[TYPE:%swift.type]] = type
// CHECK: [[INT:%TSi]] = type <{ [[LLVM_PTRSIZE_INT:i(32|64)]] }>
// CHECK: [[OBJC_CLASS:%objc_class]] = type
// CHECK: [[OPAQUE:%swift.opaque]] = type
// CHECK: [[GIZMO:%TSo5GizmoC]] = type opaque
// CHECK: [[OBJC:%objc_object]] = type opaque
// CHECK-32: @_T013objc_subclass10SwiftGizmoC1xSivWvd = hidden global i32 12, align [[WORD_SIZE_IN_BYTES:4]]
// CHECK-64: @_T013objc_subclass10SwiftGizmoC1xSivWvd = hidden global i64 16, align [[WORD_SIZE_IN_BYTES:8]]
// CHECK: @"OBJC_METACLASS_$__TtC13objc_subclass10SwiftGizmo" = hidden global [[OBJC_CLASS]] { [[OBJC_CLASS]]* @"OBJC_METACLASS_$_NSObject", [[OBJC_CLASS]]* @"OBJC_METACLASS_$_Gizmo", [[OPAQUE]]* @_objc_empty_cache, [[OPAQUE]]* null, [[LLVM_PTRSIZE_INT]] ptrtoint ({{.*}} @_METACLASS_DATA__TtC13objc_subclass10SwiftGizmo to [[LLVM_PTRSIZE_INT]]) }
// CHECK: [[STRING_SWIFTGIZMO:@.*]] = private unnamed_addr constant [32 x i8] c"_TtC13objc_subclass10SwiftGizmo\00"
// CHECK-32: @_METACLASS_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } {
// CHECK-32: i32 129,
// CHECK-32: i32 20,
// CHECK-32: i32 20,
// CHECK-32: i8* null,
// CHECK-32: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i32 0, i32 0),
// CHECK-32: i8* null,
// CHECK-32: i8* null,
// CHECK-32: i8* null,
// CHECK-32: i8* null,
// CHECK-32: i8* null
// CHECK-32: }, section "__DATA, __objc_const", align 4
// CHECK-64: @_METACLASS_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } {
// CHECK-64: i32 129,
// CHECK-64: i32 40,
// CHECK-64: i32 40,
// CHECK-64: i32 0,
// CHECK-64: i8* null,
// CHECK-64: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i64 0, i64 0),
// CHECK-64: i8* null,
// CHECK-64: i8* null,
// CHECK-64: i8* null,
// CHECK-64: i8* null,
// CHECK-64: i8* null
// CHECK-64: }, section "__DATA, __objc_const", align 8
// CHECK-32: [[METHOD_TYPE_ENCODING1:@.*]] = private unnamed_addr constant [7 x i8] c"l8@0:4\00"
// CHECK-64: [[METHOD_TYPE_ENCODING1:@.*]] = private unnamed_addr constant [8 x i8] c"q16@0:8\00"
// CHECK-32: [[METHOD_TYPE_ENCODING2:@.*]] = private unnamed_addr constant [10 x i8] c"v12@0:4l8\00"
// CHECK-64: [[METHOD_TYPE_ENCODING2:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8q16\00"
// CHECK-32: [[GETTER_ENCODING:@.*]] = private unnamed_addr constant [7 x i8] c"@8@0:4\00"
// CHECK-64: [[GETTER_ENCODING:@.*]] = private unnamed_addr constant [8 x i8] c"@16@0:8\00"
// CHECK-32: [[INIT_ENCODING:@.*]] = private unnamed_addr constant [13 x i8] c"@16@0:4l8@12\00"
// CHECK-64: [[INIT_ENCODING:@.*]] = private unnamed_addr constant [14 x i8] c"@32@0:8q16@24\00"
// CHECK-32: [[DEALLOC_ENCODING:@.*]] = private unnamed_addr constant [7 x i8] c"v8@0:4\00"
// CHECK-64: [[DEALLOC_ENCODING:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00"
// CHECK-32: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } {
// CHECK-32: i32 12,
// CHECK-32: i32 11,
// CHECK-32: [11 x { i8*, i8*, i8* }] [{ i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([2 x i8], [2 x i8]* @"\01L_selector_data(x)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[METHOD_TYPE_ENCODING1]], i32 0, i32 0),
// CHECK-32: i8* bitcast (i32 (%0*, i8*)* @_T013objc_subclass10SwiftGizmoC1xSifgTo to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(setX:)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* [[METHOD_TYPE_ENCODING2]], i32 0, i32 0),
// CHECK-32: i8* bitcast (void (%0*, i8*, i32)* @_T013objc_subclass10SwiftGizmoC1xSifsTo to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(getX)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[METHOD_TYPE_ENCODING1]], i32 0, i32 0),
// CHECK-32: i8* bitcast (i32 (%0*, i8*)* @_T013objc_subclass10SwiftGizmoC4getXSiyFTo to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(duplicate)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast (%1* (%0*, i8*)* @_T013objc_subclass10SwiftGizmoC9duplicateSo0D0CyFTo to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast (%0* (%0*, i8*)* @_T013objc_subclass10SwiftGizmoCACycfcTo to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([20 x i8], [20 x i8]* @"\01L_selector_data(initWithInt:string:)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([13 x i8], [13 x i8]* [[INIT_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast (%0* (%0*, i8*, i32, %2*)* @_T013objc_subclass10SwiftGizmoCACSi3int_SS6stringtcfcTo to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[DEALLOC_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast (void (%0*, i8*)* @_T013objc_subclass10SwiftGizmoCfDTo to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(isEnabled)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* {{@[0-9]+}}, i32 0, i32 0),
// CHECK-32: i8* bitcast ({{(i8|i1)}} (%0*, i8*)* @_T013objc_subclass10SwiftGizmoC7enabledSbfgTo to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(setIsEnabled:)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0),
// CHECK-32: i8* bitcast (void (%0*, i8*, {{(i8|i1)}})* @_T013objc_subclass10SwiftGizmoC7enabledSbfsTo to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0),
// CHECK-32: i8* bitcast (%0* (%0*, i8*, i32)* @_T013objc_subclass10SwiftGizmoCSQyACGSi7bellsOn_tcfcTo to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([15 x i8], [15 x i8]* @"\01L_selector_data(.cxx_construct)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i32 0, i32 0),
// CHECK-32: i8* bitcast (%0* (%0*, i8*)* @_T013objc_subclass10SwiftGizmoCfeTo to i8*)
// CHECK-32: }]
// CHECK-32: }, section "__DATA, __objc_const", align 4
// CHECK-64: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } {
// CHECK-64: i32 24,
// CHECK-64: i32 11,
// CHECK-64: [11 x { i8*, i8*, i8* }] [{
// CHECK-64: i8* getelementptr inbounds ([2 x i8], [2 x i8]* @"\01L_selector_data(x)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[METHOD_TYPE_ENCODING1]], i64 0, i64 0)
// CHECK-64: i8* bitcast (i64 ([[OPAQUE2:%.*]]*, i8*)* @_T013objc_subclass10SwiftGizmoC1xSifgTo to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(setX:)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[METHOD_TYPE_ENCODING2]], i64 0, i64 0)
// CHECK-64: i8* bitcast (void ([[OPAQUE3:%.*]]*, i8*, i64)* @_T013objc_subclass10SwiftGizmoC1xSifsTo to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(getX)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[METHOD_TYPE_ENCODING1]], i64 0, i64 0)
// CHECK-64: i8* bitcast (i64 ([[OPAQUE2]]*, i8*)* @_T013objc_subclass10SwiftGizmoC4getXSiyFTo to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(duplicate)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast ([[OPAQUE1:.*]]* ([[OPAQUE0:%.*]]*, i8*)* @_T013objc_subclass10SwiftGizmoC9duplicateSo0D0CyFTo to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast ([[OPAQUE5:.*]]* ([[OPAQUE6:.*]]*, i8*)* @_T013objc_subclass10SwiftGizmoCACycfcTo to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([20 x i8], [20 x i8]* @"\01L_selector_data(initWithInt:string:)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([14 x i8], [14 x i8]* [[INIT_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast ([[OPAQUE7:%.*]]* ([[OPAQUE8:%.*]]*, i8*, i64, [[OPAQUEONE:.*]]*)* @_T013objc_subclass10SwiftGizmoCACSi3int_SS6stringtcfcTo to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[DEALLOC_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast (void ([[OPAQUE10:%.*]]*, i8*)* @_T013objc_subclass10SwiftGizmoCfDTo to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(isEnabled)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* {{@[0-9]+}}, i64 0, i64 0),
// CHECK-64: i8* bitcast ({{(i8|i1)}} ([[OPAQUE11:%.*]]*, i8*)* @_T013objc_subclass10SwiftGizmoC7enabledSbfgTo to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(setIsEnabled:)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0),
// CHECK-64: i8* bitcast (void ([[OPAQUE12:%.*]]*, i8*, {{(i8|i1)}})* @_T013objc_subclass10SwiftGizmoC7enabledSbfsTo to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0),
// CHECK-64: i8* bitcast ([[OPAQUE11:%.*]]* ([[OPAQUE12:%.*]]*, i8*, i64)* @_T013objc_subclass10SwiftGizmoCSQyACGSi7bellsOn_tcfcTo to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([15 x i8], [15 x i8]* @"\01L_selector_data(.cxx_construct)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i64 0, i64 0),
// CHECK-64: i8* bitcast ([[OPAQUE5]]* ([[OPAQUE6]]*, i8*)* @_T013objc_subclass10SwiftGizmoCfeTo to i8*)
// CHECK-64: }]
// CHECK-64: }, section "__DATA, __objc_const", align 8
// CHECK: [[STRING_X:@.*]] = private unnamed_addr constant [2 x i8] c"x\00"
// CHECK: [[STRING_EMPTY:@.*]] = private unnamed_addr constant [1 x i8] zeroinitializer
// CHECK-32: @_IVARS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } {
// CHECK-32: i32 20,
// CHECK-32: i32 1,
// CHECK-32: [1 x { i32*, i8*, i8*, i32, i32 }] [{ i32*, i8*, i8*, i32, i32 } {
// CHECK-32: i32* @_T013objc_subclass10SwiftGizmoC1xSivWvd,
// CHECK-32: i8* getelementptr inbounds ([2 x i8], [2 x i8]* [[STRING_X]], i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([1 x i8], [1 x i8]* [[STRING_EMPTY]], i32 0, i32 0),
// CHECK-32: i32 2,
// CHECK-32: i32 4 }]
// CHECK-32: }, section "__DATA, __objc_const", align 4
// CHECK-64: @_IVARS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } {
// CHECK-64: i32 32,
// CHECK-64: i32 1,
// CHECK-64: [1 x { i64*, i8*, i8*, i32, i32 }] [{ i64*, i8*, i8*, i32, i32 } {
// CHECK-64: i64* @_T013objc_subclass10SwiftGizmoC1xSivWvd,
// CHECK-64: i8* getelementptr inbounds ([2 x i8], [2 x i8]* [[STRING_X]], i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([1 x i8], [1 x i8]* [[STRING_EMPTY]], i64 0, i64 0),
// CHECK-64: i32 3,
// CHECK-64: i32 8 }]
// CHECK-64: }, section "__DATA, __objc_const", align 8
// CHECK-32: @_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } {
// CHECK-32: i32 132,
// CHECK-32: i32 12,
// CHECK-32: i32 16,
// CHECK-32: i8* null,
// CHECK-32: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i32 0, i32 0),
// CHECK-32: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo,
// CHECK-32: i8* null,
// CHECK-32: @_IVARS__TtC13objc_subclass10SwiftGizmo,
// CHECK-32: i8* null,
// CHECK-32: @_PROPERTIES__TtC13objc_subclass10SwiftGizmo
// CHECK-32: }, section "__DATA, __objc_const", align 4
// CHECK-64: @_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } {
// CHECK-64: i32 132,
// CHECK-64: i32 16,
// CHECK-64: i32 24,
// CHECK-64: i32 0,
// CHECK-64: i8* null,
// CHECK-64: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i64 0, i64 0),
// CHECK-64: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo,
// CHECK-64: i8* null,
// CHECK-64: @_IVARS__TtC13objc_subclass10SwiftGizmo,
// CHECK-64: i8* null,
// CHECK-64: @_PROPERTIES__TtC13objc_subclass10SwiftGizmo
// CHECK-64: }, section "__DATA, __objc_const", align 8
// CHECK-NOT: @_TMCSo13SwiftGizmo = {{.*NSObject}}
// CHECK: @_INSTANCE_METHODS__TtC13objc_subclass12GenericGizmo
// CHECK-32: [[SETTER_ENCODING:@.*]] = private unnamed_addr constant [10 x i8] c"v12@0:4@8\00"
// CHECK-64: [[SETTER_ENCODING:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00"
// CHECK-32: @_INSTANCE_METHODS__TtC13objc_subclass11SwiftGizmo2 = private constant { i32, i32, [5 x { i8*, i8*, i8* }] } {
// CHECK-32: i32 12,
// CHECK-32: i32 5,
// CHECK-32: [5 x { i8*, i8*, i8* }] [
// CHECK-32: {
// CHECK-32: i8* getelementptr inbounds ([3 x i8], [3 x i8]* @"\01L_selector_data(sg)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast (%0* (%3*, i8*)* @_T013objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCfgTo to i8*)
// CHECK-32: }, {
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(setSg:)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* [[SETTER_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast (void (%3*, i8*, %0*)* @_T013objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCfsTo to i8*)
// CHECK-32: }, {
// CHECK-32: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast (%3* (%3*, i8*)* @_T013objc_subclass11SwiftGizmo2CACycfcTo to i8*)
// CHECK-32: }, {
// CHECK-32: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0),
// CHECK-32: i8* bitcast (%3* (%3*, i8*, i32)* @_T013objc_subclass11SwiftGizmo2CSQyACGSi7bellsOn_tcfcTo to i8*)
// CHECK-32: }, {
// CHECK-32: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i32 0, i32 0),
// CHECK-32: i8* bitcast (void (%3*, i8*)* @_T013objc_subclass11SwiftGizmo2CfETo to i8*)
// CHECK-32: }
// CHECK-32: ]
// CHECK-32: }, section "__DATA, __objc_const", align 4
// CHECK-64: @_INSTANCE_METHODS__TtC13objc_subclass11SwiftGizmo2 = private constant { i32, {{.*}}] } {
// CHECK-64: i32 24,
// CHECK-64: i32 5,
// CHECK-64: [5 x { i8*, i8*, i8* }] [
// CHECK-64: {
// CHECK-64: i8* getelementptr inbounds ([3 x i8], [3 x i8]* @"\01L_selector_data(sg)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast ([[OPAQUE13:%.*]]* ([[OPAQUE14:%.*]]*, i8*)* @_T013objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCfgTo to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(setSg:)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast (void ([[OPAQUE15:%.*]]*, i8*, [[OPAQUE16:%.*]]*)* @_T013objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCfsTo to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast ([[OPAQUE18:%.*]]* ([[OPAQUE19:%.*]]*, i8*)* @_T013objc_subclass11SwiftGizmo2CACycfcTo to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0),
// CHECK-64: i8* bitcast ([[OPAQUE21:%.*]]* ([[OPAQUE22:%.*]]*, i8*, i64)* @_T013objc_subclass11SwiftGizmo2CSQyACGSi7bellsOn_tcfcTo to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i64 0, i64 0)
// CHECK-64: i8* bitcast (void ([[OPAQUE20:%.*]]*, i8*)* @_T013objc_subclass11SwiftGizmo2CfETo to i8*)
// CHECK-64: }
// CHECK-64: ] }
// CHECK: @objc_classes = internal global [2 x i8*] [i8* bitcast (%swift.type* @_T013objc_subclass10SwiftGizmoCN to i8*), i8* bitcast (%swift.type* @_T013objc_subclass11SwiftGizmo2CN to i8*)], section "__DATA, __objc_classlist, regular, no_dead_strip", align [[WORD_SIZE_IN_BYTES]]
// CHECK: @objc_non_lazy_classes = internal global [1 x i8*] [i8* bitcast (%swift.type* @_T013objc_subclass11SwiftGizmo2CN to i8*)], section "__DATA, __objc_nlclslist, regular, no_dead_strip", align [[WORD_SIZE_IN_BYTES]]
import Foundation
import gizmo
@requires_stored_property_inits
class SwiftGizmo : Gizmo {
var x = Int()
func getX() -> Int {
return x
}
override func duplicate() -> Gizmo {
return SwiftGizmo()
}
override init() {
super.init(bellsOn:0)
}
init(int i: Int, string str : String) {
super.init(bellsOn:i)
}
deinit { var x = 10 }
var enabled: Bool {
@objc(isEnabled) get {
return true
}
@objc(setIsEnabled:) set {
}
}
}
class GenericGizmo<T> : Gizmo {
func foo() {}
var x : Int {
return 0
}
var array : [T] = []
}
// CHECK: define hidden swiftcc [[LLVM_PTRSIZE_INT]] @_T013objc_subclass12GenericGizmoC1xSifg(
var sg = SwiftGizmo()
sg.duplicate()
@objc_non_lazy_realization
class SwiftGizmo2 : Gizmo {
var sg : SwiftGizmo
override init() {
sg = SwiftGizmo()
super.init()
}
deinit { }
}
| apache-2.0 | 8c0d022e2a6f3ba602f8255ab474e914 | 57.976331 | 347 | 0.599478 | 2.762472 | false | false | false | false |
kazuteru/KKAlertView | KKAlertViewSample/Pods/KKAlertView/KKAlertView/KKAlertBackgroundView.swift | 1 | 2892 | //
// BackView.swift
// KKAlertBackgroundView
//
// Created by 小橋 一輝 on 2015/03/27.
// Copyright (c) 2015年 kobashi kazuki. All rights reserved.
//
import UIKit
class KKAlertBackgroundView: UIView {
var alertView: UIView?
var cancel: (() -> Void)?
var animator: UIDynamicAnimator!
var backgroundColorShowingAlert = UIColor.blackColor().colorWithAlphaComponent(0.2)
override init(frame: CGRect) {
super.init(frame: frame)
animator = UIDynamicAnimator(referenceView: self)
backgroundColor = self.backgroundColorShowingAlert.colorWithAlphaComponent(0.0)
}
func setAlert(alertView: UIView) {
self.alertView = alertView
self.alertView!.center.x = self.center.x
if alertView is KKAlertView {
var alertView = self.alertView as! KKAlertView
alertView.delegate = self
}
addSubview(alertView)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func showAlertView() {
//managerを使用
ShowAnimationManager.sharedInstance.attachmentAnimation(self.animator,
view: alertView!,
animations: {
self.backgroundColor = self.backgroundColorShowingAlert
}, completion: nil)
}
func dismissAlertView() {
//gravityBehaviorがdelegateをcatchできないため、UIViewのanimeのdelayを利用
DismissAnimationManager.sharedInstance.gravityAnimation(self.animator,
view: alertView!,
animations: { self.backgroundColor = self.backgroundColorShowingAlert.colorWithAlphaComponent(0.0) },
completion: { if let cancel = self.cancel { cancel() } })
}
//swift1.2より変更
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if let alertView = alertView {
if let touch = touches.first as? UITouch {
let location = touch.locationInView(self)
if checkTouch(location!) {
dismissAlertView()
}
}
}
}
func checkTouch(location: CGPoint) -> Bool {
if let alertView = alertView {
if location.x < alertView.frame.origin.x {
return true
}
if location.y < alertView.frame.origin.y {
return true
}
if location.x > alertView.frame.origin.x + alertView.frame.width {
return true
}
if location.y > alertView.frame.origin.y + alertView.frame.height {
return true
}
}
return false
}
}
extension KKAlertBackgroundView: KKAlertViewDelegate {
func dismissAlertView(alertView: KKAlertView) {
dismissAlertView()
}
} | mit | 9f45ffe049263e2537f88739e2c3165a | 30.544444 | 113 | 0.605004 | 4.80203 | false | false | false | false |
titoi2/IchigoJamSerialConsole | IchigoJamSerialConsole/Managers/MonitorManager.swift | 1 | 9383 | //
// MonitorManager.swift
// IchigoJamSerialConsole
//
// Created by titoi2 on 2015/08/18.
// Copyright (c) 2015年 titoi2. All rights reserved.
//
import Foundation
import Cocoa
protocol MonitorManagerDelegate {
func onDispChange(img:NSImage)
}
class MonitorManager:NSObject {
static let sharedInstance = MonitorManager()
let SCREEN_CHARA_WIDTH = 32
let SCREEN_CHARA_HEIGTH = 24
var width:Int = 0
var height:Int = 0
var widthPixels:Int = 0
var heightPixels:Int = 0
var cursorX:Int = 0
var cursorY:Int = 0
var vram:[[UInt8]]
// var screenImage: NSImage
enum InterpreterState {
case Idle
case TakeX
case TakeY
}
var interpreterState:InterpreterState = InterpreterState.Idle
var fontImage:NSImage = NSImage(named: "charas")!
var delegate:MonitorManagerDelegate? = nil
var bitmapContext:CGContext
private override init() {
width = SCREEN_CHARA_WIDTH
height = SCREEN_CHARA_HEIGTH
widthPixels = SCREEN_CHARA_WIDTH * 8
heightPixels = SCREEN_CHARA_HEIGTH * 8
vram = [[UInt8]](count: height, repeatedValue: [UInt8](count: width, repeatedValue: 0x20))
// 新しいサイズのビットマップを作成します。
let bitsPerComponent = Int(8)
let bytesPerRow = Int(4 * widthPixels)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
bitmapContext = CGBitmapContextCreate(nil, widthPixels, heightPixels,
bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo)!
super.init()
for y in 0 ..< height {
for x in 0 ..< width {
putChar( x, y: y, c: 0x20)
}
}
}
/*
CLS 19, 12
SCROLL 左 21, 28
SCROLL 右 21, 29
SCROLL 上 21, 30
SCROLL 下 21, 31
LOCATE 21, 32+X,32+Y
*/
func interpret(str:[UInt8]) {
for c in str {
switch interpreterState {
case .TakeX:
switch c {
case 28:
// スクロール左
scrollLeft()
interpreterState = .Idle
vram2ImageCG()
break
case 29:
// スクロール右
scrollRight()
interpreterState = .Idle
vram2ImageCG()
break
case 30:
// スクロール上
scrollUp()
interpreterState = .Idle
vram2ImageCG()
break
case 31:
// スクロール下
scrollDown()
interpreterState = .Idle
vram2ImageCG()
break
default:
cursorX = Int(c) - 32
if cursorX < 0 {
NSLog("invalid cursorX:\(cursorX)")
cursorX = 0
interpreterState = .Idle
} else {
interpreterState = .TakeY
}
break
}
break
case .TakeY:
cursorY = Int(c) - 32
if cursorY < 0 {
NSLog("invalid cursorY:\(cursorY)")
cursorY = 0
}
interpreterState = .Idle
break
default:
switch c {
case 0x0A: // LF
cursorX = 0
cursorY++
if cursorY >= height {
cursorY = height - 1
}
break
case 0x0C: // カーソル位置以降の文字を削除
for y in cursorY ..< height {
for x in cursorX ..< width {
putChar( x, y: y, c: 0x20)
}
}
vram2ImageCG()
break
case 0x0D: // CR
cursorX = 0
break
case 0x13: // Page Up (カーソルを左上へ)
cursorX = 0
cursorY = 0
break
case 0x15: // <32+<X座標>><32+<Y座標> の3バイトでカーソル移動
interpreterState = .TakeX
break
default:
putChar( cursorX, y: cursorY, c: c)
cursorX++
if cursorX >= width {
cursorX = 0
cursorY++
if cursorY >= height {
cursorY = height - 1
}
}
vram2ImageCG()
break
}
}
}
}
private func putChar(x:Int,y:Int,c:UInt8) {
if x < 0 {
NSLog("invalid x:\(x)")
}
if y < 0 {
NSLog("invalid y:\(y)")
}
vram[y][x] = c
}
// lockFocusによるイメージ生成
func vram2ImageLF() {
var screenImage = NSImage(size: NSSize(width: self.width * 8,height: self.height * 8))
screenImage.lockFocus()
for y in 0..<height {
let yp = (height - y) * 8
// NSLog("y:\(y) yp:\(yp)")
for x in 0..<width {
let c:UInt8 = vram[y][x]
let xp = x * 8
let rect = NSRect(x: xp, y: yp, width: 8, height: 8)
fontImage.drawInRect(rect,
fromRect: fontRectX(c),
operation: NSCompositingOperation.CompositeDestinationOver, fraction: 1.0)
}
}
screenImage.unlockFocus()
if let d = delegate {
d.onDispChange(screenImage)
}
}
func fontRectX(c8:UInt8) -> NSRect {
let c = Int(c8)
let low = c & 0xF
let high = 15 - ((c & 0xF0) >> 4)
return NSRect(x: low * 8, y: high * 8, width: 8, height: 8)
}
// Core Graphicsによるイメージ生成
func vram2ImageCG() {
let image = NSBitmapImageRep(data: fontImage.TIFFRepresentation!)?.CGImage!
// CGContextSetRGBFillColor(bitmapContext, 1.0, 0.0, 0.0, 1.0);
// CGContextSetRGBStrokeColor(bitmapContext, 0.0, 1.0, 0.0, 1.0);
// CGContextFillRect(bitmapContext, NSRect(x: 0,y: 0,width: widthPixels,height: heightPixels));
for y in 0..<height {
let yp = (height - y - 1) * 8
for x in 0..<width {
let c:UInt8 = vram[y][x]
let xp = x * 8
let rect = NSRect(x: xp, y: yp, width: 8, height: 8)
let fontref = CGImageCreateWithImageInRect(image, fontRect(c));
CGContextDrawImage(bitmapContext, rect, CGImageCreateCopy( fontref))
}
}
// ビットマップを NSImage に変換します。
let newImageRef = CGBitmapContextCreateImage(bitmapContext)!
let newImage = NSImage(CGImage: newImageRef, size: NSSize(width: widthPixels, height: heightPixels))
if let d = delegate {
d.onDispChange(newImage)
}
}
func fontRect(c8:UInt8) -> NSRect {
let c = Int(c8)
let low = c & 0xF
let high = ((c & 0xF0) >> 4)
return NSRect(x: low * 8, y: high * 8, width: 8, height: 8)
}
func scrollLeft() {
for y in 0..<height {
for x in 0..<(width - 1) {
vram[y][x] = vram[y][x+1]
}
vram[y][width - 1] = 32
}
}
func scrollRight() {
for y in 0..<height {
for var x = (width - 1); x > 0; x-- {
vram[y][x] = vram[y][x-1]
}
vram[y][0] = 32
}
}
func scrollUp() {
for y in 0..<(height - 1) {
for x in 0..<width {
vram[y][x] = vram[y+1][x]
}
}
for x in 0..<width {
vram[height - 1][x] = 32
}
}
func scrollDown() {
for var y = (height - 1); y > 0; y-- {
for x in 0..<width {
vram[y][x] = vram[y-1][x]
}
}
for x in 0..<width {
vram[0][x] = 32
}
}
func takeImage() {
vram2ImageCG()
}
}
| mit | ec161c9a8ce73227089d683420924350 | 26.610272 | 110 | 0.408797 | 4.542247 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/Browser/Tabs/InactiveTabCell.swift | 2 | 10916 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import UIKit
import Shared
import SwiftUI
enum InactiveTabSection: Int, CaseIterable {
case inactive
case closeAllTabsButton
}
protocol InactiveTabsDelegate: AnyObject {
func toggleInactiveTabSection(hasExpanded: Bool)
func didSelectInactiveTab(tab: Tab?)
func didTapCloseAllTabs()
func shouldCloseInactiveTab(tab: Tab)
func setupCFR(with view: UILabel)
func presentCFR()
}
class InactiveTabCell: UICollectionViewCell, ReusableCell {
struct UX {
static let HeaderAndRowHeight: CGFloat = 48
static let CloseAllTabRowHeight: CGFloat = 88
static let RoundedContainerPaddingClosed: CGFloat = 30
static let RoundedContainerAdditionalPaddingOpened: CGFloat = 40
static let InactiveTabTrayWidthPadding: CGFloat = 30
}
// MARK: - Properties
var inactiveTabsViewModel: InactiveTabViewModel?
var hasExpanded = false
weak var delegate: InactiveTabsDelegate?
// Views
lazy var tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: .grouped)
tableView.register(InactiveTabItemCell.self, forCellReuseIdentifier: InactiveTabItemCell.cellIdentifier)
tableView.register(CellWithRoundedButton.self, forCellReuseIdentifier: CellWithRoundedButton.cellIdentifier)
tableView.register(InactiveTabHeader.self, forHeaderFooterViewReuseIdentifier: InactiveTabHeader.cellIdentifier)
tableView.allowsMultipleSelectionDuringEditing = false
tableView.sectionHeaderHeight = 0
tableView.sectionFooterHeight = 0
tableView.tableHeaderView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 0, height: CGFloat.leastNormalMagnitude)))
tableView.separatorStyle = .none
tableView.separatorColor = .clear
tableView.isScrollEnabled = false
tableView.dataSource = self
tableView.delegate = self
tableView.translatesAutoresizingMaskIntoConstraints = false
return tableView
}()
private var containerView: UIView = .build { view in
view.layer.cornerRadius = 13
view.layer.borderWidth = 1
view.layer.borderColor = UIColor.clear.cgColor
}
// MARK: - Initializers
convenience init(viewModel: InactiveTabViewModel) {
self.init()
inactiveTabsViewModel = viewModel
}
override init(frame: CGRect) {
super.init(frame: frame)
containerView.addSubviews(tableView)
addSubviews(containerView)
setupConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupConstraints() {
NSLayoutConstraint.activate([
containerView.topAnchor.constraint(equalTo: topAnchor, constant: 5),
containerView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -5),
containerView.leadingAnchor.constraint(equalTo: leadingAnchor),
containerView.trailingAnchor.constraint(equalTo: trailingAnchor),
tableView.topAnchor.constraint(equalTo: topAnchor, constant: 10),
tableView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -10),
tableView.leadingAnchor.constraint(equalTo: leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: trailingAnchor),
])
self.bringSubviewToFront(tableView)
}
}
extension InactiveTabCell: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return InactiveTabSection.allCases.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if !hasExpanded { return 0 }
switch InactiveTabSection(rawValue: section) {
case .inactive:
return inactiveTabsViewModel?.inactiveTabs.count ?? 0
case .closeAllTabsButton:
return 1
case .none:
return 0
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch InactiveTabSection(rawValue: indexPath.section) {
case .inactive, .none:
return InactiveTabCell.UX.HeaderAndRowHeight
case .closeAllTabsButton:
return UITableView.automaticDimension
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch InactiveTabSection(rawValue: indexPath.section) {
case .inactive:
guard let cell = tableView.dequeueReusableCell(withIdentifier: InactiveTabItemCell.cellIdentifier,
for: indexPath) as? InactiveTabItemCell
else {
return UITableViewCell()
}
guard let tab = inactiveTabsViewModel?.inactiveTabs[indexPath.item] else { return cell }
let viewModel = InactiveTabItemCellModel(title: tab.getTabTrayTitle(),
icon: tab.displayFavicon,
website: getTabDomainUrl(tab: tab))
cell.configureCell(viewModel: viewModel)
return cell
case .closeAllTabsButton:
guard let cell = tableView.dequeueReusableCell(withIdentifier: CellWithRoundedButton.cellIdentifier,
for: indexPath) as? CellWithRoundedButton
else {
return UITableViewCell()
}
cell.buttonClosure = {
self.delegate?.didTapCloseAllTabs()
}
return cell
case .none:
guard let cell = tableView.dequeueReusableCell(withIdentifier: OneLineTableViewCell.cellIdentifier,
for: indexPath) as? OneLineTableViewCell
else {
return UITableViewCell()
}
return cell
}
}
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if !hasExpanded { return nil }
switch InactiveTabSection(rawValue: section) {
case .inactive, .none, .closeAllTabsButton:
return nil
}
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if !hasExpanded { return CGFloat.leastNormalMagnitude }
switch InactiveTabSection(rawValue: section) {
case .inactive, .none, .closeAllTabsButton:
return CGFloat.leastNormalMagnitude
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let section = indexPath.section
switch InactiveTabSection(rawValue: section) {
case .inactive:
if let tab = inactiveTabsViewModel?.inactiveTabs[indexPath.item] {
delegate?.didSelectInactiveTab(tab: tab)
}
case .closeAllTabsButton, .none:
print("nothing")
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
switch InactiveTabSection(rawValue: section) {
case .inactive, .none:
guard let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: InactiveTabHeader.cellIdentifier) as? InactiveTabHeader else { return nil }
headerView.state = hasExpanded ? .down : .right
headerView.title = String.TabsTrayInactiveTabsSectionTitle
headerView.accessibilityLabel = hasExpanded ?
.TabsTray.InactiveTabs.TabsTrayInactiveTabsSectionOpenedAccessibilityTitle :
.TabsTray.InactiveTabs.TabsTrayInactiveTabsSectionClosedAccessibilityTitle
headerView.moreButton.isHidden = false
headerView.moreButton.addTarget(self,
action: #selector(toggleInactiveTabSection),
for: .touchUpInside)
headerView.contentView.backgroundColor = .clear
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(toggleInactiveTabSection))
headerView.addGestureRecognizer(tapGesture)
delegate?.setupCFR(with: headerView.titleLabel)
return headerView
case .closeAllTabsButton:
return nil
}
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
let section = indexPath.section
switch InactiveTabSection(rawValue: section) {
case .inactive:
return .delete
case .closeAllTabsButton, .none:
return .none
}
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
let section = indexPath.section
guard editingStyle == .delete else { return }
switch InactiveTabSection(rawValue: section) {
case .inactive:
if let tab = inactiveTabsViewModel?.inactiveTabs[indexPath.item] {
delegate?.shouldCloseInactiveTab(tab: tab)
}
case .closeAllTabsButton, .none: return
}
}
@objc func toggleInactiveTabSection() {
hasExpanded = !hasExpanded
tableView.reloadData()
delegate?.toggleInactiveTabSection(hasExpanded: hasExpanded)
// Post accessibility notification when the section was opened/closed
UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: nil)
if hasExpanded { delegate?.presentCFR() }
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
switch InactiveTabSection(rawValue: section) {
case .inactive, .none:
return InactiveTabCell.UX.HeaderAndRowHeight
case .closeAllTabsButton:
return CGFloat.leastNormalMagnitude
}
}
func getTabDomainUrl(tab: Tab) -> URL? {
guard tab.url != nil else { return tab.sessionData?.urls.last?.domainURL }
return tab.url?.domainURL
}
func applyTheme(_ theme: Theme) {
backgroundColor = .clear
tableView.backgroundColor = .clear
containerView.backgroundColor = theme.colors.layer5
tableView.reloadData()
}
}
| mpl-2.0 | 4eb6de35c5dc23745075ff301061316c | 38.407942 | 168 | 0.655551 | 5.566548 | false | false | false | false |
haawa799/WaniKani-iOS | WaniKani/Utils/KeychainManager.swift | 1 | 1327 | //
// KeychainManager.swift
// WaniKani
//
// Created by Andriy K. on 2/2/16.
// Copyright © 2016 Andriy K. All rights reserved.
//
import UIKit
import UICKeyChainStore
struct KeychainManager {
let apiKeyStoreKey = "WaniKaniApiKey"
let userKey = "userKey"
let passwordKey = "passwordKey"
let keychain = UICKeyChainStore(service: "com.haawa.WaniKani")
let firstRunDefaultsKey = "FirstRun"
let firstRunValue = "1strun"
func cleanKeychainIfNeeded() {
if (NSUserDefaults.standardUserDefaults().objectForKey(firstRunDefaultsKey) == nil) {
keychain[apiKeyStoreKey] = nil
NSUserDefaults.standardUserDefaults().setValue(firstRunValue, forKey: firstRunDefaultsKey)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
func wipeKeychain() {
keychain[apiKeyStoreKey] = nil
keychain[userKey] = nil
keychain[passwordKey] = nil
}
var apiKey: String? {
return keychain[apiKeyStoreKey]
}
func setNewApiKey(key: String) {
keychain[apiKeyStoreKey] = key
}
var user: String? {
return keychain[userKey]
}
func setUsername(usr: String) {
keychain[userKey] = usr
}
var password: String? {
return keychain[passwordKey]
}
func setPassword(passw: String) {
keychain[passwordKey] = passw
}
}
| gpl-3.0 | 2d0dcc02766e7ffb33b8613af2ca73d7 | 20.387097 | 96 | 0.680995 | 4.018182 | false | false | false | false |
luanlzsn/EasyPass | EasyPass/Classes/Common/Common.swift | 1 | 11460 | //
// Common.swift
// MoFan
//
// Created by luan on 2016/12/8.
// Copyright © 2016年 luan. All rights reserved.
//
import UIKit
import YYCategories
import AFNetworking
class Common: NSObject {
//MARK: - 根据十六进制颜色值获取颜色
class func colorWithHexString(colorStr:String) -> UIColor {
var color = UIColor.red
var cStr : String = colorStr.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
if cStr.hasPrefix("#") {
let index = cStr.index(after: cStr.startIndex)
cStr = cStr.substring(from: index)
}
if cStr.characters.count != 6 {
return UIColor.black
}
//两种不同截取字符串的方法
let rRange = cStr.startIndex ..< cStr.index(cStr.startIndex, offsetBy: 2)
let rStr = cStr.substring(with: rRange)
let gRange = cStr.index(cStr.startIndex, offsetBy: 2) ..< cStr.index(cStr.startIndex, offsetBy: 4)
let gStr = cStr.substring(with: gRange)
let bIndex = cStr.index(cStr.endIndex, offsetBy: -2)
let bStr = cStr.substring(from: bIndex)
color = UIColor(red: CGFloat(changeToInt(numStr: rStr)) / 255.0, green: CGFloat(changeToInt(numStr: gStr)) / 255.0, blue: CGFloat(changeToInt(numStr: bStr)) / 255.0, alpha: 1)
return color
}
class func changeToInt(numStr: String) -> Int {
let str = numStr.uppercased()
var sum = 0
for i in str.utf8 {
//0-9 从48开始
sum = sum * 16 + Int(i) - 48
if i >= 65 {
//A~Z 从65开始,但初始值为10
sum -= 7
}
}
return sum
}
//MARK: - 中文转拼音
class func chineseToPinyin(chinese: String) -> String {
let mutableString = NSMutableString(string: chinese)
CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
return mutableString.replacingOccurrences(of: " ", with: "")
}
// MARK: - 校验手机号
class func isValidateMobile(mobile: String) -> Bool {
do {
let pattern = "^((13[0-9])|(15[^4,\\D])|(17[0,0-9])|(18[0,0-9]))\\d{8}$"
let regex: NSRegularExpression = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let matches = regex.numberOfMatches(in: mobile, options: [.reportProgress], range: NSMakeRange(0, mobile.characters.count))
return matches > 0
}
catch {
return false
}
}
// MARK: - 校验邮箱
class func isValidateEmail(email: String) -> Bool {
do {
let pattern = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-_]+\\.[A-Za-z]{2,4}"
let regex: NSRegularExpression = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let matches = regex.numberOfMatches(in: email, options: [.reportProgress], range: NSMakeRange(0, email.characters.count))
return matches > 0
}
catch {
return false
}
}
// MARK: - 校验邮箱
class func isValidateURL(urlStr: String) -> Bool {
do {
let pattern = "http(s)?:\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&=]*)?"
let regex: NSRegularExpression = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let matches = regex.numberOfMatches(in: urlStr, options: [.reportProgress], range: NSMakeRange(0, urlStr.characters.count))
return matches > 0
}
catch {
return false
}
}
// MARK: - 校验数字
class func isValidateNumber(numberStr: String) -> Bool {
do {
let pattern = "^[0-9]*$"
let regex: NSRegularExpression = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let matches = regex.numberOfMatches(in: numberStr, options: [.reportProgress], range: NSMakeRange(0, numberStr.characters.count))
return matches > 0
}
catch {
return false
}
}
//MARK: - 将字符串根据格式转换为日期
class func obtainDateWithStr(str: String, formatterStr: String) -> Date {
let formatter = DateFormatter()
formatter.dateFormat = formatterStr
let date = formatter.date(from: str)
return (date != nil) ? date! : Date()
}
//MARK: - 根据日期和格式获取字符串
class func obtainStringWithDate(date: Date, formatterStr: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = formatterStr
return formatter.string(from: date)
}
//MARK: - md5加密
class func md5String(str:String) -> String {
let cStr = str.cString(using: String.Encoding.utf8);
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 16)
CC_MD5(cStr!,(CC_LONG)(strlen(cStr!)), buffer)
let md5String = NSMutableString();
for i in 0 ..< 16{
md5String.appendFormat("%02x", buffer[i])
}
free(buffer)
return md5String as String
}
// MARK: 根据属性对对象数组进行排序
class func sortArray(array: [Any], descriptor: String, ascending: Bool) -> [Any] {
let sortDescriptor = NSSortDescriptor.init(key: descriptor, ascending: ascending)
return (array as NSArray).sortedArray(using: [sortDescriptor])
}
//MARK: - 需要登录之后才能执行的操作判断是否可以操作,返回YES可以继续操作,否则自动跳转到登录
class func checkIsOperation(controller : UIViewController) -> Bool {
if AntManage.isLogin {
return true
} else {
let storyboard = UIStoryboard(name: "Login", bundle: Bundle.main)
let login = storyboard.instantiateInitialViewController()
controller.present(login!, animated: true, completion: nil)
return false
}
}
//MARK: - 游客需要登录之后才能执行的操作判断是否可以操作,返回YES可以继续操作,否则自动跳转到登录
class func checkTouristIsOperation(controller : UIViewController) -> Bool {
if AntManage.isLogin, !AntManage.isTourist {
return true
} else {
let storyboard = UIStoryboard(name: "Login", bundle: Bundle.main)
let login = storyboard.instantiateInitialViewController()
controller.present(login!, animated: true, completion: nil)
return false
}
}
//MARK: - 永久闪烁的动画
class func opacityForeverAnimation(time: Float) -> CABasicAnimation {
let animation = CABasicAnimation(keyPath: "opacity")
animation.fromValue = 1.0
animation.toValue = 0.0
animation.autoreverses = true
animation.duration = CFTimeInterval(time)
animation.repeatCount = MAXFLOAT
animation.isRemovedOnCompletion = false
animation.fillMode = kCAFillModeForwards
animation.timingFunction = CAMediaTimingFunction(name:kCAMediaTimingFunctionEaseIn)//没有的话是均匀的动画。
return animation;
}
//MARK: - 是否是中文
class func isIncludeChineseIn(string: String) -> Bool {
for (_, value) in string.characters.enumerated() {
if ("\u{4E00}" <= value && value <= "\u{9FA5}") {
return true
}
}
return false
}
//MARK: - 校验是否是空字符串
class func isBlankString(str: String?) -> Bool {
if str == nil || str!.isEmpty {
return true
}
if str!.trimmingCharacters(in: NSCharacterSet.controlCharacters).isEmpty {
return true
}
return false
}
// MARK: - 判断controller是否正在显示
class func isVisibleWithController(_ controller: UIViewController) -> Bool {
return (controller.isViewLoaded && controller.view.window != nil)
}
// MARK: - 获取token字符串
class func getDeviceTokenStringWithDeviceToken(deviceToken: Data) -> String {
return deviceToken.description.replacingOccurrences(of: "<", with: "").replacingOccurrences(of: ">", with: "").replacingOccurrences(of: " ", with: "")
}
// MARK: - 获取应用版本号
class func checkVersion() {
let infoDic = Bundle.main.infoDictionary!
let currentVersion = (infoDic["CFBundleShortVersionString"] as! String).replacingOccurrences(of: ".", with: "")
let manager = AFHTTPSessionManager.init()
manager.post(kAppVersion_URL, parameters: nil, progress: nil, success: { (task, response) in
if let dic = response as? [String : Any] {
if let results = dic["results"] {
if let resultArray = results as? [[String : Any]] {
if let result = resultArray.first {
if var lastVersion = result["version"] as? String {
lastVersion = lastVersion.replacingOccurrences(of: ".", with: "")
if Int(currentVersion)! > Int(lastVersion)! {
AntManage.isExamine = true
}
}
}
}
}
}
}) { (task, error) in
}
}
// MARK: - 获取设备UUID
class func getUniqueIdentification() -> String {
if UIDevice.current.name == "iPhone Simulator" {
return "G43HHTZUJ5.com.bm.easypass"
} else {
let wrapper = KeychainItemWrapper(identifier: "UUID", accessGroup: "G43HHTZUJ5.com.bm.easypass")
var strUUID = wrapper?.object(forKey: kSecAttrAccount) as? String
if strUUID == nil || (strUUID?.isEmpty)! {
let uuidRef = CFUUIDCreate(kCFAllocatorDefault)
strUUID = CFBridgingRetain(CFUUIDCreateString(kCFAllocatorDefault, uuidRef)) as? String
wrapper?.setObject(strUUID, forKey: kSecAttrAccount)
}
return strUUID!
}
}
}
extension UIView {
@IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.masksToBounds = true
layer.cornerRadius = newValue
}
}
@IBInspectable
var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable
var borderColor: UIColor {
get {
return self.borderColor
}
set {
layer.borderColor = newValue.cgColor
}
}
}
extension UITextField {
@IBInspectable
var leftImage: UIImage {
get {
return self.leftImage
}
set {
let imgView = UIImageView(image: newValue)
imgView.contentMode = .right
imgView.frame = CGRect(x: 0, y: 0, width: newValue.size.width + 8, height: height)
leftView = imgView
leftViewMode = .always
}
}
}
| mit | b73837291e7db30e8d635c0820cb88bb | 34.543689 | 183 | 0.572885 | 4.527205 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Conversation/Content/Cells/ConfigurationMessageCell/Content/Text/ConversationQuoteCell.swift | 1 | 14085 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
import Down
import WireDataModel
import WireCommonComponents
final class ConversationReplyContentView: UIView {
typealias View = ConversationReplyCell
typealias FileSharingRestrictions = L10n.Localizable.FeatureConfig.FileSharingRestrictions
typealias MessagePreview = L10n.Localizable.Conversation.InputBar.MessagePreview
let numberOfLinesLimit: Int = 4
struct Configuration {
enum Content {
case text(NSAttributedString)
case imagePreview(thumbnail: PreviewableImageResource, isVideo: Bool)
}
var quotedMessage: ZMConversationMessage?
var showDetails: Bool {
guard let message = quotedMessage,
(message.isText
|| message.isLocation
|| message.isAudio
|| message.isImage
|| message.isVideo
|| message.isFile) else {
return false
}
return true
}
var isEdited: Bool {
return quotedMessage?.updatedAt != nil
}
var senderName: String? {
return quotedMessage?.senderName
}
var timestamp: String? {
return quotedMessage?.formattedOriginalReceivedDate()
}
var showRestriction: Bool {
guard let message = quotedMessage,
!message.canBeShared else {
return false
}
return true
}
var restrictionDescription: String? {
guard let message = quotedMessage,
!message.canBeShared else {
return nil
}
if message.isAudio {
return FileSharingRestrictions.audio
} else if message.isImage {
return FileSharingRestrictions.picture
} else if message.isVideo {
return FileSharingRestrictions.video
} else if message.isFile {
return FileSharingRestrictions.file
} else {
return nil
}
}
var content: Content {
return setupContent()
}
var contentType: String {
guard let message = quotedMessage else {
return "quote.type.unavailable"
}
return "quote.type.\(message.typeString)"
}
private func setupContent() -> Content {
let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.smallSemiboldFont,
.foregroundColor: UIColor.from(scheme: .textForeground)]
switch quotedMessage {
case let message? where message.isText:
let data = message.textMessageData!
return .text(NSAttributedString.formatForPreview(message: data, inputMode: false))
case let message? where message.isLocation:
let location = message.locationMessageData!
let imageIcon = NSTextAttachment.textAttachment(for: .locationPin, with: .from(scheme: .textForeground))
let initialString = NSAttributedString(attachment: imageIcon) + " " + (location.name ?? MessagePreview.location).localizedUppercase
return .text(initialString && attributes)
case let message? where message.isAudio:
let imageIcon = NSTextAttachment.textAttachment(for: .microphone, with: .from(scheme: .textForeground))
let initialString = NSAttributedString(attachment: imageIcon) + " " + MessagePreview.audio.localizedUppercase
return .text(initialString && attributes)
case let message? where message.isImage && !message.canBeShared:
let imageIcon = NSTextAttachment.textAttachment(for: .photo, with: .from(scheme: .textForeground))
let initialString = NSAttributedString(attachment: imageIcon) + " " + MessagePreview.image.localizedUppercase
return .text(initialString && attributes)
case let message? where message.isImage:
return .imagePreview(thumbnail: message.imageMessageData!.image, isVideo: false)
case let message? where message.isVideo && !message.canBeShared:
let imageIcon = NSTextAttachment.textAttachment(for: .camera, with: .from(scheme: .textForeground))
let initialString = NSAttributedString(attachment: imageIcon) + " " + MessagePreview.video.localizedUppercase
return .text(initialString && attributes)
case let message? where message.isVideo:
return .imagePreview(thumbnail: message.fileMessageData!.thumbnailImage, isVideo: true)
case let message? where message.isFile:
let fileData = message.fileMessageData!
let imageIcon = NSTextAttachment.textAttachment(for: .document, with: .from(scheme: .textForeground))
let initialString = NSAttributedString(attachment: imageIcon) + " " + (fileData.filename ?? MessagePreview.file).localizedUppercase
return .text(initialString && attributes)
default:
let attributes: [NSAttributedString.Key: AnyObject] = [.font: UIFont.mediumFont.italic,
.foregroundColor: UIColor.from(scheme: .textDimmed)]
return .text(NSAttributedString(string: "content.message.reply.broken_message".localized,
attributes: attributes))
}
}
}
let senderComponent = SenderNameCellComponent()
let contentTextView = UITextView()
let timestampLabel = UILabel()
let restrictionLabel = UILabel()
let assetThumbnail = ImageResourceThumbnailView()
let stackView = UIStackView()
override init(frame: CGRect) {
super.init(frame: frame)
configureSubviews()
configureConstraints()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init?(coder aDecoder: NSCoder) is not implemented")
}
private func configureSubviews() {
shouldGroupAccessibilityChildren = false
stackView.axis = .vertical
stackView.alignment = .leading
stackView.spacing = 6
addSubview(stackView)
senderComponent.label.accessibilityIdentifier = "original.sender"
senderComponent.indicatorView.accessibilityIdentifier = "original.edit_icon"
senderComponent.label.font = .mediumSemiboldFont
senderComponent.label.textColor = .from(scheme: .textForeground)
stackView.addArrangedSubview(senderComponent)
contentTextView.textContainer.lineBreakMode = .byTruncatingTail
contentTextView.textContainer.maximumNumberOfLines = numberOfLinesLimit
contentTextView.textContainer.lineFragmentPadding = 0
contentTextView.isScrollEnabled = false
contentTextView.isUserInteractionEnabled = false
contentTextView.textContainerInset = .zero
contentTextView.isEditable = false
contentTextView.isSelectable = false
contentTextView.backgroundColor = .clear
contentTextView.textColor = .from(scheme: .textForeground)
contentTextView.setContentCompressionResistancePriority(.defaultHigh, for: .vertical)
stackView.addArrangedSubview(contentTextView)
restrictionLabel.accessibilityIdentifier = "original.restriction"
restrictionLabel.font = .smallLightFont
restrictionLabel.textColor = .from(scheme: .textDimmed)
stackView.addArrangedSubview(restrictionLabel)
assetThumbnail.shape = .rounded(radius: 4)
assetThumbnail.setContentCompressionResistancePriority(.required, for: .vertical)
stackView.addArrangedSubview(assetThumbnail)
timestampLabel.accessibilityIdentifier = "original.timestamp"
timestampLabel.font = .mediumFont
timestampLabel.textColor = .from(scheme: .textDimmed)
timestampLabel.numberOfLines = 1
timestampLabel.setContentCompressionResistancePriority(.required, for: .vertical)
stackView.addArrangedSubview(timestampLabel)
}
private func configureConstraints() {
stackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 12),
stackView.topAnchor.constraint(equalTo: topAnchor, constant: 12),
stackView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
stackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -12),
assetThumbnail.heightAnchor.constraint(lessThanOrEqualToConstant: 140),
contentTextView.widthAnchor.constraint(equalTo: stackView.widthAnchor)
])
}
func configure(with object: Configuration) {
senderComponent.isHidden = !object.showDetails
timestampLabel.isHidden = !object.showDetails
restrictionLabel.isHidden = !object.showRestriction
senderComponent.senderName = object.senderName
senderComponent.indicatorIcon = object.isEdited ? StyleKitIcon.pencil.makeImage(size: 8, color: SemanticColors.Icon.foregroundDefault) : nil
senderComponent.indicatorLabel = object.isEdited ? "content.message.reply.edited_message".localized : nil
timestampLabel.text = object.timestamp
restrictionLabel.text = object.restrictionDescription?.localizedUppercase
switch object.content {
case .text(let attributedContent):
let mutableAttributedContent = NSMutableAttributedString(attributedString: attributedContent)
// Trim the string to first four lines to prevent last line narrower spacing issue
mutableAttributedContent.paragraphTailTruncated()
contentTextView.attributedText = mutableAttributedContent.trimmedToNumberOfLines(numberOfLinesLimit: numberOfLinesLimit)
contentTextView.isHidden = false
contentTextView.accessibilityIdentifier = object.contentType
contentTextView.isAccessibilityElement = true
assetThumbnail.isHidden = true
assetThumbnail.isAccessibilityElement = false
case .imagePreview(let resource, let isVideo):
assetThumbnail.setResource(resource, isVideoPreview: isVideo)
assetThumbnail.isHidden = false
assetThumbnail.accessibilityIdentifier = object.contentType
assetThumbnail.isAccessibilityElement = true
contentTextView.isHidden = true
contentTextView.isAccessibilityElement = false
}
}
}
class ConversationReplyCell: UIView, ConversationMessageCell {
typealias Configuration = ConversationReplyContentView.Configuration
var isSelected: Bool = false
let contentView: ConversationReplyContentView
var container: ReplyRoundCornersView
weak var delegate: ConversationMessageCellDelegate?
weak var message: ZMConversationMessage?
override init(frame: CGRect) {
contentView = ConversationReplyContentView()
container = ReplyRoundCornersView(containedView: contentView)
super.init(frame: frame)
configureSubviews()
configureConstraints()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configureSubviews() {
container.addTarget(self, action: #selector(onTap), for: .touchUpInside)
addSubview(container)
}
private func configureConstraints() {
container.translatesAutoresizingMaskIntoConstraints = false
container.fitIn(view: self)
}
func configure(with object: Configuration, animated: Bool) {
contentView.configure(with: object)
}
@objc func onTap() {
delegate?.perform(action: .openQuote, for: message, view: self)
}
}
final class ConversationReplyCellDescription: ConversationMessageCellDescription {
typealias View = ConversationReplyCell
let configuration: View.Configuration
var showEphemeralTimer: Bool = false
var topMargin: Float = 8
let isFullWidth = false
let supportsActions = false
let containsHighlightableContent: Bool = true
weak var message: ZMConversationMessage?
weak var delegate: ConversationMessageCellDelegate?
weak var actionController: ConversationMessageActionController?
let accessibilityLabel: String? = "content.message.original_label".localized
let accessibilityIdentifier: String? = "ReplyCell"
init(quotedMessage: ZMConversationMessage?) {
configuration = View.Configuration(quotedMessage: quotedMessage)
}
}
private extension ZMConversationMessage {
var typeString: String {
if isText {
return "text"
} else if isLocation {
return "location"
} else if isAudio {
return "audio"
} else if isImage {
return "image"
} else if isVideo {
return "video"
} else if isFile {
return "file"
} else {
return "unavailable"
}
}
}
| gpl-3.0 | b61d49b0b74f5c589bba5964f2491547 | 39.826087 | 148 | 0.664537 | 5.695512 | false | true | false | false |
xiaoxinghu/swift-org | Sources/Tokens.swift | 1 | 4088 | //
// Tokens.swift
// SwiftOrg
//
// Created by Xiaoxing Hu on 13/09/16.
// Copyright © 2016 Xiaoxing Hu. All rights reserved.
//
import Foundation
public struct TokenMeta {
public let raw: String?
public let lineNumber: Int
}
typealias TokenInfo = (TokenMeta, Token)
public enum Token {
case setting(key: String, value: String?)
case headline(stars: Int, text: String?)
case planning(keyword: PlanningKeyword, timestamp: Timestamp?)
case blank
case horizontalRule
case blockBegin(name: String, params: [String]?)
case blockEnd(name: String)
case drawerBegin(name: String)
case drawerEnd
case listItem(indent: Int, text: String?, ordered: Bool, checked: Bool?)
case comment(String?)
case line(text: String)
case footnote(label: String, content: String?)
case tableRow(cells: [String])
case horizontalSeparator
case raw(String)
}
typealias TokenGenerator = ([String?]) -> Token
struct TokenDescriptor {
let pattern: String
let options: RegularExpression.Options
let generator: TokenGenerator
init(_ thePattern: String,
options theOptions: RegularExpression.Options = [],
generator theGenerator: @escaping TokenGenerator = { matches in .raw(matches[0]!) }) {
pattern = thePattern
options = theOptions
generator = theGenerator
}
}
func define(_ pattern: String,
options: RegularExpression.Options = [],
generator: @escaping TokenGenerator) {
tokenDescriptors.append(
TokenDescriptor(pattern,
options: options,
generator: generator))
}
var tokenDescriptors: [TokenDescriptor] = []
func defineTokens() {
if tokenDescriptors.count > 0 {return}
define("^\\s*$") { _ in .blank }
define("^#\\+([a-zA-Z_]+):\\s*(.*)$") { matches in
.setting(key: matches[1]!, value: matches[2]) }
define("^(\\*+)\\s+(.*)$") { matches in
.headline(stars: matches[1]!.characters.count, text: matches[2]) }
define("^\\s*(\(PlanningKeyword.all.joined(separator: "|"))):\\s+(.+)$") { matches in
let timestamp = Timestamp.from(string: matches[2]!)
return .planning(keyword: PlanningKeyword(rawValue: matches[1]!)!, timestamp: timestamp)
}
// Block
define("^(\\s*)#\\+begin_([a-z]+)(?:\\s+(.*))?$",
options: [.caseInsensitive])
{ matches in
var params: [String]?
if let m3 = matches[3] {
params = m3.characters.split{$0 == " "}.map(String.init)
}
return .blockBegin(name: matches[2]!, params: params)
}
define("^(\\s*)#\\+end_([a-z]+)$", options: [.caseInsensitive]) { matches in
.blockEnd(name: matches[2]!) }
// Drawer
define("^(\\s*):end:\\s*$", options: [.caseInsensitive]) { _ in .drawerEnd }
define("^(\\s*):([a-z]+):\\s*$",
options: [.caseInsensitive]) { matches in
.drawerBegin(name: matches[2]!) }
define("^(\\s*)([-+*]|\\d+(?:\\.|\\)))\\s+(?:\\[([ X-])\\]\\s+)?(.*)$") { matches in
var ordered = true
if let m = matches[2] {
ordered = !["-", "+", "*"].contains(m)
}
var checked: Bool? = nil
if let m = matches[3] {
checked = m == "X"
}
return .listItem(indent: length(matches[1]), text: matches[4], ordered: ordered, checked: checked) }
define("^\\s*-{5,}$") { _ in .horizontalRule }
define("^\\s*#\\s+(.*)$") { matches in
.comment(matches[1]) }
define("^\\[fn:(\\d+)\\](?:\\s+(.*))?$") { matches in
.footnote(label: matches[1]!, content: matches[2])
}
// Table
define("\\s*\\|-.*$") { matches in
return .horizontalSeparator
}
define("^\\s*\\|(?:[^\\r\\n\\|]*\\|?)+$") { matches in
let cells = matches[0]!
.components(separatedBy: "|")
.map { $0.trimmed }
.filter { !$0.isEmpty }
return .tableRow(cells: cells)
}
define("^(\\s*)(.*)$") { matches in
.line(text: matches[2]!) }
}
| mit | b2b36c171da0955ed68b4b0ae7be7b20 | 28.192857 | 108 | 0.556398 | 3.837559 | false | false | false | false |
The-iPocalypse/BA-iOS-Application | src/BASubscriptionViewController.swift | 1 | 1476 | //
// BASubscriptionViewController.swift
// BA-iOS-Application
//
// Created by Maxime Mongeau on 2016-02-13.
// Copyright © 2016 Samuel Bellerose. All rights reserved.
//
import UIKit
class BASubscriptionViewController: UIViewController {
var goodDeed: GoodDeed?
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var descTextView: UITextView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var dateDebutLabel: UILabel!
@IBOutlet weak var dateFinLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
if let gd = goodDeed {
self.title = gd.title
let formatter = NSDateFormatter()
formatter.dateFormat = "YYYY/MM/dd - HH:mm"
self.descTextView.text = gd.desc
self.dateDebutLabel.text = formatter.stringFromDate(gd.startDate)
self.dateFinLabel.text = formatter.stringFromDate(gd.endDate)
self.usernameLabel.text = gd.creator.name
self.imageView.image = UIImage(named: gd.creator.name.lowercaseString)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cancelTapped(sender: UIBarButtonItem) {
self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func propositionTapped() {
}
}
| mit | 51cd95bf8382e088147fa0a34311b756 | 29.729167 | 91 | 0.668475 | 4.638365 | false | false | false | false |
sachin004/firefox-ios | Client/Frontend/Settings/ClearPrivateDataTableViewController.swift | 2 | 5854 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
private let SectionToggles = 0
private let SectionButton = 1
private let NumberOfSections = 2
private let SectionHeaderFooterIdentifier = "SectionHeaderFooterIdentifier"
private let HeaderFooterHeight: CGFloat = 44
private let TogglesPrefKey = "clearprivatedata.toggles"
private let log = Logger.browserLogger
class ClearPrivateDataTableViewController: UITableViewController {
private var clearButton: UITableViewCell?
var profile: Profile!
var tabManager: TabManager!
private typealias DefaultCheckedState = Bool
private lazy var clearables: [(clearable: Clearable, checked: DefaultCheckedState)] = {
return [
(HistoryClearable(profile: self.profile), true),
(CacheClearable(tabManager: self.tabManager), true),
(CookiesClearable(tabManager: self.tabManager), true),
(SiteDataClearable(tabManager: self.tabManager), true),
]
}()
private lazy var toggles: [Bool] = {
if let savedToggles = self.profile.prefs.arrayForKey(TogglesPrefKey) as? [Bool] {
return savedToggles
}
return self.clearables.map { $0.checked }
}()
private var clearButtonEnabled = true {
didSet {
clearButton?.textLabel?.textColor = clearButtonEnabled ? UIConstants.DestructiveRed : UIColor.lightGrayColor()
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("Clear Private Data", tableName: "ClearPrivateData", comment: "Navigation title in settings.")
tableView.registerClass(SettingsTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderFooterIdentifier)
tableView.separatorColor = UIConstants.TableViewSeparatorColor
tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
let footer = SettingsTableSectionHeaderFooterView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: HeaderFooterHeight))
footer.showBottomBorder = false
tableView.tableFooterView = footer
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
if indexPath.section == SectionToggles {
cell.textLabel?.text = clearables[indexPath.item].clearable.label
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
control.on = toggles[indexPath.item]
cell.accessoryView = control
cell.selectionStyle = .None
control.tag = indexPath.item
} else {
assert(indexPath.section == SectionButton)
cell.textLabel?.text = NSLocalizedString("Clear Private Data", tableName: "ClearPrivateData", comment: "Button in settings that clears private data for the selected items.")
cell.textLabel?.textAlignment = NSTextAlignment.Center
cell.textLabel?.textColor = UIConstants.DestructiveRed
cell.accessibilityTraits = UIAccessibilityTraitButton
clearButton = cell
}
return cell
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return NumberOfSections
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == SectionToggles {
return clearables.count
}
assert(section == SectionButton)
return 1
}
override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
guard indexPath.section == SectionButton else { return false }
// Highlight the button only if it's enabled.
return clearButtonEnabled
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
guard indexPath.section == SectionButton else { return }
let toggles = self.toggles
clearables
.enumerate()
.flatMap { (i, pair) in
guard toggles[i] else {
return nil
}
log.debug("Clearing \(pair.clearable).")
return pair.clearable.clear()
}
.allSucceed()
.upon { result in
assert(result.isSuccess, "Private data cleared successfully")
self.profile.prefs.setObject(self.toggles, forKey: TogglesPrefKey)
dispatch_async(dispatch_get_main_queue()) {
// Disable the Clear Private Data button after it's clicked.
self.clearButtonEnabled = false
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionHeaderFooterIdentifier) as! SettingsTableSectionHeaderFooterView
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return HeaderFooterHeight
}
@objc func switchValueChanged(toggle: UISwitch) {
toggles[toggle.tag] = toggle.on
// Dim the clear button if no clearables are selected.
clearButtonEnabled = toggles.contains(true)
}
} | mpl-2.0 | a3a4fe39fdd171d63a7f7f67e032399a | 38.829932 | 185 | 0.675777 | 5.585878 | false | false | false | false |
cameronklein/SwiftPasscodeLock | PasscodeLock/Views/PasscodeSignButton.swift | 4 | 2421 | //
// PasscodeSignButton.swift
// PasscodeLock
//
// Created by Yanko Dimitrov on 8/28/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import UIKit
@IBDesignable
public class PasscodeSignButton: UIButton {
@IBInspectable
public var passcodeSign: String = "1"
@IBInspectable
public var borderColor: UIColor = UIColor.whiteColor() {
didSet {
setupView()
}
}
@IBInspectable
public var borderRadius: CGFloat = 30 {
didSet {
setupView()
}
}
@IBInspectable
public var highlightBackgroundColor: UIColor = UIColor.clearColor() {
didSet {
setupView()
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
setupView()
setupActions()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupActions()
}
public override func intrinsicContentSize() -> CGSize {
return CGSizeMake(60, 60)
}
private var defaultBackgroundColor = UIColor.clearColor()
private func setupView() {
layer.borderWidth = 1
layer.cornerRadius = borderRadius
layer.borderColor = borderColor.CGColor
if let backgroundColor = backgroundColor {
defaultBackgroundColor = backgroundColor
}
}
private func setupActions() {
addTarget(self, action: Selector("handleTouchDown"), forControlEvents: .TouchDown)
addTarget(self, action: Selector("handleTouchUp"), forControlEvents: [.TouchUpInside, .TouchDragOutside, .TouchCancel])
}
func handleTouchDown() {
animateBackgroundColor(highlightBackgroundColor)
}
func handleTouchUp() {
animateBackgroundColor(defaultBackgroundColor)
}
private func animateBackgroundColor(color: UIColor) {
UIView.animateWithDuration(
0.3,
delay: 0.0,
usingSpringWithDamping: 1,
initialSpringVelocity: 0.0,
options: [.AllowUserInteraction, .BeginFromCurrentState],
animations: {
self.backgroundColor = color
},
completion: nil
)
}
}
| mit | fb99808f0c19caa25c7d3d58dd0804c4 | 22.495146 | 127 | 0.570661 | 5.803357 | false | false | false | false |
StefanKruger/WiLibrary | Pod/Classes/ImageLoader/Core/Nuke.swift | 2 | 2023 | // The MIT License (MIT)
//
// Copyright (c) 2015 Alexander Grebenyuk (github.com/kean).
import Foundation
// MARK: - Convenience
/** Creates a task with a given URL. After you create a task, you start it by calling its resume method.
*/
public func taskWithURL(URL: NSURL, completion: ImageTaskCompletion? = nil) -> ImageTask {
return ImageManager.shared.taskWithURL(URL, completion: completion)
}
/** Creates a task with a given request. After you create a task, you start it by calling its resume method.
*/
public func taskWithRequest(request: ImageRequest, completion: ImageTaskCompletion? = nil) -> ImageTask {
return ImageManager.shared.taskWithRequest(request, completion: completion)
}
/** Prepares images for the given requests for later use.
When you call this method, ImageManager starts to load and cache images for the given requests. ImageManager caches images with the exact target size, content mode, and filters. At any time afterward, you can create tasks with equivalent requests.
*/
public func startPreheatingImages(requests: [ImageRequest]) {
ImageManager.shared.startPreheatingImages(requests)
}
/** Stop preheating for the given requests. The request parameters should match the parameters used in startPreheatingImages method.
*/
public func stopPreheatingImages(requests: [ImageRequest]) {
ImageManager.shared.stopPreheatingImages(requests)
}
/** Stops all preheating tasks.
*/
public func stopPreheatingImages() {
ImageManager.shared.stopPreheatingImages()
}
// MARK: - Internal
#if os(OSX)
import Cocoa
public typealias Image = NSImage
#else
import UIKit
public typealias Image = UIImage
#endif
internal func dispathOnMainThread(closure: (Void) -> Void) {
NSThread.isMainThread() ? closure() : dispatch_async(dispatch_get_main_queue(), closure)
}
internal extension NSOperationQueue {
convenience init(maxConcurrentOperationCount: Int) {
self.init()
self.maxConcurrentOperationCount = maxConcurrentOperationCount
}
}
| mit | 9e0bce10e0a11021e2d39b451c2c225f | 32.163934 | 247 | 0.757785 | 4.556306 | false | false | false | false |
Ossey/WUO-iOS | WUO/WUO/Classes/Trend/View/XYConstant-Swift.swift | 1 | 3901 | //
// XYConstant-Swift.swift
// WUO
//
// Created by mofeini on 17/1/19.
// Copyright © 2017年 com.test.demo. All rights reserved.
//
import UIKit
/*************** 颜色 ***************/
func COLOR(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> UIColor {
return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)
}
func RANDOM_COLOR() -> UIColor {
return COLOR(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)), a: 1.0)
}
// title文本的颜色
func COLOR_TITLE_TEXT() -> UIColor {
return COLOR(r: 25, g: 25, b: 25, a: 1.0);
}
// content文本颜色
func COLOR_CONTENT_TEXT() -> UIColor {
return COLOR(r: 125, g: 125, b: 125, a: 1.0)
}
// job文本颜色
func COLOR_JOB_TEXT() -> UIColor {
return COLOR(r: 94, g: 167, b: 86, a: 1.0)
}
// 昵称name文本颜色
func COLOR_NAME_TEXT() -> UIColor {
return COLOR_NAME_TEXT_BLACK()
}
// 昵称name文本颜色 浅蓝色
func COLOR_NAME_TEXT_BLUE() -> UIColor {
return COLOR(r: 106, g: 140, b: 181, a: 1.0)
}
// name文字颜色 黑色
func COLOR_NAME_TEXT_BLACK() -> UIColor {
return COLOR(r: 10, g: 101, b: 10, a: 1.0)
}
// 浅蓝色
func COLOR_LIGHTBLUE() -> UIColor {
return COLOR(r: 106, g: 140, b: 181, a: 1.0)
}
// 分隔符的颜色
func COLOR_SEPARATOR() -> UIColor {
return COLOR(r: 140, g: 140, b: 140, a: 0.6)
}
// cell的全局颜色
func COLOR_GLOBAL_CELL() -> UIColor {
return COLOR(r: 250, g: 250, b: 250, a: 1.0)
}
// 灰色
func COLOR_LIGHTGRAY() -> UIColor {
return COLOR(r: 180, g: 180, b: 180, a: 1.0)
}
// 绿色
func COLOR_GLOBAL_GREEN() -> UIColor {
return COLOR(r: 47, g: 189, b: 169, a: 1.0)
}
func SCREENT_W() -> CGFloat {
return UIScreen.main.bounds.size.width
}
/*************** 动态界面 ***************/
let SIZE_CONTENT_W = SCREENT_W() - SIZE_GAP_MARGIN * 2 - SIZE_HEADERWH - SIZE_GAP_PADDING
let SIZE_SEPARATORH : CGFloat = 5.0 // 分割线高度
let SIZE_TOOLVIEWH : CGFloat = 40.0 // 工具条高度
let SIZE_GAP_MARGIN : CGFloat = 15.0 // 全局外间距
let SIZE_GAP_TOP : CGFloat = 13.0 // 全局顶部间距
let SIZE_HEADERWH : CGFloat = 50.0 // 头像尺寸
let SIZE_GAP_PADDING : CGFloat = 10.0 // 内间距
let SIZE_PIC_BOTTOM : CGFloat = 20.0 // 图片底部间距
let SIZE_GAP_SMALL : CGFloat = 5.0 // 最小的间距
let SIZE_PICMARGIN : CGFloat = 5.0 // 每张图片之间的间距
let SIZE_PICWH : CGFloat = 80.0 // 单张图片宽度
let SIZE_FONT : CGFloat = 17.0 // 字体大小
let SIZE_FONT_NAME = SIZE_FONT - 1 // 昵称字体大小
let SIZE_FONT_SUBTITLE = SIZE_FONT-8 // job及创建日期字体大小
let SIZE_FONT_TITLE : CGFloat = 15.0 // 标题字体大小
let SIZE_FONT_LOCATION : CGFloat = SIZE_FONT - 5 // 标题字体大小
let SIZE_FONT_CONTENT = (SIZE_FONT_TITLE-3) // 内容文本字体大小
let COLOR_COUNT_TEXT = COLOR(r: 205, g: 205, b: 205, a: 1.0) // 工具条的各种数量文本颜色
let COLOR_READCOUNT_TEXT = COLOR(r: 180, g: 180, b: 180, a: 1.0) // 阅读文本数量颜色
let SIZE_TREND_DETAIL_SELECTVIEW_H : CGFloat = 35.0
let COLOR_INVEST_SEARCH_BG = COLOR(r: 211, g: 211, b: 211, a: 1.0)
let COLOR_TABLEVIEW_BG = COLOR(r: 238, g: 238, b: 238, a: 238) // 所有tableView的背景颜色
let SIZE_INVESET_HEADERVIEW_H : CGFloat = 260.0
/** 全局字体 */
func FontWithSize(s: CGFloat) -> UIFont {
return UIFont.init(name: "HelveticaNeue-Light", size: s)!
}
let TableViewBgColor = COLOR(r: 238, g: 238, b: 238, a: 1.0) // 所有tableView的背景颜色
| apache-2.0 | 0ed0c9d29badeac1bc1ecd336edb7716 | 29.877193 | 135 | 0.565909 | 2.827309 | false | false | false | false |
gkye/TheMovieDatabaseSwiftWrapper | Tests/TMDBSwiftTests/Models/MovieTests.swift | 1 | 10844 | @testable import TMDBSwift
import XCTest
private let data = """
{
"adult": false,
"backdrop_path": "/jBFxXKCrViA88hhO59fDx0Av4P.jpg",
"belongs_to_collection": {
"id": 10,
"name": "Star Wars Collection",
"poster_path": "/bYbHqvRANCpuRTs0RAu10LhmVKU.jpg",
"backdrop_path": "/d8duYyyC9J5T825Hg7grmaabfxQ.jpg"
},
"budget": 11000000,
"genres": [
{
"id": 12,
"name": "Adventure"
},
{
"id": 28,
"name": "Action"
},
{
"id": 878,
"name": "Science Fiction"
}
],
"homepage": "http://www.starwars.com/films/star-wars-episode-iv-a-new-hope",
"id": 11,
"imdb_id": "tt0076759",
"original_language": "en",
"original_title": "Star Wars",
"overview": "Princess Leia is captured and held hostage by the evil Imperial forces in their effort to take over the galactic Empire. Venturesome Luke Skywalker and dashing captain Han Solo team together with the loveable robot duo R2-D2 and C-3PO to rescue the beautiful princess and restore peace and justice in the Empire.",
"popularity": 138.085,
"poster_path": "/6FfCtAuVAW8XJjZ7eWeLibRLWTw.jpg",
"production_companies": [
{
"id": 1,
"logo_path": "/o86DbpburjxrqAzEDhXZcyE8pDb.png",
"name": "Lucasfilm Ltd.",
"origin_country": "US"
},
{
"id": 25,
"logo_path": "/qZCc1lty5FzX30aOCVRBLzaVmcp.png",
"name": "20th Century Fox",
"origin_country": "US"
}
],
"production_countries": [
{
"iso_3166_1": "US",
"name": "United States of America"
}
],
"release_date": "1977-05-25",
"revenue": 775398007,
"runtime": 121,
"spoken_languages": [
{
"english_name": "English",
"iso_639_1": "en",
"name": "English"
}
],
"status": "Released",
"tagline": "A long time ago in a galaxy far, far away...",
"title": "Star Wars",
"video": false,
"vote_average": 8.2,
"vote_count": 17375
}
"""
private let dataWithGenreIDs = """
{
"adult": false,
"backdrop_path": "/jBFxXKCrViA88hhO59fDx0Av4P.jpg",
"belongs_to_collection": {
"id": 10,
"name": "Star Wars Collection",
"poster_path": "/bYbHqvRANCpuRTs0RAu10LhmVKU.jpg",
"backdrop_path": "/d8duYyyC9J5T825Hg7grmaabfxQ.jpg"
},
"budget": 11000000,
"genre_ids": [
12,
28,
878
],
"homepage": "http://www.starwars.com/films/star-wars-episode-iv-a-new-hope",
"id": 11,
"imdb_id": "tt0076759",
"media_type": "movie",
"original_language": "en",
"original_title": "Star Wars",
"overview": "Princess Leia is captured and held hostage by the evil Imperial forces in their effort to take over the galactic Empire. Venturesome Luke Skywalker and dashing captain Han Solo team together with the loveable robot duo R2-D2 and C-3PO to rescue the beautiful princess and restore peace and justice in the Empire.",
"popularity": 138.085,
"poster_path": "/6FfCtAuVAW8XJjZ7eWeLibRLWTw.jpg",
"production_companies": [
{
"id": 1,
"logo_path": "/o86DbpburjxrqAzEDhXZcyE8pDb.png",
"name": "Lucasfilm Ltd.",
"origin_country": "US"
},
{
"id": 25,
"logo_path": "/qZCc1lty5FzX30aOCVRBLzaVmcp.png",
"name": "20th Century Fox",
"origin_country": "US"
}
],
"production_countries": [
{
"iso_3166_1": "US",
"name": "United States of America"
}
],
"release_date": "1977-05-25",
"revenue": 775398007,
"runtime": 121,
"spoken_languages": [
{
"english_name": "English",
"iso_639_1": "en",
"name": "English"
}
],
"status": "Released",
"tagline": "A long time ago in a galaxy far, far away...",
"title": "Star Wars",
"video": false,
"vote_average": 8.2,
"vote_count": 17375
}
"""
final class MovieTests: XCTestCase {
func testEncode() throws {
let movie = try JSONDecoder().decode(Movie.self, from: data.data(using: .utf8)!)
let encodedData = try JSONEncoder().encode(movie)
let decodedMovie = try JSONDecoder().decode(Movie.self, from: encodedData)
XCTAssertEqual(movie, decodedMovie)
}
func testDecode() throws {
let jsonDecoder = JSONDecoder()
let movie = try jsonDecoder.decode(Movie.self, from: data.data(using: .utf8)!)
XCTAssertEqual(movie.id, 11)
XCTAssertEqual(movie.adult, false)
XCTAssertEqual(movie.backdropPath, "/jBFxXKCrViA88hhO59fDx0Av4P.jpg")
XCTAssertEqual(movie.budget, 11000000)
XCTAssertEqual(movie.collection, Collection(id: 10,
name: "Star Wars Collection",
backdropPath: "/d8duYyyC9J5T825Hg7grmaabfxQ.jpg",
posterPath: "/bYbHqvRANCpuRTs0RAu10LhmVKU.jpg"))
XCTAssertEqual(movie.genres, [Genre(id: 12, name: "Adventure"),
Genre(id: 28, name: "Action"),
Genre(id: 878, name: "Science Fiction")])
XCTAssertEqual(movie.homepage, "http://www.starwars.com/films/star-wars-episode-iv-a-new-hope")
XCTAssertEqual(movie.imdbID, .imdb("tt0076759"))
XCTAssertEqual(movie.originalLanguage, .en)
XCTAssertEqual(movie.originalTitle, "Star Wars")
XCTAssertEqual(movie.overview, "Princess Leia is captured and held hostage by the evil Imperial forces in their effort to take over the galactic Empire. Venturesome Luke Skywalker and dashing captain Han Solo team together with the loveable robot duo R2-D2 and C-3PO to rescue the beautiful princess and restore peace and justice in the Empire.")
XCTAssertEqual(movie.popularity, 138.085)
XCTAssertEqual(movie.posterPath, "/6FfCtAuVAW8XJjZ7eWeLibRLWTw.jpg")
XCTAssertEqual(movie.productionCompanies, [Company(id: 1,
logoPath: "/o86DbpburjxrqAzEDhXZcyE8pDb.png",
name: "Lucasfilm Ltd.",
originCountry: "US"),
Company(id: 25,
logoPath: "/qZCc1lty5FzX30aOCVRBLzaVmcp.png",
name: "20th Century Fox",
originCountry: "US")])
XCTAssertEqual(movie.productionCountries, [.US])
XCTAssertEqual(movie.releaseDate, Calendar.current.date(from: DateComponents(year: 1977, month: 5, day: 25)))
XCTAssertEqual(movie.revenue, 775398007)
XCTAssertEqual(movie.runtime, 121)
XCTAssertEqual(movie.spokenLanguages, [.en])
XCTAssertEqual(movie.status, "Released")
XCTAssertEqual(movie.tagline, "A long time ago in a galaxy far, far away...")
XCTAssertEqual(movie.title, "Star Wars")
XCTAssertEqual(movie.video, false)
XCTAssertEqual(movie.voteAverage, 8.2)
XCTAssertEqual(movie.voteCount, 17375)
}
func testEncode_WithGenreIDs() throws {
let movie = try JSONDecoder().decode(Movie.self, from: dataWithGenreIDs.data(using: .utf8)!)
let encodedData = try JSONEncoder().encode(movie)
let decodedMovie = try JSONDecoder().decode(Movie.self, from: encodedData)
XCTAssertEqual(movie, decodedMovie)
}
func testDecode_WithGenreIDs() throws {
let jsonDecoder = JSONDecoder()
let movie = try jsonDecoder.decode(Movie.self, from: dataWithGenreIDs.data(using: .utf8)!)
XCTAssertEqual(movie.id, 11)
XCTAssertEqual(movie.adult, false)
XCTAssertEqual(movie.backdropPath, "/jBFxXKCrViA88hhO59fDx0Av4P.jpg")
XCTAssertEqual(movie.budget, 11000000)
XCTAssertEqual(movie.collection, Collection(id: 10,
name: "Star Wars Collection",
backdropPath: "/d8duYyyC9J5T825Hg7grmaabfxQ.jpg",
posterPath: "/bYbHqvRANCpuRTs0RAu10LhmVKU.jpg"))
XCTAssertEqual(movie.genres, [Genre(id: 12),
Genre(id: 28),
Genre(id: 878)])
XCTAssertEqual(movie.homepage, "http://www.starwars.com/films/star-wars-episode-iv-a-new-hope")
XCTAssertEqual(movie.imdbID, .imdb("tt0076759"))
XCTAssertEqual(movie.originalLanguage, .en)
XCTAssertEqual(movie.originalTitle, "Star Wars")
XCTAssertEqual(movie.overview, "Princess Leia is captured and held hostage by the evil Imperial forces in their effort to take over the galactic Empire. Venturesome Luke Skywalker and dashing captain Han Solo team together with the loveable robot duo R2-D2 and C-3PO to rescue the beautiful princess and restore peace and justice in the Empire.")
XCTAssertEqual(movie.popularity, 138.085)
XCTAssertEqual(movie.posterPath, "/6FfCtAuVAW8XJjZ7eWeLibRLWTw.jpg")
XCTAssertEqual(movie.productionCompanies, [Company(id: 1,
logoPath: "/o86DbpburjxrqAzEDhXZcyE8pDb.png",
name: "Lucasfilm Ltd.",
originCountry: "US"),
Company(id: 25,
logoPath: "/qZCc1lty5FzX30aOCVRBLzaVmcp.png",
name: "20th Century Fox",
originCountry: "US")])
XCTAssertEqual(movie.productionCountries, [.US])
XCTAssertEqual(movie.releaseDate, Calendar.current.date(from: DateComponents(year: 1977, month: 5, day: 25)))
XCTAssertEqual(movie.revenue, 775398007)
XCTAssertEqual(movie.runtime, 121)
XCTAssertEqual(movie.spokenLanguages, [.en])
XCTAssertEqual(movie.status, "Released")
XCTAssertEqual(movie.tagline, "A long time ago in a galaxy far, far away...")
XCTAssertEqual(movie.title, "Star Wars")
XCTAssertEqual(movie.video, false)
XCTAssertEqual(movie.voteAverage, 8.2)
XCTAssertEqual(movie.voteCount, 17375)
}
}
| mit | 3a865a33701b0e914a8bd85efdca1cf5 | 43.809917 | 354 | 0.562984 | 3.842665 | false | false | false | false |
VBVMI/VerseByVerse-iOS | Pods/VimeoNetworking/VimeoNetworking/Sources/VimeoSessionManager+Constructors.swift | 1 | 7515 | //
// VimeoSessionManager+Constructors.swift
// VimeoNetworkingExample-iOS
//
// Created by Huebner, Rob on 3/29/16.
// Copyright © 2016 Vimeo. All rights reserved.
//
// 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
public extension VimeoSessionManager
{
// MARK: - Default Session Initialization
/**
Creates an authenticated session manager with a static access token
- parameter baseUrl: the base URL for the HTTP client. This value should usually be set to `VimeoBaseURL`.
- parameter accessToken: the static access token to use for request serialization
- returns: an initialized `VimeoSessionManager`
*/
static func defaultSessionManager(baseUrl: URL, accessToken: String) -> VimeoSessionManager
{
let sessionConfiguration = URLSessionConfiguration.defaultSessionConfigurationNoCache()
let requestSerializer = VimeoRequestSerializer(accessTokenProvider: { accessToken })
return VimeoSessionManager(baseUrl: baseUrl, sessionConfiguration: sessionConfiguration, requestSerializer: requestSerializer)
}
/**
Creates a session manager with a block that provides an access token. Note that if no access token is returned by the provider block, no Authorization header will be serialized with new requests, whereas a Basic Authorization header is required at minimum for all api endpoints. For unauthenticated requests, use a constructor that accepts an `AppConfiguration`.
- parameter baseUrl: the base URL for the HTTP client. This value should usually be set to `VimeoBaseURL`.
- parameter accessTokenProvider: a block that provides an access token dynamically, called on each request serialization
- returns: an initialized `VimeoSessionManager`
*/
static func defaultSessionManager(baseUrl: URL, accessTokenProvider: @escaping VimeoRequestSerializer.AccessTokenProvider) -> VimeoSessionManager
{
let sessionConfiguration = URLSessionConfiguration.defaultSessionConfigurationNoCache()
let requestSerializer = VimeoRequestSerializer(accessTokenProvider: accessTokenProvider)
return VimeoSessionManager(baseUrl: baseUrl, sessionConfiguration: sessionConfiguration, requestSerializer: requestSerializer)
}
/**
Creates an unauthenticated session manager with a static application configuration
- parameter appConfiguration: configuration used to generate the basic authentication header
- returns: an initialized `VimeoSessionManager`
*/
static func defaultSessionManager(appConfiguration: AppConfiguration) -> VimeoSessionManager
{
let sessionConfiguration = URLSessionConfiguration.defaultSessionConfigurationNoCache()
let requestSerializer = VimeoRequestSerializer(appConfiguration: appConfiguration)
return VimeoSessionManager(baseUrl: appConfiguration.baseUrl, sessionConfiguration: sessionConfiguration, requestSerializer: requestSerializer)
}
// MARK: - Background Session Initialization
/**
Creates an authenticated background session manager with a static access token
- parameter identifier: the background session identifier
- parameter baseUrl: the base URL for the HTTP client. This value should usually be set to `VimeoBaseURL`.
- parameter accessToken: the static access token to use for request serialization
- returns: an initialized `VimeoSessionManager`
*/
static func backgroundSessionManager(identifier: String, baseUrl: URL, accessToken: String) -> VimeoSessionManager
{
let sessionConfiguration = self.backgroundSessionConfiguration(identifier: identifier)
let requestSerializer = VimeoRequestSerializer(accessTokenProvider: { accessToken })
return VimeoSessionManager(baseUrl: baseUrl, sessionConfiguration: sessionConfiguration, requestSerializer: requestSerializer)
}
/**
Creates a background session manager with a block that provides an access token. Note that if no access token is returned by the provider block, no Authorization header will be serialized with new requests, whereas a Basic Authorization header is required at minimum for all api endpoints. For unauthenticated requests, use a constructor that accepts an `AppConfiguration`.
- parameter identifier: the background session identifier
- parameter baseUrl: the base URL for the HTTP client. This value should usually be set to `VimeoBaseURL`.
- parameter accessTokenProvider: a block that provides an access token dynamically, called on each request serialization
- returns: an initialized `VimeoSessionManager`
*/
static func backgroundSessionManager(identifier: String, baseUrl: URL, accessTokenProvider: @escaping VimeoRequestSerializer.AccessTokenProvider) -> VimeoSessionManager
{
let sessionConfiguration = self.backgroundSessionConfiguration(identifier: identifier)
let requestSerializer = VimeoRequestSerializer(accessTokenProvider: accessTokenProvider)
return VimeoSessionManager(baseUrl: baseUrl, sessionConfiguration: sessionConfiguration, requestSerializer: requestSerializer)
}
/**
Creates an unauthenticated background session manager with a static application configuration
- parameter identifier: the background session identifier
- parameter appConfiguration: configuration used to generate the basic authentication header
- returns: an initialized `VimeoSessionManager`
*/
static func backgroundSessionManager(identifier: String, appConfiguration: AppConfiguration) -> VimeoSessionManager
{
let sessionConfiguration = self.backgroundSessionConfiguration(identifier: identifier)
let requestSerializer = VimeoRequestSerializer(appConfiguration: appConfiguration)
return VimeoSessionManager(baseUrl: appConfiguration.baseUrl, sessionConfiguration: sessionConfiguration, requestSerializer: requestSerializer)
}
// MARK: Private API
// Would prefer that this live in a NSURLSessionConfiguration extension but the method name would conflict [AH] 2/5/2016
private static func backgroundSessionConfiguration(identifier: String) -> URLSessionConfiguration
{
return URLSessionConfiguration.background(withIdentifier: identifier)
}
}
| mit | 973afdecf856b0aead6dce09aef82604 | 52.671429 | 380 | 0.757519 | 5.930545 | false | true | false | false |
babyboy18/swift_code | Swifter/JSON.swift | 1 | 11317 | //
// JSON.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly
//
// 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
public typealias JSONValue = JSON
public let JSONTrue = JSONValue(true)
public let JSONFalse = JSONValue(false)
public let JSONNull = JSONValue.JSONNull
public enum JSON : Equatable, Printable {
case JSONString(Swift.String)
case JSONNumber(Double)
case JSONObject(Dictionary<String, JSONValue>)
case JSONArray(Array<JSON>)
case JSONBool(Bool)
case JSONNull
case JSONInvalid
init(_ value: Bool?) {
if let bool = value {
self = .JSONBool(bool)
}
else {
self = .JSONInvalid
}
}
init(_ value: Double?) {
if let number = value {
self = .JSONNumber(number)
}
else {
self = .JSONInvalid
}
}
init(_ value: Int?) {
if let number = value {
self = .JSONNumber(Double(number))
}
else {
self = .JSONInvalid
}
}
init(_ value: String?) {
if let string = value {
self = .JSONString(string)
}
else {
self = .JSONInvalid
}
}
init(_ value: Array<JSONValue>?) {
if let array = value {
self = .JSONArray(array)
}
else {
self = .JSONInvalid
}
}
init(_ value: Dictionary<String, JSONValue>?) {
if let dict = value {
self = .JSONObject(dict)
}
else {
self = .JSONInvalid
}
}
init(_ rawValue: AnyObject?) {
if let value : AnyObject = rawValue {
switch value {
case let data as NSData:
if let jsonObject : AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) {
self = JSON(jsonObject)
}
else {
self = .JSONInvalid
}
case let array as NSArray:
var newArray : [JSONValue] = []
for item : AnyObject in array {
newArray.append(JSON(item))
}
self = .JSONArray(newArray)
case let dict as NSDictionary:
var newDict : Dictionary<String, JSONValue> = [:]
for (k : AnyObject, v : AnyObject) in dict {
if let key = k as? String {
newDict[key] = JSON(v)
}
else {
assert(true, "Invalid key type; expected String")
self = .JSONInvalid
return
}
}
self = .JSONObject(newDict)
case let string as NSString:
self = .JSONString(string)
case let number as NSNumber:
if number.isBool {
self = .JSONBool(number.boolValue)
}
else {
self = .JSONNumber(number.doubleValue)
}
case let null as NSNull:
self = .JSONNull
default:
assert(true, "This location should never be reached")
self = .JSONInvalid
}
}
else {
self = .JSONInvalid
}
}
public var string : String? {
switch self {
case .JSONString(let value):
return value
default:
return nil
}
}
public var integer : Int? {
switch self {
case .JSONNumber(let value):
return Int(value)
default:
return nil
}
}
public var double : Double? {
switch self {
case .JSONNumber(let value):
return value
default:
return nil
}
}
public var object : Dictionary<String, JSONValue>? {
switch self {
case .JSONObject(let value):
return value
default:
return nil
}
}
public var array : Array<JSONValue>? {
switch self {
case .JSONArray(let value):
return value
default:
return nil
}
}
public var bool : Bool? {
switch self {
case .JSONBool(let value):
return value
default:
return nil
}
}
public subscript(key: String) -> JSONValue {
switch self {
case .JSONObject(let dict):
if let value = dict[key] {
return value
}
else {
return .JSONInvalid
}
default:
return .JSONInvalid
}
}
public subscript(index: Int) -> JSONValue {
switch self {
case .JSONArray(let array) where array.count > index:
return array[index]
default:
return .JSONInvalid
}
}
static func parseJSONData(jsonData : NSData, error: NSErrorPointer) -> JSON? {
var JSONObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableContainers, error: error)
return (JSONObject == nil) ? nil : JSON(JSONObject)
}
static func parseJSONString(jsonString : String, error: NSErrorPointer) -> JSON? {
if let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
return parseJSONData(data, error: error)
}
return nil
}
func stringify(indent: String = " ") -> String? {
switch self {
case .JSONInvalid:
assert(true, "The JSON value is invalid")
return nil
default:
return _prettyPrint(indent, 0)
}
}
}
public func ==(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs, rhs) {
case (.JSONNull, .JSONNull):
return true
case (.JSONBool(let lhsValue), .JSONBool(let rhsValue)):
return lhsValue == rhsValue
case (.JSONString(let lhsValue), .JSONString(let rhsValue)):
return lhsValue == rhsValue
case (.JSONNumber(let lhsValue), .JSONNumber(let rhsValue)):
return lhsValue == rhsValue
case (.JSONArray(let lhsValue), .JSONArray(let rhsValue)):
return lhsValue == rhsValue
case (.JSONObject(let lhsValue), .JSONObject(let rhsValue)):
return lhsValue == rhsValue
default:
return false
}
}
extension JSON: Printable {
public var description: String {
if let jsonString = stringify() {
return jsonString
}
else {
return "<INVALID JSON>"
}
}
private func _prettyPrint(indent: String, _ level: Int) -> String {
let currentIndent = join(indent, map(0...level, { _ in "" }))
let nextIndent = currentIndent + " "
switch self {
case .JSONBool(let bool):
return bool ? "true" : "false"
case .JSONNumber(let number):
return "\(number)"
case .JSONString(let string):
return "\"\(string)\""
case .JSONArray(let array):
return "[\n" + join(",\n", array.map({ "\(nextIndent)\($0._prettyPrint(indent, level + 1))" })) + "\n\(currentIndent)]"
case .JSONObject(let dict):
return "{\n" + join(",\n", map(dict, { "\(nextIndent)\"\($0)\" : \($1._prettyPrint(indent, level + 1))"})) + "\n\(currentIndent)}"
case .JSONNull:
return "null"
case .JSONInvalid:
assert(true, "This should never be reached")
return ""
}
}
}
extension JSONValue: BooleanType {
public var boolValue: Bool {
switch self {
case .JSONBool(let bool):
return bool
case .JSONInvalid:
return false
default:
return true
}
}
}
extension JSON: StringLiteralConvertible {
public init(stringLiteral value: StringLiteralType) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value)
}
}
extension JSON: IntegerLiteralConvertible {
public init(integerLiteral value: IntegerLiteralType) {
self.init(value)
}
}
extension JSON: BooleanLiteralConvertible {
public init(booleanLiteral value: BooleanLiteralType) {
self.init(value)
}
}
extension JSON: FloatLiteralConvertible {
public init(floatLiteral value: FloatLiteralType) {
self.init(value)
}
}
extension JSON: DictionaryLiteralConvertible {
public init(dictionaryLiteral elements: (String, AnyObject)...) {
var dict = [String : AnyObject]()
for (key, value) in elements {
dict[key] = value
}
self.init(dict)
}
}
extension JSON: ArrayLiteralConvertible {
public init(arrayLiteral elements: AnyObject...) {
self.init(elements)
}
}
extension JSON: NilLiteralConvertible {
public init(nilLiteral: ()) {
self.init(NSNull())
}
}
private let trueNumber = NSNumber(bool: true)
private let falseNumber = NSNumber(bool: false)
private let trueObjCType = String.fromCString(trueNumber.objCType)
private let falseObjCType = String.fromCString(falseNumber.objCType)
private extension NSNumber {
var isBool:Bool {
get {
let objCType = String.fromCString(self.objCType)
if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){
return true
} else {
return false
}
}
}
}
| mit | 84058dd13e5818ecaa1be39d2a0e3404 | 25.076037 | 200 | 0.537952 | 4.954904 | false | false | false | false |
Coderian/SwiftedGPX | SwiftedGPX/Elements/Bounds.swift | 1 | 4577 | //
// Bounds.swift
// SwiftedGPX
//
// Created by 佐々木 均 on 2016/02/16.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// GPX Bounds
///
/// [GPX 1.1 schema](http://www.topografix.com/GPX/1/1/gpx.xsd)
///
/// <xsd:element name="bounds" type="boundsType" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// Minimum and maximum coordinates which describe the extent of the coordinates in the file.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
public class Bounds : SPXMLElement, HasXMLElementValue {
public static var elementName: String = "bounds"
public override var parent:SPXMLElement! {
didSet {
// 複数回呼ばれたて同じものがある場合は追加しない
if self.parent.childs.contains(self) == false {
self.parent.childs.insert(self)
switch parent {
case let v as Metadata: v.value.bounds = self
default: break
}
}
}
}
public var value:BoundsType
public required init(attributes:[String:String]){
self.value = BoundsType(minlat: attributes[BoundsType.MinLatitude.attributeName]!,
minlon: attributes[BoundsType.MinLongitude.attributeName]!,
maxlat: attributes[BoundsType.MaxLatitude.attributeName]!,
maxlon: attributes[BoundsType.MaxLongitude.attributeName]!)
super.init(attributes: attributes)
}
}
/// GPX boundsType
///
/// [GPX 1.1 schema](http://www.topografix.com/GPX/1/1/gpx.xsd)
///
/// <xsd:complexType name="boundsType">
/// <xsd:annotation>
/// <xsd:documentation>
/// Two lat/lon pairs defining the extent of an element.
/// </xsd:documentation>
/// </xsd:annotation>
/// <xsd:attribute name="minlat" type="latitudeType" use="required">
/// <xsd:annotation>
/// <xsd:documentation>
/// The minimum latitude.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:attribute>
/// <xsd:attribute name="minlon" type="longitudeType" use="required">
/// <xsd:annotation>
/// <xsd:documentation>
/// The minimum longitude.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:attribute>
/// <xsd:attribute name="maxlat" type="latitudeType" use="required">
/// <xsd:annotation>
/// <xsd:documentation>
/// The maximum latitude.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:attribute>
/// <xsd:attribute name="maxlon" type="longitudeType" use="required">
/// <xsd:annotation>
/// <xsd:documentation>
/// The maximum longitude.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:attribute>
/// </xsd:complexType>
public class BoundsType {
public struct MinLatitude : XMLAttributed {
public static var attributeName: String = "minlat"
public var value: LatitudeType
public init( value: String ){
self.value = LatitudeType(latitude: value)
}
}
public var minlat:MinLatitude
public struct MinLongitude : XMLAttributed {
public static var attributeName: String = "minlon"
public var value: LongitudeType
public init( value : String ){
self.value = LongitudeType(longitude: value)
}
}
public var minlon:MinLongitude
public struct MaxLatitude : XMLAttributed {
public static var attributeName: String = "maxlat"
public var value: LatitudeType
public init( value: String) {
self.value = LatitudeType(latitude: value)
}
}
public var maxlat:MaxLatitude
public struct MaxLongitude : XMLAttributed {
public static var attributeName: String = "maxlon"
public var value: LongitudeType
public init( value : String ){
self.value = LongitudeType(longitude: value)
}
}
public var maxlon:MaxLongitude
public init(minlat: String, minlon:String, maxlat:String, maxlon:String){
self.minlat = BoundsType.MinLatitude(value: minlat)
self.minlon = BoundsType.MinLongitude(value: minlon)
self.maxlat = BoundsType.MaxLatitude(value: maxlat)
self.maxlon = BoundsType.MaxLongitude(value: maxlon)
}
} | mit | 6cc30b6549a4195cc1b39094a8a42b95 | 34.598425 | 103 | 0.587832 | 4.057451 | false | false | false | false |
cardstream/iOS-SDK | cardstream-ios-sdk/Cardstream/Gateway.swift | 1 | 14329 | //
// Cardstream Payment Gateway SDK.
//
import CryptoSwift
///
/// Class to communicate with Payment Gateway.
///
open class Gateway {
/// Transaction successful reponse code
open static let RC_SUCCESS = 0
/// Transaction declined reponse code
open static let RC_DO_NOT_HONOR = 5
/// Verification successful reponse code
open static let RC_NO_REASON_TO_DECLINE = 85
open static let RC_3DS_AUTHENTICATION_REQUIRED = 0x1010A
static let REMOVE_REQUEST_FIELDS = [
"directUrl",
"hostedUrl",
"merchantAlias",
"merchantID2",
"merchantSecret",
"responseCode",
"responseMessage",
"responseStatus",
"signature",
"state",
]
/// HTTP protocol errors
public enum HTTPError: Error {
case clientError
case serverError
case unknownError
}
/// Request errors
public enum RequestError: Error {
case missingAction
case missingMerchantID
}
/// Response errors
public enum ResponseError: Error {
case incorrectSignature
case incorrectSignature1
case incorrectSignature2
case missingResponseCode
}
let gatewayUrl: URL!
let merchantID: String
let merchantSecret: String?
let merchantPwd: String?
///
/// Configure the Payment Gateway interface.
///
/// - Parameter gatewayUrl: Gateway API Endpoint (Direct or Hosted)
/// - Parameter merchantID: Merchant Account Id or Alias
/// - Parameter merchantSecret: Secret for above Merchant Account
/// - Parameter merchantPwd: Password for above Merchant Account
///
public init(_ gatewayUrl: String, _ merchantID: String, _ merchantSecret: String?, merchantPwd: String? = nil) {
self.gatewayUrl = URL(string: gatewayUrl)
self.merchantID = merchantID
self.merchantSecret = merchantSecret
self.merchantPwd = merchantPwd
}
///
/// Send request to Gateway using HTTP Direct API.
///
/// The method will create a NSURLRequest to send to Gateway using HTTP Direct API.
///
/// The request will use the following Gateway properties unless alternative
/// values are provided in the request:
///
/// - 'directUrl' - Gateway Direct API Endpoint
/// - 'merchantID' - Merchant Account Id or Alias
/// - 'merchantPwd' - Merchant Account Password
/// - 'merchantSecret' - Merchant Account Secret
///
/// The method will sign the request and also check the signature on any
/// response.
///
/// The method will throw an exception if it is unable to send the request
/// or receive the response.
///
/// The method does not attempt to validate any request fields.
///
/// - Parameter request: request data
/// - Parameter secret: any extracted 'merchantSecret' (return)
/// - Parameter options: options
/// - Returns: NSURLRequest ready for sending
/// - Throws: RequestError invalid request data
///
open func directRequest(_ request: [String: String], options: [String: String] = [:], secret: inout String?) throws -> URLRequest {
let directUrl: URL
if let _directUrl = request["directUrl"] {
directUrl = URL(string: _directUrl)!
} else {
directUrl = self.gatewayUrl
}
secret = request["merchantSecret"] ?? self.merchantSecret
var _request = try self.prepareRequest(request, options: options)
if secret != nil {
_request["signature"] = self.sign(_request, secret: secret)
}
let data = Gateway.buildQueryString(_request).data(using: String.Encoding.utf8)!
let httpRequest = NSMutableURLRequest(url: directUrl)
httpRequest.httpMethod = "POST"
httpRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
httpRequest.setValue(String(data.count), forHTTPHeaderField: "Content-Length")
httpRequest.httpBody = data
return httpRequest as URLRequest
}
///
/// Handle a NSURLResponse received from the gateway.
///
/// - Parameter data: data returned by the server
/// - Parameter response: response meta-data
/// - Parameter secret: secret to use in signing
/// - Returns: verified response data
/// - Throws: HTTPError communications failure
///
open func directRequestComplete(_ data: Data, response: URLResponse? = nil, secret: String? = nil) throws -> [String: String] {
if let httpResponse = response as? HTTPURLResponse {
switch httpResponse.statusCode {
case 200:
break
case 300...399:
throw HTTPError.clientError
case 400...499:
throw HTTPError.serverError
default:
throw HTTPError.unknownError
}
}
let _data = String(data: data, encoding: String.Encoding.utf8)!
let _response = Gateway.parseQueryString(_data)
return try self.verifyResponse(_response, secret: secret)
}
///
/// Send request to Gateway using HTTP Hosted API.
///
/// The method will send a request to the Gateway using the HTTP Hosted API.
///
/// The request will use the following Gateway properties unless alternative
/// values are provided in the request:
/// - 'hostedUrl': Gateway Hosted API Endpoint
/// - 'merchantID': Merchant Account Id or Alias
/// - 'merchantPwd': Merchant Account Password
/// - 'merchantSecret': Merchant Account Secret
///
/// The method accepts the following options:
/// - 'formAttrs': HTML form attributes
/// - 'submitAttrs': HTML submit button attributes
/// - 'submitImage': Image to use as the Submit button
/// - 'submitHtml': HTML to show on the Submit button
/// - 'submitText': Text to show on the Submit button
///
/// 'submitImage', 'submitHtml' and 'submitText' are mutually exclusive
/// options and will be checked for in that order. If none are provided
/// the submitText='Pay Now' is assumed.
///
/// The method will sign the request; partial signing will be used to allow
/// for submit button images et cetera.
///
/// The method returns the HTML fragment that needs including in order to
/// send the request.
///
/// The method does not attempt to validate any request fields.
///
/// - Parameter request: request data
/// - Parameter options: options
/// - Returns: request HTML form
/// - Throws: RequestError invalid request data
///
open func hostedRequest(_ request: [String: String], options: [String: String] = [:]) throws -> String {
let hostedUrl: URL
if let _directUrl = request["hostedUrl"] {
hostedUrl = URL(string: _directUrl)!
} else {
hostedUrl = self.gatewayUrl
}
let secret = request["merchantSecret"] ?? self.merchantSecret
var _request = try self.prepareRequest(request, options: options)
if secret != nil {
_request["signature"] = self.sign(_request, secret: secret, partial: true)
}
var form = "<form method=\"post\" "
if let formAttrs = options["formAttrs"] {
form += formAttrs
}
form += " action=\"" + htmlencode(hostedUrl.absoluteString) + "\">\n"
for name in Array(_request.keys).sorted() {
form += self.fieldToHtml(name, value: _request[name]!)
}
if options["submitHtml"] != nil {
form += "<button type=\"submit\" "
} else {
form += "<input "
}
if let submitAttrs = options["submitAttrs"] {
form += submitAttrs
}
if let submitImage = options["submitImage"] {
form += " type=\"image\" src=\"" + htmlencode(submitImage) + "\">\n"
} else if let submitHtml = options["submitHtml"] {
form += ">" + submitHtml + "</button>\n"
} else if let submitText = options["submitText"] {
form += " type=\"submit\" value=\"" + htmlencode(submitText) + "\">\n"
} else {
form += " type=\"submit\" value=\"Pay Now\">\n"
}
form += "</form>\n"
return form
}
///
/// Prepare a request for sending to the Gateway.
///
/// The method will insert the following configuration properties into
/// the request if they are not already present:
///
/// - merchantID: Merchant Account Id or Alias
/// - merchantPwd: Merchant Account Password (if provided)
///
/// The method will throw an exception if the request doesn't contain
/// an 'action' element or a 'merchantID' element (and none could be
/// inserted).
///
/// The method does not attempt to validate any request fields.
///
/// - Parameter request: request data
/// - Parameter options: options
/// - Returns: request data ready for sending
/// - Throws: RequestError invalid request data
///
open func prepareRequest(_ request: [String: String], options: [String: String] = [:]) throws -> [String: String] {
guard request["action"] != nil else {
throw RequestError.missingAction
}
var _request = request
if _request["merchantID"] == nil {
_request["merchantID"] = self.merchantID
}
if self.merchantPwd != nil && _request["merchantPwd"] == nil {
_request["merchantPwd"] = self.merchantPwd
}
guard _request["merchantID"] != nil else {
throw RequestError.missingMerchantID
}
for name in Gateway.REMOVE_REQUEST_FIELDS {
_request.removeValue(forKey: name)
}
return _request
}
///
/// Verify the response from the Gateway.
///
/// This method will verify that the response is present, contains a
/// response code and is correctly signed if a secret is available.
///
/// If the response is invalid then an exception will be thrown.
///
/// Any signature is removed from the passed response.
///
/// - Parameter response: response to verify
/// - Parameter secret: secret to use in signing
/// - Returns: verified response data
/// - Throws: ResponseError invalid response data
///
open func verifyResponse(_ response: [String: String], secret: String? = nil) throws -> [String: String] {
guard response["responseCode"] != nil else {
throw ResponseError.missingResponseCode
}
let secret = secret ?? self.merchantSecret
var _response = response
var signature = _response.removeValue(forKey: "signature")
var partial: String? = nil
if let _signature = signature {
if _signature.contains("|") {
let components = _signature.components(separatedBy: "|")
signature = components[0]
partial = components[1]
}
}
if secret == nil && signature != nil {
// Signature present when not expected (Gateway has a secret but we don't)
throw ResponseError.incorrectSignature1
}
if secret != nil && signature == nil {
// Signature missing when one expected (we have a secret but the Gateway doesn't)
throw ResponseError.incorrectSignature2
}
if secret != nil && self.sign(_response, secret: secret, partial: partial) != signature {
// Signature mismatch
throw ResponseError.incorrectSignature
}
return _response
}
///
/// Sign the given array of data.
///
/// This method will return the correct signature for the data array.
///
/// If the secret is not provided then merchantSecret is used.
///
/// The partial parameter is used to indicate that the signature should
/// be marked as 'partial' and can take three possible value types as
/// follows:
///
/// - boolean: sign with all fields
/// - string: comma separated list of field names to sign
/// - array: array of field names to sign
///
/// - Parameter data: data to sign
/// - Parameter secret: secret to use in signing
/// - Parameter partial: partial signing
/// - Returns: signature
///
open func sign(_ data: [String: String], secret: String? = nil, partial: Any? = nil) -> String {
let secret = secret ?? self.merchantSecret
var _data = data
let _partial: String?
if partial != nil {
let arrayPartial: [String]?
if let _stringPartial = partial as? String {
arrayPartial = _stringPartial.components(separatedBy: ",")
} else if let _arrayPartial = partial as? [String] {
arrayPartial = _arrayPartial
} else {
arrayPartial = nil
}
if arrayPartial != nil {
for name in arrayPartial! {
_data.removeValue(forKey: name)
}
}
_partial = Array(_data.keys).sorted().joined(separator: ",")
} else {
_partial = nil
}
let message = Gateway.buildQueryString(data) + secret!
let signature = message.sha512()
if let partial = _partial {
return signature + "|" + partial
}
return signature
}
///
/// Return the field name and value as HTML input tags.
///
/// The method will return a string containing one or more HTML <input
/// type="hidden"> tags which can be used to store the name and value.
///
/// - Parameter name: field name
/// - Parameter value: field value
/// - Returns: HTML containing <INPUT> tags
///
open func fieldToHtml(_ name: String, value: String) -> String {
if value.isEmpty {
return ""
}
let name = htmlencode(name)
let value = htmlencode(value)
return "<input type=\"hidden\" name=\"\(name)\" value=\"\(value)\" />\n"
}
class func buildQueryString(_ data: [String: String]) -> String {
let allowedCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")
var items = [String]()
for name in Array(data.keys).sorted() {
let _name = name.addingPercentEncoding(withAllowedCharacters: allowedCharacters)!
let _value = data[name]!.addingPercentEncoding(withAllowedCharacters: allowedCharacters)!
items.append("\(_name)=\(_value)")
}
var query = items.joined(separator: "&")
if let regex = try? NSRegularExpression(pattern: "%0D%0A|%0A%0D|%0D", options: .caseInsensitive) {
query = regex.stringByReplacingMatches(in: query, options: .withTransparentBounds, range: NSMakeRange(0, query.characters.count), withTemplate: "%0A")
}
return query.replacingOccurrences(of: "%20", with: "+")
}
class func parseQueryString(_ query: String) -> [String: String] {
var data = [String: String]()
for pair in query.components(separatedBy: "&") {
let item = pair.components(separatedBy: "=")
let name = item[0].removingPercentEncoding!
let value = item[1].replacingOccurrences(of: "+", with: " ").removingPercentEncoding
data[name] = value
}
return data
}
}
func htmlencode(_ str: String) -> String {
// based on http://stackoverflow.com/a/1673173
return str.replacingOccurrences(of: "&", with: "&")
.replacingOccurrences(of: "\"", with: """)
.replacingOccurrences(of: "'", with: "'")
.replacingOccurrences(of: "<", with: "<")
.replacingOccurrences(of: ">", with: ">")
}
| gpl-3.0 | 4afa7c9f5c017ab3363a5e512d128029 | 27.374257 | 153 | 0.668644 | 3.800796 | false | false | false | false |
Endika/tsuru | misc/git-hooks/pre-receive.swift | 2 | 2597 | #!/bin/bash -el
# This script generates a git archive from the provided commit, uploads it to
# Swift, sends the URL to Tsuru and then delete the archive in from the
# container.
#
# It depends on the "swift" command line (it can be installed with pip).
#
# It also depends on the following environment variables:
#
# - AUTH_PARAMS: the parameters used in authentication (for example:
# "-A https://yourswift.com -K yourkey -U youruser")
# - CDN_URL: the URL of the CDN that serves content from your container (for
# example: something.cf5.rackcdn.com).
# - CONTAINER_NAME: name of the container where the script will store the
# archives
# - TSURU_HOST: URL to the Tsuru API (for example: http://yourtsuru:8080)
# - TSURU_TOKEN: the token to communicate with the API (generated with
# `tsurud token`, in the server).
while read oldrev newrev refname
do
set +e
echo $refname | grep -v tags/master$ | grep -q /master$
status=$?
set -e
if [ $status = 0 ]
then
COMMIT=${newrev}
fi
done
if [ -z ${COMMIT} ]
then
echo "ERROR: please push to master"
exit 3
fi
git_archive_all() {
REV=$1; FILE=$2
TMP_WORK_DIR=$(mktemp -d)
chmod 755 $TMP_WORK_DIR
unset GIT_DIR GIT_WORK_TREE
git clone -q $PWD $TMP_WORK_DIR &> /dev/null
pushd $TMP_WORK_DIR > /dev/null
git config advice.detachedHead false
git checkout $REV > /dev/null
git submodule update --init --recursive > /dev/null
find -name .git -prune -exec rm -rf {} \; > /dev/null
tar zcf /tmp/$FILE .
popd > /dev/null
rm -rf $TMP_WORK_DIR > /dev/null
}
APP_DIR=${PWD##*/}
APP_NAME=${APP_DIR/.git/}
UUID=`python -c 'import uuid; print uuid.uuid4().hex'`
ARCHIVE_FILE_NAME=${APP_NAME}_${COMMIT}_${UUID}.tar.gz
git_archive_all $COMMIT $ARCHIVE_FILE_NAME
swift -q $AUTH_PARAMS upload $CONTAINER_NAME /tmp/$ARCHIVE_FILE_NAME --object-name $ARCHIVE_FILE_NAME
swift -q $AUTH_PARAMS post -r ".r:*" $CONTAINER_NAME
rm /tmp/$ARCHIVE_FILE_NAME
if [ -z "${CDN_URL}" ]
then
ARCHIVE_URL=`swift $AUTH_PARAMS stat -v $CONTAINER_NAME $ARCHIVE_FILE_NAME | grep URL | awk -F': ' '{print $2}'`
else
ARCHIVE_URL=${CDN_URL}/${ARCHIVE_FILE_NAME}
fi
URL="${TSURU_HOST}/apps/${APP_NAME}/deploy"
curl -H "Authorization: bearer ${TSURU_TOKEN}" -d "archive-url=${ARCHIVE_URL}&commit=${COMMIT}&user=${TSURU_USER}" -s -N $URL | tee /tmp/deploy-${APP_NAME}.log
swift -q $AUTH_PARAMS delete $CONTAINER_NAME $ARCHIVE_FILE_NAME
tail -1 /tmp/deploy-${APP_NAME}.log | grep -q "^OK$"
| bsd-3-clause | 46e21e51f427465ca450bd19d2bdae72 | 35.069444 | 159 | 0.641894 | 3.073373 | false | false | false | false |
withcopper/CopperKit | CopperKit/C29RequestDataSource.swift | 1 | 1869 | //
// C29RequestDataSource.swift
// Copper
//
// Created by Doug Williams on 3/23/2016.
// Copyright © 2015 Doug Williams. All rights reserved.
//
import Foundation
// MARK: - Copper Request Objects
@objc public protocol C29RequestDataSource: class {
var userId: String { get }
var id: String { get }
var applicationId: String { get }
var expired: Bool { get }
var timestamp: NSDate { get }
var scopesString: String? { get }
var platform: C29RequestPlatform? { get }
var status: NSInteger { get }
var responded: Bool { get }
var complete: Bool { get }
var records: [CopperRecord] { get set }
}
public protocol C29RequestCaller {
func getApplication(session: C29SessionDataSource) -> C29CopperworksApplication?
static func getRequest(session: C29SessionDataSource, requestId: String, callback: C29RequestCallback)
func sendResponse(session: C29SessionDataSource, status: C29RequestStatus, callback: C29RequestResponseCallback)
func setAck(session: C29SessionDataSource)
}
public protocol C29RequestScopeable: class {
var scopes: [C29Scope] { get }
}
@objc public enum C29RequestStatus: NSInteger {
case Approved = 1
case Dismissed = 0
case Reported = -1
case Unanswered = -29
var localizedString:String {
get {
switch (self) {
case Approved:
return "Approved"
case Dismissed:
return "Dismissed"
case Reported:
return "Reported"
case Unanswered:
return "Unanswered"
}
}
}
static var DefaultStatus: C29RequestStatus {
return Unanswered
}
}
public typealias C29RequestCallback = (request: C29RequestDataSource?) -> ()
public typealias C29RequestResponseCallback = (success: Bool, redirecting: Bool) -> ()
| mit | d0829c47f7f8f63302aa549a9e8392b6 | 29.129032 | 116 | 0.657388 | 4.178971 | false | false | false | false |
luvacu/XLPagerTabStrip | Sources/ButtonBarPagerTabStripViewController.swift | 1 | 19160 | // ButtonBarPagerTabStripViewController.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2017 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
public enum ButtonBarItemSpec<CellType: UICollectionViewCell> {
case nibFile(nibName: String, bundle: Bundle?, width:((IndicatorInfo)-> CGFloat))
case cellClass(width:((IndicatorInfo)-> CGFloat))
public var weight: ((IndicatorInfo) -> CGFloat) {
switch self {
case .cellClass(let widthCallback):
return widthCallback
case .nibFile(_, _, let widthCallback):
return widthCallback
}
}
}
public struct ButtonBarPagerTabStripSettings {
public struct Style {
public var buttonBarBackgroundColor: UIColor?
public var buttonBarMinimumLineSpacing: CGFloat?
public var buttonBarLeftContentInset: CGFloat?
public var buttonBarRightContentInset: CGFloat?
public var selectedBarBackgroundColor = UIColor.black
public var selectedBarHeight: CGFloat = 5
public var selectedBarVerticalAlignment: SelectedBarVerticalAlignment = .bottom
public var buttonBarItemBackgroundColor: UIColor?
public var buttonBarItemFont = UIFont.systemFont(ofSize: 18)
public var buttonBarItemLeftRightMargin: CGFloat = 8
public var buttonBarItemTitleColor: UIColor?
@available(*, deprecated: 7.0.0) public var buttonBarItemsShouldFillAvailiableWidth: Bool {
set {
buttonBarItemsShouldFillAvailableWidth = newValue
}
get {
return buttonBarItemsShouldFillAvailableWidth
}
}
public var buttonBarItemsShouldFillAvailableWidth = true
// only used if button bar is created programaticaly and not using storyboards or nib files
public var buttonBarHeight: CGFloat?
}
public var style = Style()
}
open class ButtonBarPagerTabStripViewController: PagerTabStripViewController, PagerTabStripDataSource, PagerTabStripIsProgressiveDelegate, UICollectionViewDelegate, UICollectionViewDataSource {
public var settings = ButtonBarPagerTabStripSettings()
public var buttonBarItemSpec: ButtonBarItemSpec<ButtonBarViewCell>!
public var changeCurrentIndex: ((_ oldCell: ButtonBarViewCell?, _ newCell: ButtonBarViewCell?, _ animated: Bool) -> Void)?
public var changeCurrentIndexProgressive: ((_ oldCell: ButtonBarViewCell?, _ newCell: ButtonBarViewCell?, _ progressPercentage: CGFloat, _ changeCurrentIndex: Bool, _ animated: Bool) -> Void)?
@IBOutlet public weak var buttonBarView: ButtonBarView!
lazy private var cachedCellWidths: [CGFloat]? = { [unowned self] in
return self.calculateWidths()
}()
override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
delegate = self
datasource = self
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delegate = self
datasource = self
}
open override func viewDidLoad() {
super.viewDidLoad()
buttonBarItemSpec = .nibFile(nibName: "ButtonCell", bundle: Bundle(for: ButtonBarViewCell.self), width:{ [weak self] (childItemInfo) -> CGFloat in
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = self?.settings.style.buttonBarItemFont
label.text = childItemInfo.title
let labelSize = label.intrinsicContentSize
return labelSize.width + (self?.settings.style.buttonBarItemLeftRightMargin ?? 8) * 2
})
let buttonBarViewAux = buttonBarView ?? {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .horizontal
let buttonBarHeight = settings.style.buttonBarHeight ?? 44
let buttonBar = ButtonBarView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: buttonBarHeight), collectionViewLayout: flowLayout)
buttonBar.backgroundColor = .orange
buttonBar.selectedBar.backgroundColor = .black
buttonBar.autoresizingMask = .flexibleWidth
var newContainerViewFrame = containerView.frame
newContainerViewFrame.origin.y = buttonBarHeight
newContainerViewFrame.size.height = containerView.frame.size.height - (buttonBarHeight - containerView.frame.origin.y)
containerView.frame = newContainerViewFrame
return buttonBar
}()
buttonBarView = buttonBarViewAux
if buttonBarView.superview == nil {
view.addSubview(buttonBarView)
}
if buttonBarView.delegate == nil {
buttonBarView.delegate = self
}
if buttonBarView.dataSource == nil {
buttonBarView.dataSource = self
}
buttonBarView.scrollsToTop = false
let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout
flowLayout.scrollDirection = .horizontal
flowLayout.minimumInteritemSpacing = 0
flowLayout.minimumLineSpacing = settings.style.buttonBarMinimumLineSpacing ?? flowLayout.minimumLineSpacing
let sectionInset = flowLayout.sectionInset
flowLayout.sectionInset = UIEdgeInsetsMake(sectionInset.top, settings.style.buttonBarLeftContentInset ?? sectionInset.left, sectionInset.bottom, settings.style.buttonBarRightContentInset ?? sectionInset.right)
buttonBarView.showsHorizontalScrollIndicator = false
buttonBarView.backgroundColor = settings.style.buttonBarBackgroundColor ?? buttonBarView.backgroundColor
buttonBarView.selectedBar.backgroundColor = settings.style.selectedBarBackgroundColor
buttonBarView.selectedBarHeight = settings.style.selectedBarHeight
buttonBarView.selectedBarVerticalAlignment = settings.style.selectedBarVerticalAlignment
// register button bar item cell
switch buttonBarItemSpec! {
case .nibFile(let nibName, let bundle, _):
buttonBarView.register(UINib(nibName: nibName, bundle: bundle), forCellWithReuseIdentifier:"Cell")
case .cellClass:
buttonBarView.register(ButtonBarViewCell.self, forCellWithReuseIdentifier:"Cell")
}
//-
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
buttonBarView.layoutIfNeeded()
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard isViewAppearing || isViewRotating else { return }
// Force the UICollectionViewFlowLayout to get laid out again with the new size if
// a) The view is appearing. This ensures that
// collectionView:layout:sizeForItemAtIndexPath: is called for a second time
// when the view is shown and when the view *frame(s)* are actually set
// (we need the view frame's to have been set to work out the size's and on the
// first call to collectionView:layout:sizeForItemAtIndexPath: the view frame(s)
// aren't set correctly)
// b) The view is rotating. This ensures that
// collectionView:layout:sizeForItemAtIndexPath: is called again and can use the views
// *new* frame so that the buttonBarView cell's actually get resized correctly
cachedCellWidths = calculateWidths()
buttonBarView.collectionViewLayout.invalidateLayout()
// When the view first appears or is rotated we also need to ensure that the barButtonView's
// selectedBar is resized and its contentOffset/scroll is set correctly (the selected
// tab/cell may end up either skewed or off screen after a rotation otherwise)
buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .scrollOnlyIfOutOfScreen)
}
// MARK: - Public Methods
open override func reloadPagerTabStripView() {
super.reloadPagerTabStripView()
guard isViewLoaded else { return }
buttonBarView.reloadData()
cachedCellWidths = calculateWidths()
buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .yes)
}
open func calculateStretchedCellWidths(_ minimumCellWidths: [CGFloat], suggestedStretchedCellWidth: CGFloat, previousNumberOfLargeCells: Int) -> CGFloat {
var numberOfLargeCells = 0
var totalWidthOfLargeCells: CGFloat = 0
for minimumCellWidthValue in minimumCellWidths where minimumCellWidthValue > suggestedStretchedCellWidth {
totalWidthOfLargeCells += minimumCellWidthValue
numberOfLargeCells += 1
}
guard numberOfLargeCells > previousNumberOfLargeCells else { return suggestedStretchedCellWidth }
let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout
let collectionViewAvailiableWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right
let numberOfCells = minimumCellWidths.count
let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing
let numberOfSmallCells = numberOfCells - numberOfLargeCells
let newSuggestedStretchedCellWidth = (collectionViewAvailiableWidth - totalWidthOfLargeCells - cellSpacingTotal) / CGFloat(numberOfSmallCells)
return calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: newSuggestedStretchedCellWidth, previousNumberOfLargeCells: numberOfLargeCells)
}
open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) {
guard shouldUpdateButtonBarView else { return }
buttonBarView.moveTo(index: toIndex, animated: true, swipeDirection: toIndex < fromIndex ? .right : .left, pagerScroll: .yes)
if let changeCurrentIndex = changeCurrentIndex {
let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarViewCell
let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarViewCell
changeCurrentIndex(oldCell, newCell, true)
}
}
open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) {
guard shouldUpdateButtonBarView else { return }
buttonBarView.move(fromIndex: fromIndex, toIndex: toIndex, progressPercentage: progressPercentage, pagerScroll: .yes)
if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarViewCell
let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarViewCell
changeCurrentIndexProgressive(oldCell, newCell, progressPercentage, indexWasChanged, true)
}
}
// MARK: - UICollectionViewDelegateFlowLayut
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
guard let cellWidthValue = cachedCellWidths?[indexPath.row] else {
fatalError("cachedCellWidths for \(indexPath.row) must not be nil")
}
return CGSize(width: cellWidthValue, height: collectionView.frame.size.height)
}
open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard indexPath.item != currentIndex else { return }
buttonBarView.moveTo(index: indexPath.item, animated: true, swipeDirection: .none, pagerScroll: .yes)
shouldUpdateButtonBarView = false
let oldIndexPath = IndexPath(item: currentIndex, section: 0)
let newIndexPath = IndexPath(item: indexPath.item, section: 0)
collectionView.reloadItems(at: [oldIndexPath, newIndexPath])
collectionView.layoutIfNeeded()
// Another solution might be to deactivate iOS 10 CollectionView prefetching (collectionView.isPrefetchingEnabled = false)
let oldCell = buttonBarView.cellForItem(at: oldIndexPath) as? ButtonBarViewCell
let newCell = buttonBarView.cellForItem(at: newIndexPath) as? ButtonBarViewCell
if pagerBehaviour.isProgressiveIndicator {
if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
changeCurrentIndexProgressive(oldCell, newCell, 1, true, true)
}
}
else {
if let changeCurrentIndex = changeCurrentIndex {
changeCurrentIndex(oldCell, newCell, true)
}
}
moveToViewController(at: indexPath.item)
}
// MARK: - UICollectionViewDataSource
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewControllers.count
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? ButtonBarViewCell else {
fatalError("UICollectionViewCell should be or extend from ButtonBarViewCell")
}
let childController = viewControllers[indexPath.item] as! IndicatorInfoProvider
let indicatorInfo = childController.indicatorInfo(for: self)
cell.label.text = indicatorInfo.title
cell.label.font = settings.style.buttonBarItemFont
cell.label.textColor = settings.style.buttonBarItemTitleColor ?? cell.label.textColor
cell.contentView.backgroundColor = settings.style.buttonBarItemBackgroundColor ?? cell.contentView.backgroundColor
cell.backgroundColor = settings.style.buttonBarItemBackgroundColor ?? cell.backgroundColor
if let image = indicatorInfo.image {
cell.imageView.image = image
}
if let highlightedImage = indicatorInfo.highlightedImage {
cell.imageView.highlightedImage = highlightedImage
}
configureCell(cell, indicatorInfo: indicatorInfo)
if pagerBehaviour.isProgressiveIndicator {
if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
changeCurrentIndexProgressive(currentIndex == indexPath.item ? nil : cell, currentIndex == indexPath.item ? cell : nil, 1, true, false)
}
}
else {
if let changeCurrentIndex = changeCurrentIndex {
changeCurrentIndex(currentIndex == indexPath.item ? nil : cell, currentIndex == indexPath.item ? cell : nil, false)
}
}
return cell
}
// MARK: - UIScrollViewDelegate
open override func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
super.scrollViewDidEndScrollingAnimation(scrollView)
guard scrollView == containerView else { return }
shouldUpdateButtonBarView = true
}
open func configureCell(_ cell: ButtonBarViewCell, indicatorInfo: IndicatorInfo){
}
private func calculateWidths() -> [CGFloat] {
let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout
let numberOfCells = viewControllers.count
var minimumCellWidths = [CGFloat]()
var collectionViewContentWidth: CGFloat = 0
for viewController in viewControllers {
let childController = viewController as! IndicatorInfoProvider
let indicatorInfo = childController.indicatorInfo(for: self)
switch buttonBarItemSpec! {
case .cellClass(let widthCallback):
let width = widthCallback(indicatorInfo)
minimumCellWidths.append(width)
collectionViewContentWidth += width
case .nibFile(_, _, let widthCallback):
let width = widthCallback(indicatorInfo)
minimumCellWidths.append(width)
collectionViewContentWidth += width
}
}
let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing
collectionViewContentWidth += cellSpacingTotal
let collectionViewAvailableVisibleWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right
if !settings.style.buttonBarItemsShouldFillAvailableWidth || collectionViewAvailableVisibleWidth < collectionViewContentWidth {
return minimumCellWidths
}
else {
let stretchedCellWidthIfAllEqual = (collectionViewAvailableVisibleWidth - cellSpacingTotal) / CGFloat(numberOfCells)
let generalMinimumCellWidth = calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: stretchedCellWidthIfAllEqual, previousNumberOfLargeCells: 0)
var stretchedCellWidths = [CGFloat]()
for minimumCellWidthValue in minimumCellWidths {
let cellWidth = (minimumCellWidthValue > generalMinimumCellWidth) ? minimumCellWidthValue : generalMinimumCellWidth
stretchedCellWidths.append(cellWidth)
}
return stretchedCellWidths
}
}
private var shouldUpdateButtonBarView = true
}
| mit | 510e7f2e5d8f7d1a667ace6b97297810 | 49.55409 | 217 | 0.696347 | 6.059456 | false | false | false | false |
KeithPiTsui/Pavers | Pavers/Sources/FRP/ReactiveSwift/Event.swift | 2 | 25511 | import Foundation
import Dispatch
extension Signal {
/// Represents a signal event.
///
/// Signals must conform to the grammar:
/// `value* (failed | completed | interrupted)?`
public enum Event {
/// A value provided by the signal.
case value(Value)
/// The signal terminated because of an error. No further events will be
/// received.
case failed(Error)
/// The signal successfully terminated. No further events will be received.
case completed
/// Event production on the signal has been interrupted. No further events
/// will be received.
///
/// - important: This event does not signify the successful or failed
/// completion of the signal.
case interrupted
/// Whether this event is a completed event.
public var isCompleted: Bool {
switch self {
case .completed:
return true
case .value, .failed, .interrupted:
return false
}
}
/// Whether this event indicates signal termination (i.e., that no further
/// events will be received).
public var isTerminating: Bool {
switch self {
case .value:
return false
case .failed, .completed, .interrupted:
return true
}
}
/// Lift the given closure over the event's value.
///
/// - important: The closure is called only on `value` type events.
///
/// - parameters:
/// - f: A closure that accepts a value and returns a new value
///
/// - returns: An event with function applied to a value in case `self` is a
/// `value` type of event.
public func map<U>(_ f: (Value) -> U) -> Signal<U, Error>.Event {
switch self {
case let .value(value):
return .value(f(value))
case let .failed(error):
return .failed(error)
case .completed:
return .completed
case .interrupted:
return .interrupted
}
}
/// Lift the given closure over the event's error.
///
/// - important: The closure is called only on failed type event.
///
/// - parameters:
/// - f: A closure that accepts an error object and returns
/// a new error object
///
/// - returns: An event with function applied to an error object in case
/// `self` is a `.Failed` type of event.
public func mapError<F>(_ f: (Error) -> F) -> Signal<Value, F>.Event {
switch self {
case let .value(value):
return .value(value)
case let .failed(error):
return .failed(f(error))
case .completed:
return .completed
case .interrupted:
return .interrupted
}
}
/// Unwrap the contained `value` value.
public var value: Value? {
if case let .value(value) = self {
return value
} else {
return nil
}
}
/// Unwrap the contained `Error` value.
public var error: Error? {
if case let .failed(error) = self {
return error
} else {
return nil
}
}
}
}
extension Signal.Event where Value: Equatable, Error: Equatable {
public static func == (lhs: Signal<Value, Error>.Event, rhs: Signal<Value, Error>.Event) -> Bool {
switch (lhs, rhs) {
case let (.value(left), .value(right)):
return left == right
case let (.failed(left), .failed(right)):
return left == right
case (.completed, .completed):
return true
case (.interrupted, .interrupted):
return true
default:
return false
}
}
}
extension Signal.Event: Equatable where Value: Equatable, Error: Equatable {}
extension Signal.Event: CustomStringConvertible {
public var description: String {
switch self {
case let .value(value):
return "VALUE \(value)"
case let .failed(error):
return "FAILED \(error)"
case .completed:
return "COMPLETED"
case .interrupted:
return "INTERRUPTED"
}
}
}
/// Event protocol for constraining signal extensions
public protocol EventProtocol {
/// The value type of an event.
associatedtype Value
/// The error type of an event. If errors aren't possible then `Never` can
/// be used.
associatedtype Error: Swift.Error
/// Extracts the event from the receiver.
var event: Signal<Value, Error>.Event { get }
}
extension Signal.Event: EventProtocol {
public var event: Signal<Value, Error>.Event {
return self
}
}
// Event Transformations
//
// Operators backed by event transformations have such characteristics:
//
// 1. Unary
// The operator applies to only one stream.
//
// 2. Serial
// The outcome need not be synchronously emitted, but all events must be delivered in
// serial order.
//
// 3. No side effect upon interruption.
// The operator must not perform any side effect upon receving `interrupted`.
//
// Examples of ineligible operators (for now):
//
// 1. `timeout`
// This operator forwards the `failed` event on a different scheduler.
//
// 2. `combineLatest`
// This operator applies to two or more streams.
//
// 3. `SignalProducer.then`
// This operator starts a second stream when the first stream completes.
//
// 4. `on`
// This operator performs side effect upon interruption.
extension Signal.Event {
internal typealias Transformation<U, E: Swift.Error> = (@escaping Signal<U, E>.Observer.Action, Lifetime) -> Signal<Value, Error>.Observer.Action
internal static func filter(_ isIncluded: @escaping (Value) -> Bool) -> Transformation<Value, Error> {
return { action, _ in
return { event in
switch event {
case let .value(value):
if isIncluded(value) {
action(.value(value))
}
case .completed:
action(.completed)
case let .failed(error):
action(.failed(error))
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func filterMap<U>(_ transform: @escaping (Value) -> U?) -> Transformation<U, Error> {
return { action, _ in
return { event in
switch event {
case let .value(value):
if let newValue = transform(value) {
action(.value(newValue))
}
case .completed:
action(.completed)
case let .failed(error):
action(.failed(error))
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func map<U>(_ transform: @escaping (Value) -> U) -> Transformation<U, Error> {
return { action, _ in
return { event in
switch event {
case let .value(value):
action(.value(transform(value)))
case .completed:
action(.completed)
case let .failed(error):
action(.failed(error))
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func mapError<E>(_ transform: @escaping (Error) -> E) -> Transformation<Value, E> {
return { action, _ in
return { event in
switch event {
case let .value(value):
action(.value(value))
case .completed:
action(.completed)
case let .failed(error):
action(.failed(transform(error)))
case .interrupted:
action(.interrupted)
}
}
}
}
internal static var materialize: Transformation<Signal<Value, Error>.Event, Never> {
return { action, _ in
return { event in
action(.value(event))
switch event {
case .interrupted:
action(.interrupted)
case .completed, .failed:
action(.completed)
case .value:
break
}
}
}
}
internal static var materializeResults: Transformation<Result<Value, Error>, Never> {
return { action, _ in
return { event in
switch event {
case .value(let value):
action(.value(Result(success: value)))
case .failed(let error):
action(.value(Result(failure: error)))
action(.completed)
case .completed:
action(.completed)
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func attemptMap<U>(_ transform: @escaping (Value) -> Result<U, Error>) -> Transformation<U, Error> {
return { action, _ in
return { event in
switch event {
case let .value(value):
switch transform(value) {
case let .success(value):
action(.value(value))
case let .failure(error):
action(.failed(error))
}
case let .failed(error):
action(.failed(error))
case .completed:
action(.completed)
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func attempt(_ action: @escaping (Value) -> Result<(), Error>) -> Transformation<Value, Error> {
return attemptMap { value -> Result<Value, Error> in
return action(value).map { _ in value }
}
}
}
extension Signal.Event where Error == Swift.Error {
internal static func attempt(_ action: @escaping (Value) throws -> Void) -> Transformation<Value, Error> {
return attemptMap { value in
try action(value)
return value
}
}
internal static func attemptMap<U>(_ transform: @escaping (Value) throws -> U) -> Transformation<U, Error> {
return attemptMap { value in
Result { try transform(value) }
}
}
}
extension Signal.Event {
internal static func take(first count: Int) -> Transformation<Value, Error> {
assert(count >= 1)
return { action, _ in
var taken = 0
return { event in
guard let value = event.value else {
action(event)
return
}
if taken < count {
taken += 1
action(.value(value))
}
if taken == count {
action(.completed)
}
}
}
}
internal static func take(last count: Int) -> Transformation<Value, Error> {
return { action, _ in
var buffer: [Value] = []
buffer.reserveCapacity(count)
return { event in
switch event {
case let .value(value):
// To avoid exceeding the reserved capacity of the buffer,
// we remove then add. Remove elements until we have room to
// add one more.
while (buffer.count + 1) > count {
buffer.remove(at: 0)
}
buffer.append(value)
case let .failed(error):
action(.failed(error))
case .completed:
buffer.forEach { action(.value($0)) }
action(.completed)
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func take(while shouldContinue: @escaping (Value) -> Bool) -> Transformation<Value, Error> {
return { action, _ in
return { event in
if let value = event.value, !shouldContinue(value) {
action(.completed)
} else {
action(event)
}
}
}
}
internal static func skip(first count: Int) -> Transformation<Value, Error> {
precondition(count > 0)
return { action, _ in
var skipped = 0
return { event in
if case .value = event, skipped < count {
skipped += 1
} else {
action(event)
}
}
}
}
internal static func skip(while shouldContinue: @escaping (Value) -> Bool) -> Transformation<Value, Error> {
return { action, _ in
var isSkipping = true
return { event in
switch event {
case let .value(value):
isSkipping = isSkipping && shouldContinue(value)
if !isSkipping {
fallthrough
}
case .failed, .completed, .interrupted:
action(event)
}
}
}
}
}
extension Signal.Event where Value: EventProtocol, Error == Never {
internal static var dematerialize: Transformation<Value.Value, Value.Error> {
return { action, _ in
return { event in
switch event {
case let .value(innerEvent):
action(innerEvent.event)
case .failed:
fatalError("Never is impossible to construct")
case .completed:
action(.completed)
case .interrupted:
action(.interrupted)
}
}
}
}
}
extension Signal.Event where Value: ResultProtocol, Error == Never {
internal static var dematerializeResults: Transformation<Value.Success, Value.Failure> {
return { action, _ in
return { event in
let event = event.map { $0.result }
switch event {
case .value(.success(let value)):
action(.value(value))
case .value(.failure(let error)):
action(.failed(error))
case .failed:
fatalError("Never is impossible to construct")
case .completed:
action(.completed)
case .interrupted:
action(.interrupted)
}
}
}
}
}
extension Signal.Event where Value: OptionalProtocol {
internal static var skipNil: Transformation<Value.Wrapped, Error> {
return filterMap { $0.optional }
}
}
/// A reference type which wraps an array to auxiliate the collection of values
/// for `collect` operator.
private final class CollectState<Value> {
var values: [Value] = []
/// Collects a new value.
func append(_ value: Value) {
values.append(value)
}
/// Check if there are any items remaining.
///
/// - note: This method also checks if there weren't collected any values
/// and, in that case, it means an empty array should be sent as the
/// result of collect.
var isEmpty: Bool {
/// We use capacity being zero to determine if we haven't collected any
/// value since we're keeping the capacity of the array to avoid
/// unnecessary and expensive allocations). This also guarantees
/// retro-compatibility around the original `collect()` operator.
return values.isEmpty && values.capacity > 0
}
/// Removes all values previously collected if any.
func flush() {
// Minor optimization to avoid consecutive allocations. Can
// be useful for sequences of regular or similar size and to
// track if any value was ever collected.
values.removeAll(keepingCapacity: true)
}
}
extension Signal.Event {
internal static var collect: Transformation<[Value], Error> {
return collect { _, _ in false }
}
internal static func collect(count: Int) -> Transformation<[Value], Error> {
precondition(count > 0)
return collect { values in values.count == count }
}
internal static func collect(_ shouldEmit: @escaping (_ collectedValues: [Value]) -> Bool) -> Transformation<[Value], Error> {
return { action, _ in
let state = CollectState<Value>()
return { event in
switch event {
case let .value(value):
state.append(value)
if shouldEmit(state.values) {
action(.value(state.values))
state.flush()
}
case .completed:
if !state.isEmpty {
action(.value(state.values))
}
action(.completed)
case let .failed(error):
action(.failed(error))
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func collect(_ shouldEmit: @escaping (_ collected: [Value], _ latest: Value) -> Bool) -> Transformation<[Value], Error> {
return { action, _ in
let state = CollectState<Value>()
return { event in
switch event {
case let .value(value):
if shouldEmit(state.values, value) {
action(.value(state.values))
state.flush()
}
state.append(value)
case .completed:
if !state.isEmpty {
action(.value(state.values))
}
action(.completed)
case let .failed(error):
action(.failed(error))
case .interrupted:
action(.interrupted)
}
}
}
}
/// Implementation detail of `combinePrevious`. A default argument of a `nil` initial
/// is deliberately avoided, since in the case of `Value` being an optional, the
/// `nil` literal would be materialized as `Optional<Value>.none` instead of `Value`,
/// thus changing the semantic.
internal static func combinePrevious(initial: Value?) -> Transformation<(Value, Value), Error> {
return { action, _ in
var previous = initial
return { event in
switch event {
case let .value(value):
if let previous = previous {
action(.value((previous, value)))
}
previous = value
case .completed:
action(.completed)
case let .failed(error):
action(.failed(error))
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func skipRepeats(_ isEquivalent: @escaping (Value, Value) -> Bool) -> Transformation<Value, Error> {
return { action, _ in
var previous: Value?
return { event in
switch event {
case let .value(value):
if let previous = previous, isEquivalent(previous, value) {
return
}
previous = value
fallthrough
case .completed, .interrupted, .failed:
action(event)
}
}
}
}
internal static func uniqueValues<Identity: Hashable>(_ transform: @escaping (Value) -> Identity) -> Transformation<Value, Error> {
return { action, _ in
var seenValues: Set<Identity> = []
return { event in
switch event {
case let .value(value):
let identity = transform(value)
let (inserted, _) = seenValues.insert(identity)
if inserted {
fallthrough
}
case .failed, .completed, .interrupted:
action(event)
}
}
}
}
internal static func scan<U>(into initialResult: U, _ nextPartialResult: @escaping (inout U, Value) -> Void) -> Transformation<U, Error> {
return { action, _ in
var accumulator = initialResult
return { event in
action(event.map { value in
nextPartialResult(&accumulator, value)
return accumulator
})
}
}
}
internal static func scan<U>(_ initialResult: U, _ nextPartialResult: @escaping (U, Value) -> U) -> Transformation<U, Error> {
return scan(into: initialResult) { $0 = nextPartialResult($0, $1) }
}
internal static func reduce<U>(into initialResult: U, _ nextPartialResult: @escaping (inout U, Value) -> Void) -> Transformation<U, Error> {
return { action, _ in
var accumulator = initialResult
return { event in
switch event {
case let .value(value):
nextPartialResult(&accumulator, value)
case .completed:
action(.value(accumulator))
action(.completed)
case .interrupted:
action(.interrupted)
case let .failed(error):
action(.failed(error))
}
}
}
}
internal static func reduce<U>(_ initialResult: U, _ nextPartialResult: @escaping (U, Value) -> U) -> Transformation<U, Error> {
return reduce(into: initialResult) { $0 = nextPartialResult($0, $1) }
}
internal static func observe(on scheduler: Scheduler) -> Transformation<Value, Error> {
return { action, lifetime in
lifetime.observeEnded {
scheduler.schedule {
action(.interrupted)
}
}
return { event in
scheduler.schedule {
if !lifetime.hasEnded {
action(event)
}
}
}
}
}
internal static func lazyMap<U>(on scheduler: Scheduler, transform: @escaping (Value) -> U) -> Transformation<U, Error> {
return { action, lifetime in
let box = Atomic<Value?>(nil)
let completionDisposable = SerialDisposable()
let valueDisposable = SerialDisposable()
lifetime += valueDisposable
lifetime += completionDisposable
lifetime.observeEnded {
scheduler.schedule {
action(.interrupted)
}
}
return { event in
switch event {
case let .value(value):
// Schedule only when there is no prior outstanding value.
if box.swap(value) == nil {
valueDisposable.inner = scheduler.schedule {
if let value = box.swap(nil) {
action(.value(transform(value)))
}
}
}
case .completed, .failed:
// Completion and failure should not discard the outstanding
// value.
completionDisposable.inner = scheduler.schedule {
action(event.map(transform))
}
case .interrupted:
// `interrupted` overrides any outstanding value and any
// scheduled completion/failure.
valueDisposable.dispose()
completionDisposable.dispose()
scheduler.schedule {
action(.interrupted)
}
}
}
}
}
internal static func delay(_ interval: TimeInterval, on scheduler: DateScheduler) -> Transformation<Value, Error> {
precondition(interval >= 0)
return { action, lifetime in
lifetime.observeEnded {
scheduler.schedule {
action(.interrupted)
}
}
return { event in
switch event {
case .failed, .interrupted:
scheduler.schedule {
action(event)
}
case .value, .completed:
let date = scheduler.currentDate.addingTimeInterval(interval)
scheduler.schedule(after: date) {
if !lifetime.hasEnded {
action(event)
}
}
}
}
}
}
internal static func throttle(_ interval: TimeInterval, on scheduler: DateScheduler) -> Transformation<Value, Error> {
precondition(interval >= 0)
return { action, lifetime in
let state: Atomic<ThrottleState<Value>> = Atomic(ThrottleState())
let schedulerDisposable = SerialDisposable()
lifetime.observeEnded {
schedulerDisposable.dispose()
scheduler.schedule { action(.interrupted) }
}
return { event in
guard let value = event.value else {
schedulerDisposable.inner = scheduler.schedule {
action(event)
}
return
}
let scheduleDate: Date = state.modify { state in
state.pendingValue = value
let proposedScheduleDate: Date
if let previousDate = state.previousDate, previousDate <= scheduler.currentDate {
proposedScheduleDate = previousDate.addingTimeInterval(interval)
} else {
proposedScheduleDate = scheduler.currentDate
}
return proposedScheduleDate < scheduler.currentDate ? scheduler.currentDate : proposedScheduleDate
}
schedulerDisposable.inner = scheduler.schedule(after: scheduleDate) {
if let pendingValue = state.modify({ $0.retrieveValue(date: scheduleDate) }) {
action(.value(pendingValue))
}
}
}
}
}
internal static func debounce(_ interval: TimeInterval, on scheduler: DateScheduler, discardWhenCompleted: Bool) -> Transformation<Value, Error> {
precondition(interval >= 0)
let state: Atomic<ThrottleState<Value>> = Atomic(ThrottleState(previousDate: scheduler.currentDate, pendingValue: nil))
return { action, lifetime in
let d = SerialDisposable()
lifetime.observeEnded {
d.dispose()
scheduler.schedule { action(.interrupted) }
}
return { event in
switch event {
case let .value(value):
state.modify { state in
state.pendingValue = value
}
let date = scheduler.currentDate.addingTimeInterval(interval)
d.inner = scheduler.schedule(after: date) {
if let pendingValue = state.modify({ $0.retrieveValue(date: date) }) {
action(.value(pendingValue))
}
}
case .completed:
d.inner = scheduler.schedule {
let pending: (value: Value, previousDate: Date)? = state.modify { state in
defer { state.pendingValue = nil }
guard let pendingValue = state.pendingValue, let previousDate = state.previousDate else { return nil }
return (pendingValue, previousDate)
}
if !discardWhenCompleted, let (pendingValue, previousDate) = pending {
scheduler.schedule(after: previousDate.addingTimeInterval(interval)) {
action(.value(pendingValue))
action(.completed)
}
} else {
action(.completed)
}
}
case .failed, .interrupted:
d.inner = scheduler.schedule {
action(event)
}
}
}
}
}
internal static func collect(every interval: DispatchTimeInterval, on scheduler: DateScheduler, skipEmpty: Bool, discardWhenCompleted: Bool) -> Transformation<[Value], Error> {
return { action, lifetime in
let state = Atomic<CollectEveryState<Value>>(.init(skipEmpty: skipEmpty))
let d = SerialDisposable()
d.inner = scheduler.schedule(after: scheduler.currentDate.addingTimeInterval(interval), interval: interval, leeway: interval * 0.1) {
let (currentValues, isCompleted) = state.modify { ($0.collect(), $0.isCompleted) }
if let currentValues = currentValues {
action(.value(currentValues))
}
if isCompleted {
action(.completed)
}
}
lifetime.observeEnded {
d.dispose()
scheduler.schedule { action(.interrupted) }
}
return { event in
switch event {
case let .value(value):
state.modify { $0.values.append(value) }
case let .failed(error):
d.inner = scheduler.schedule { action(.failed(error)) }
case .completed where !discardWhenCompleted:
state.modify { $0.isCompleted = true }
case .completed:
d.inner = scheduler.schedule { action(.completed) }
case .interrupted:
d.inner = scheduler.schedule { action(.interrupted) }
}
}
}
}
}
private struct CollectEveryState<Value> {
let skipEmpty: Bool
var values: [Value] = []
var isCompleted: Bool = false
init(skipEmpty: Bool) {
self.skipEmpty = skipEmpty
}
var hasValues: Bool {
return !values.isEmpty || !skipEmpty
}
mutating func collect() -> [Value]? {
guard hasValues else { return nil }
defer { values.removeAll() }
return values
}
}
private struct ThrottleState<Value> {
var previousDate: Date?
var pendingValue: Value?
mutating func retrieveValue(date: Date) -> Value? {
defer {
if pendingValue != nil {
pendingValue = nil
previousDate = date
}
}
return pendingValue
}
}
extension Signal.Event where Error == Never {
internal static func promoteError<F>(_: F.Type) -> Transformation<Value, F> {
return { action, _ in
return { event in
switch event {
case let .value(value):
action(.value(value))
case .failed:
fatalError("Never is impossible to construct")
case .completed:
action(.completed)
case .interrupted:
action(.interrupted)
}
}
}
}
}
extension Signal.Event where Value == Never {
internal static func promoteValue<U>(_: U.Type) -> Transformation<U, Error> {
return { action, _ in
return { event in
switch event {
case .value:
fatalError("Never is impossible to construct")
case let .failed(error):
action(.failed(error))
case .completed:
action(.completed)
case .interrupted:
action(.interrupted)
}
}
}
}
}
| mit | 0d1f847dd33e1d0326aa1f1548b693fe | 23.743938 | 177 | 0.648073 | 3.659065 | false | false | false | false |
vijaytholpadi/calc-swift | testCalc/testCalc/ViewController.swift | 1 | 3861 | //
// ViewController.swift
// testCalc
//
// Created by Vijay Tholpadi on 7/22/14.
// Copyright (c) 2014 TheGeekProjekt. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var lastNumber :String = ""
@IBOutlet var answerField: UILabel!
@IBOutlet var operatorField: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonTapped(theButton: UIButton) {
println(theButton.titleLabel.text)
println("button tapped!")
if answerField.text == "0.0"{
answerField.text = theButton.titleLabel.text
}else{
answerField.text = answerField.text + theButton.titleLabel.text
}
}
@IBAction func enterTapped(AnyObject?){
var num1:Float = lastNumber.bridgeToObjectiveC().floatValue
var num2:Float = answerField.text.bridgeToObjectiveC().floatValue
if (num1 == 0.0) || (num2 == 0.0) {
showError()
return
}
var answer:Float = 0.0
if operatorField.text == "+"{
answer = num1 + num2
} else if operatorField.text == "-"{
answer = num1 - num2
}else if operatorField.text == "*"{
answer = num1 * num2
}else if operatorField.text == "/"{
answer = num1 / num2
}
answerField.text = "\(answer)"
operatorField.text = ""
}
@IBAction func clearTapped(theButton: UIButton){
println(theButton.titleLabel.text)
operatorField.text = ""
answerField.text = "0.0"
lastNumber = ""
}
@IBAction func plusTapped(theButton: UIButton) {
println(theButton.titleLabel.text)
if operatorField.text == ""{
operatorField.text = "+"
lastNumber = answerField.text
answerField.text = "0.0"
}else{
enterTapped(nil)
operatorField.text = "+"
}
}
@IBAction func minusTapped(theButton: UIButton) {
println(theButton.titleLabel.text)
if operatorField.text == ""{
operatorField.text = "-"
lastNumber = answerField.text
answerField.text = "0.0"
}else{
enterTapped(nil)
operatorField.text = "-"
}
}
@IBAction func multiplyTapped(theButton: UIButton) {
println(theButton.titleLabel.text)
if operatorField?.text == ""{
operatorField.text = "*"
lastNumber = answerField.text
answerField.text = "0.0"
}else{
enterTapped(nil)
operatorField.text = "*"
}
}
@IBAction func divideTapped(theButton: UIButton) {
println(theButton.titleLabel.text)
if operatorField.text == ""{
operatorField.text = "/"
lastNumber = answerField.text
answerField.text = "0.0"
}else{
enterTapped(nil)
operatorField.text = "/"
}
}
@IBAction func moduloTapped(theButton: UIButton) {
println(theButton.titleLabel.text)
if operatorField.text == ""{
operatorField.text = "%"
lastNumber = answerField.text
answerField.text = "0.0"
}else{
enterTapped(nil)
operatorField.text = "%"
}
}
@IBAction func decimalPointPressed(theButton: UIButton){
answerField.text = answerField.text + "."
}
func showError(){
println("There was an error. Please inspect.")
}
}
| apache-2.0 | 8ed7e299629723cf9be6d568a0e0f6ad | 27.813433 | 80 | 0.556851 | 4.601907 | false | false | false | false |
hermantai/samples | ios/SwiftUI-Cookbook-2nd-Edition/Chapter13-Handling-Core-Data-in-SwiftUI/02-Showing-Core-Data-objects-with-@FetchRequest/FetchContacts/FetchContacts/CoreDataStack.swift | 1 | 1180 | //
// CoreDataStack.swift
// CoreDataStack
//
// Created by Giordano Scalzo on 01/09/2021.
//
import Foundation
import CoreData
class CoreDataStack {
private let persistentContainer: NSPersistentContainer
var managedObjectContext: NSManagedObjectContext {
persistentContainer.viewContext
}
init(modelName: String) {
persistentContainer = {
let container = NSPersistentContainer(name: modelName)
container.loadPersistentStores { description, error in
if let error = error {
print(error)
}
}
return container
}()
}
func save () {
guard managedObjectContext.hasChanges else { return }
do {
try managedObjectContext.save()
} catch {
print(error)
}
}
func insertContact(firstName: String,
lastName: String,
phoneNumber: String) {
let contact = Contact(context: managedObjectContext)
contact.firstName = firstName
contact.lastName = lastName
contact.phoneNumber = phoneNumber
}
}
| apache-2.0 | c061999439203716a58f5f31e8a5944b | 24.652174 | 66 | 0.583898 | 5.841584 | false | false | false | false |
ShauryaS/Bookkeeper | Bookkeeping/SelectPurposeView.swift | 1 | 4588 | //
// SelectPurposeView.swift
// Bookkeeping
//
// Created by Shaurya Srivastava on 7/14/16.
// Copyright © 2016 CFO-online, Inc. All rights reserved.
//
import Foundation
import UIKit
class SelectPurposeView: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate{
//variable for the UIPickerView
@IBOutlet var pickerView: UIPickerView!
//variable to store the string text of the option selected
fileprivate var valSelected = ""
//variable for the type label text
var typeLabel = ""
//variable for the notes label text
var notes = ""
//variable for the attendees label text
var attendees = ""
//variable for the imgPath label text
var imgPath = ""
//array for the data to be loaded into the UIPickerView
var pickerDataSource = [""]
//called when the view is loaded
//Params: none
//sets the data of the UIPickerView
//Return: none
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title="Select Expense Purpose"
pickerDataSource = dataPurposes
pickerView.dataSource = self;
pickerView.delegate = self;
}
//function that is called when view is going to appear
//Param: boolean variable to determine if view should be animated
//sets the navigation bar to be visible
//sets the tint of the notification bar to white (light content)
//sets the color of the notification bar to black
//Return: none
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = false
UIApplication.shared.isStatusBarHidden = false
UIApplication.shared.statusBarStyle = .lightContent
let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
if statusBar.responds(to: #selector(setter: UIView.backgroundColor)) {
statusBar.backgroundColor = UIColor.black
}
}
//default view method
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//params: UIPickerView - used to override inherited method
//func returns number of columns
//Return: int
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
//params: UIPickerView, Int
//func returns the number of rows
//Return: Int
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerDataSource.count;
}
//params: UIPickerView, Int
//func returns the text of the option selected
//uses row (Int) to determine the variable selected
//Return: String
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerDataSource[row]
}
//param: AnyObject that is recieved by button
//param not used but necessary as button always sends an AnyObject
//switches view to upload receipt view
@IBAction func choose(_ sender: AnyObject) {
self.performSegue(withIdentifier: "SelectToMainSegue", sender: sender)
}
//params: UIPickerView, Int
//saves the text of the option selected to a new constant variable
//text also saved in valSelected var
//Return: none
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
// selected value in Uipickerview in Swift
let value=pickerDataSource[row]
valSelected = value
}
//params: UIStoryboardSegue - to monitor the segue used - and AnyObject
//func used to send data through the segue
//sends attendees text, notes text, and img path if going to select type view
//takes the valSelected variable and sets it as the type label text
//Return: none
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if "SelectToMainSegue"==segue.identifier{
let yourNextViewController = (segue.destination as! UploadReceiptView)
yourNextViewController.purpose = valSelected
yourNextViewController.type = typeLabel
if notes != ""{
yourNextViewController.notesText = notes
}
if attendees != ""{
yourNextViewController.attendeesText = attendees
}
if imgPath != ""{
yourNextViewController.imgPath = imgPath
}
}
}
}
| apache-2.0 | cc1be3f828665cdc6fb36018bbe1cf84 | 34.015267 | 111 | 0.662743 | 5.136618 | false | false | false | false |
byvapps/ByvUtils | ByvUtils/Classes/Double+extension.swift | 1 | 1425 | //
// Double+extension.swift
// Pods
//
// Created by Adrian Apodaca on 27/4/17.
//
//
import Foundation
public extension Double {
public func asEuros(decimals:Int = 2) -> String {
return self.asCurrency(locale: Locale(identifier: "es_ES"), decimals:decimals)
}
public func asMyCurrency(decimals:Int = 2) -> String {
return self.asCurrency(locale: Locale.current, decimals:decimals)
}
public func asCurrency(currencyCode: String, decimals:Int = 2) -> String {
if let locale = Utils.locale(currencyCode: currencyCode) {
return self.asCurrency(locale: locale, decimals:decimals)
}
return String(self)
}
public func asCurrency(locale: Locale, decimals:Int = 2) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = decimals;
formatter.locale = Locale(identifier: Locale.current.identifier)
if let result = formatter.string(from: NSNumber(value: self)) {
return result
}
return String(self)
}
public func roundTo(decimals: Int) -> Double {
let divisor = pow(10.0, Double(decimals))
return (self * divisor).rounded() / divisor
}
public func cleanString() -> String {
return self / 1 == 0 ? String(format: "%.0f", self) : String(self)
}
}
| mit | edfccee7e94570d752a2c15d03b120ef | 28.6875 | 86 | 0.618947 | 4.215976 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.