repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
xivol/MCS-V3-Mobile | examples/uiKit/UIKitCatalog.playground/Pages/UILabel.xcplaygroundpage/Contents.swift | 1 | 924 | //: # UILabel
//: A view that displays one or more lines of read-only text, often used in conjunction with controls to describe their intended purpose.
//:
//: [UILabel API Reference](https://developer.apple.com/reference/uikit/uilabel)
import UIKit
import PlaygroundSupport
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 250, height: 250))
label.backgroundColor = #colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 1)
label.text = "Hello Label!"
label.textColor = #colorLiteral(red: 0.9686274529, green: 0.78039217, blue: 0.3450980484, alpha: 1)
label.shadowColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
label.textAlignment = .center
label.font = UIFont(name: "AmericanTypewriter", size: 32)
// for other font family names visit http://iosfonts.com/
PlaygroundPage.current.liveView = label
//: [Previous](@previous) | [Table of Contents](TableOfContents) | [Next](@next)
| mit |
debugsquad/Hyperborea | Hyperborea/View/Favorites/VFavoritesCell.swift | 1 | 2830 | import UIKit
class VFavoritesCell:UICollectionViewCell
{
private weak var label:UILabel!
private weak var imageView:UIImageView!
private let kLabelRight:CGFloat = -10
private let kImageWidth:CGFloat = 32
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
let label:UILabel = UILabel()
label.isUserInteractionEnabled = false
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.clear
label.font = UIFont.bold(size:17)
label.numberOfLines = 2
self.label = label
let imageView:UIImageView = UIImageView()
imageView.isUserInteractionEnabled = false
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.clipsToBounds = true
imageView.contentMode = UIViewContentMode.center
self.imageView = imageView
addSubview(label)
addSubview(imageView)
NSLayoutConstraint.equalsVertical(
view:imageView,
toView:self)
NSLayoutConstraint.leftToLeft(
view:imageView,
toView:self)
NSLayoutConstraint.width(
view:imageView,
constant:kImageWidth)
NSLayoutConstraint.equalsVertical(
view:label,
toView:self)
NSLayoutConstraint.leftToRight(
view:label,
toView:imageView)
NSLayoutConstraint.rightToRight(
view:label,
toView:self,
constant:kLabelRight)
}
required init?(coder:NSCoder)
{
return nil
}
override var isSelected:Bool
{
didSet
{
hover()
}
}
override var isHighlighted:Bool
{
didSet
{
hover()
}
}
//MARK: private
private func hover()
{
if isSelected
{
backgroundColor = UIColor.hyperBlue
label.textColor = UIColor.white
}
else
{
backgroundColor = UIColor.white
label.textColor = UIColor.black
}
}
private func loadSquare(languageRaw:Int16)
{
let language:MLanguage = MLanguage.language(rawValue:languageRaw)
DispatchQueue.main.async
{ [weak self] in
self?.imageView.image = language.imageSquare
}
}
//MARK: public
func config(model:MFavoritesItem)
{
label.text = model.word
hover()
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.loadSquare(languageRaw:model.languageRaw)
}
}
}
| mit |
inket/stts | stts/ServiceTableView/StatusTableCell.swift | 1 | 4373 | //
// StatusTableCell.swift
// stts
//
import Cocoa
class StatusTableCell: NSTableCellView {
let statusIndicator = StatusIndicator()
let stackView = NSStackView()
let titleField = NSTextField()
let statusField = NSTextField()
enum Layout {
static let verticalPadding: CGFloat = 10
static let verticalSpacing: CGFloat = 4
static let horizontalPadding: CGFloat = 8
static let horizontalSpacing: CGFloat = 8
static let titleFont = NSFont.systemFont(ofSize: 13)
static let messageFont = NSFontManager.shared.font(
withFamily: titleFont.fontName,
traits: NSFontTraitMask.italicFontMask,
weight: 5,
size: 11
)
static let statusIndicatorSize = CGSize(width: 14, height: 14)
private static let dummyCell = StatusTableCell(frame: .zero)
static func heightOfRow(for service: Service, width: CGFloat) -> CGFloat {
let nsScrollerWidth: CGFloat = 16
let realRowWidth = width - (nsScrollerWidth - 4) // 4 by trial & error
dummyCell.frame.size = CGSize(width: realRowWidth, height: 400)
dummyCell.setup(with: service)
dummyCell.layoutSubtreeIfNeeded()
return dummyCell.stackView.frame.size.height + (verticalPadding * 2)
}
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
textField?.removeFromSuperview()
statusIndicator.scaleUnitSquare(to: NSSize(width: 0.3, height: 0.3))
statusIndicator.translatesAutoresizingMaskIntoConstraints = false
addSubview(statusIndicator)
stackView.orientation = .vertical
stackView.distribution = .fill
stackView.alignment = .leading
stackView.spacing = Layout.verticalSpacing
stackView.translatesAutoresizingMaskIntoConstraints = false
addSubview(stackView)
titleField.isEditable = false
titleField.isBordered = false
titleField.isSelectable = false
titleField.maximumNumberOfLines = 2
titleField.cell!.truncatesLastVisibleLine = true
titleField.cell!.lineBreakMode = .byWordWrapping
titleField.cell!.wraps = true
titleField.font = Layout.titleFont
titleField.textColor = NSColor.labelColor
titleField.backgroundColor = NSColor.clear
statusField.isEditable = false
statusField.isBordered = false
statusField.isSelectable = false
statusField.font = Layout.messageFont
statusField.textColor = NSColor.secondaryLabelColor
statusField.maximumNumberOfLines = 6
statusField.cell!.truncatesLastVisibleLine = true
statusField.cell!.lineBreakMode = .byWordWrapping
statusField.cell!.wraps = true
statusField.backgroundColor = NSColor.clear
[titleField, statusField].forEach {
stackView.addArrangedSubview($0)
}
NSLayoutConstraint.activate([
statusIndicator.heightAnchor.constraint(equalToConstant: Layout.statusIndicatorSize.height),
statusIndicator.widthAnchor.constraint(equalToConstant: Layout.statusIndicatorSize.height),
statusIndicator.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Layout.horizontalPadding),
statusIndicator.centerYAnchor.constraint(equalTo: centerYAnchor),
stackView.leadingAnchor.constraint(
equalTo: statusIndicator.trailingAnchor,
constant: Layout.horizontalSpacing
),
stackView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -Layout.horizontalPadding),
stackView.topAnchor.constraint(equalTo: topAnchor, constant: Layout.verticalPadding),
stackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -Layout.verticalPadding)
])
}
func setup(with service: Service) {
titleField.stringValue = service.name
statusIndicator.status = service.status
statusField.stringValue = service.message
statusField.isHidden = service.status == .good && Preferences.shared.hideServiceDetailsIfAvailable
}
}
| mit |
proversity-org/edx-app-ios | Source/CourseGenericBlockTableViewCell.swift | 1 | 2817 | //
// CourseHTMLTableViewCell.swift
// edX
//
// Created by Ehmad Zubair Chughtai on 14/05/2015.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
class CourseGenericBlockTableViewCell : UITableViewCell, CourseBlockContainerCell {
fileprivate let content = CourseOutlineItemView()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(content)
content.snp.makeConstraints { make in
make.edges.equalTo(contentView)
}
}
var block : CourseBlock? = nil {
didSet {
content.setTitleText(title: block?.displayName)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class CourseHTMLTableViewCell: CourseGenericBlockTableViewCell {
static let identifier = "CourseHTMLTableViewCellIdentifier"
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style : style, reuseIdentifier : reuseIdentifier)
content.setContentIcon(icon: Icon.CourseHTMLContent)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class CourseProblemTableViewCell : CourseGenericBlockTableViewCell {
static let identifier = "CourseProblemTableViewCellIdentifier"
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style : style, reuseIdentifier : reuseIdentifier)
content.setContentIcon(icon: Icon.CourseProblemContent)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class CourseUnknownTableViewCell: CourseGenericBlockTableViewCell {
static let identifier = "CourseUnknownTableViewCellIdentifier"
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
content.leadingIconColor = OEXStyles.shared().neutralBase()
content.setContentIcon(icon: Icon.CourseUnknownContent)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class DiscussionTableViewCell: CourseGenericBlockTableViewCell {
static let identifier = "DiscussionTableViewCellIdentifier"
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
content.setContentIcon(icon: Icon.Discussions)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 |
debugsquad/Hyperborea | Hyperborea/View/Settings/VSettingsCellReview.swift | 1 | 1822 | import UIKit
class VSettingsCellReview:VSettingsCell
{
private let kTitleLeft:CGFloat = 10
private let kTitleWidth:CGFloat = 250
private let kImageWidth:CGFloat = 100
override init(frame:CGRect)
{
super.init(frame:frame)
let labelTitle:UILabel = UILabel()
labelTitle.isUserInteractionEnabled = false
labelTitle.translatesAutoresizingMaskIntoConstraints = false
labelTitle.backgroundColor = UIColor.clear
labelTitle.font = UIFont.bolder(size:15)
labelTitle.textColor = UIColor.white
labelTitle.numberOfLines = 2
labelTitle.text = NSLocalizedString("VSettingsCellReview_labelTitle", comment:"")
let imageView:UIImageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.clipsToBounds = true
imageView.contentMode = UIViewContentMode.center
imageView.isUserInteractionEnabled = false
imageView.image = #imageLiteral(resourceName: "assetGenericReview")
addSubview(labelTitle)
addSubview(imageView)
NSLayoutConstraint.equalsVertical(
view:labelTitle,
toView:self)
NSLayoutConstraint.leftToLeft(
view:labelTitle,
toView:self,
constant:kTitleLeft)
NSLayoutConstraint.width(
view:labelTitle,
constant:kTitleWidth)
NSLayoutConstraint.equalsVertical(
view:imageView,
toView:self)
NSLayoutConstraint.rightToRight(
view:imageView,
toView:self)
NSLayoutConstraint.width(
view:imageView,
constant:kImageWidth)
}
required init?(coder:NSCoder)
{
return nil
}
}
| mit |
gkaimakas/SwiftyForms | SwiftyForms/Classes/Inputs/LocationInput.swift | 1 | 2328 | //
// LocationInput.swift
// Pods
//
// Created by Γιώργος Καϊμακάς on 29/06/16.
//
//
import Foundation
public typealias LocationInputEvent = (LocationInput) -> Void
open class LocationInput: Input {
open static let Latitude = "latitude"
open static let Longitude = "longitude"
fileprivate var _previousLatitude: String? = nil
fileprivate var _previousLongitude: String? = nil
fileprivate var _locationEvents: [LocationInputEvent] = []
override open var data: [String : Any]? {
if isValid == false {
return nil
}
return [
attributeLatitude : latitude,
attributeLongitude : longitude
]
}
override open var isValid: Bool {
return _validate()
}
open var latitude: String {
willSet {
_previousLatitude = self.latitude
}
didSet {
self._dirty = true
for event in _locationEvents {
event(self)
}
}
}
open var longitude: String {
willSet {
_previousLongitude = self.longitude
}
didSet {
self._dirty = true
for event in _locationEvents {
event(self)
}
}
}
open var previousLatitude: String? {
return _previousLatitude
}
open var previousLongitude: String? {
return _previousLongitude
}
open var attributeLatitude: String = LocationInput.Latitude
open var attributeLongitude: String = LocationInput.Longitude
public convenience init(name: String) {
self.init(name: name, enabled: true, hidden: false)
}
public override init(name: String, enabled: Bool, hidden: Bool) {
self.latitude = "0.0"
self.longitude = "0.0"
super.init(name: name, enabled: enabled, hidden: hidden)
}
open func on(_ location: LocationInputEvent? = nil) {
if let event = location {
_locationEvents.append(event)
}
}
open func setAttributeLatitude(_ name: String) -> Self {
attributeLatitude = name
return self
}
open func setAttributeLongitude(_ name: String) -> Self {
attributeLongitude = name
return self
}
fileprivate func _validate() -> Bool {
let latitudeValidation = self._validationRules
.map() { $0.rule }
.map() { $0(latitude) }
.reduce(true) { $0 && $1 }
let longitudeValidation = self._validationRules
.map() { $0.rule }
.map() { $0(latitude) }
.reduce(true) { $0 && $1 }
return latitudeValidation && longitudeValidation
}
}
| mit |
wayfair/brickkit-ios | Example/Source/Bricks/Custom/WhoToFollowBrick.swift | 2 | 1981 | //
// WhoToFollow.swift
// BrickKit
//
// Created by Yusheng Yang on 9/20/16.
// Copyright © 2016 Wayfair LLC. All rights reserved.
//
import Foundation
import BrickKit
class WhoToFollowBrick: Brick {
weak var dataSource: WhoToFollowBrickDataSource?
init(_ identifier: String, width: BrickDimension = .ratio(ratio: 1), height: BrickDimension = .auto(estimate: .fixed(size: 50)), backgroundColor: UIColor = UIColor.clear, backgroundView: UIView? = nil, dataSource: WhoToFollowBrickDataSource) {
self.dataSource = dataSource
super.init(identifier, size: BrickSize(width: width, height: height), backgroundColor: backgroundColor, backgroundView: backgroundView)
}
}
protocol WhoToFollowBrickDataSource: class {
func whoToFollowImage(cell: WhoToFollowBrickCell) -> UIImage
func whoToFollowTitle(cell: WhoToFollowBrickCell) -> String
func whoToFollowDescription(cell: WhoToFollowBrickCell) -> String
func whoToFollowAtTag(cell: WhoToFollowBrickCell) -> String
}
class WhoToFollowBrickCell: BrickCell, Bricklike {
typealias BrickType = WhoToFollowBrick
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var followButton: UIButton!
@IBOutlet weak var atTag: UILabel!
override func updateContent() {
super.updateContent()
followButton.layer.cornerRadius = 5.0
followButton.layer.borderWidth = 1.0
followButton.layer.borderColor = self.tintColor.cgColor
imageView.layer.cornerRadius = 4
imageView.clipsToBounds = true
imageView.image = brick.dataSource?.whoToFollowImage(cell: self)
titleLabel.text = brick.dataSource?.whoToFollowTitle(cell: self)
descriptionLabel.text = brick.dataSource?.whoToFollowDescription(cell: self)
atTag.text = brick.dataSource?.whoToFollowAtTag(cell: self)
}
}
| apache-2.0 |
Foild/SugarRecord | spec/Models/RealmObjectTests.swift | 1 | 7221 | //
// RealmObjectTests.swift
// SugarRecord
//
// Created by Pedro Piñera Buendia on 20/09/14.
// Copyright (c) 2014 SugarRecord. All rights reserved.
//
import XCTest
import CoreData
import Realm
class RealmObjectTests: XCTestCase
{
override func setUp()
{
SugarRecord.addStack(DefaultREALMStack(stackName: "RealmTest", stackDescription: "Realm stack for tests"))
}
override func tearDown() {
SugarRecord.cleanup()
SugarRecord.removeDatabase()
}
func testObjectCreation()
{
var realmObject: RealmObject = RealmObject.create() as! RealmObject
realmObject.name = "Realmy"
realmObject.age = 22
realmObject.email = "test@mail.com"
realmObject.city = "TestCity"
realmObject.birthday = NSDate()
let saved: Bool = realmObject.save()
var realmObject2: RealmObject = RealmObject.create() as! RealmObject
realmObject2.name = "Realmy"
realmObject2.age = 22
realmObject2.email = "test@mail.com"
realmObject2.city = "TestCity"
realmObject2.birthday = NSDate()
let saved2: Bool = realmObject2.save()
XCTAssertEqual(RealmObject.all().find().count, 2, "The number of objects fetched should be equal to 2")
realmObject.beginWriting().delete().endWriting()
realmObject2.beginWriting().delete().endWriting()
}
func testObjectDeletion()
{
var realmObject: RealmObject = RealmObject.create() as! RealmObject
realmObject.name = "Realmy"
realmObject.age = 22
realmObject.email = "test@mail.com"
realmObject.city = "TestCity"
realmObject.birthday = NSDate()
let saved: Bool = realmObject.save()
realmObject.beginWriting().delete().endWriting()
XCTAssertEqual(RealmObject.all().find().count, 0, "The number of objects fetched after the deletion should be equal to 0")
}
func testAllObjectsDeletion()
{
var realmObject: RealmObject = RealmObject.create() as! RealmObject
realmObject.name = "Realmy"
realmObject.age = 22
realmObject.email = "test@mail.com"
realmObject.city = "TestCity"
realmObject.birthday = NSDate()
let saved: Bool = realmObject.save()
var realmObject2: RealmObject = RealmObject.create() as! RealmObject
realmObject2.name = "Realmy"
realmObject2.age = 22
realmObject2.email = "test@mail.com"
realmObject2.city = "TestCity"
realmObject2.birthday = NSDate()
let saved2: Bool = realmObject2.save()
realmObject.beginWriting().delete().endWriting()
realmObject2.beginWriting().delete().endWriting()
XCTAssertEqual(RealmObject.all().find().count, 0, "The number of objects fetched after the deletion should be equal to 0")
}
func testObjectsEdition()
{
var realmObject: RealmObject? = nil
realmObject = RealmObject.create() as? RealmObject
realmObject?.save()
realmObject!.beginWriting()
realmObject!.name = "Testy"
realmObject!.endWriting()
let fetchedObject: RealmObject = RealmObject.allObjects().firstObject() as! RealmObject
XCTAssertEqual(fetchedObject.name, "Testy", "The name of the fetched object should be Testy")
realmObject!.beginWriting().delete().endWriting()
}
func testObjectQuerying()
{
var realmObject: RealmObject? = nil
var realmObject2: RealmObject? = nil
realmObject = RealmObject.create() as? RealmObject
realmObject!.name = "Realmy"
realmObject!.age = 22
realmObject!.email = "test@mail.com"
realmObject!.city = "TestCity"
realmObject!.birthday = NSDate()
let saved: Bool = realmObject!.save()
realmObject2 = RealmObject.create() as? RealmObject
realmObject2!.name = "Realmy2"
realmObject2!.age = 22
realmObject2!.email = "test@mail.com"
realmObject2!.city = "TestCity2"
realmObject2!.birthday = NSDate()
let saved2: Bool = realmObject2!.save()
XCTAssertEqual(RealmObject.all().find().count, 2, "It should return 2 elements")
XCTAssertEqual(RealmObject.by("age", equalTo: "22").find().count, 2, "It should return 2 elements with the age of 22")
XCTAssertEqual(RealmObject.by("age", equalTo: "10").find().count, 0, "It should return 0 elements with the age of 10")
XCTAssertEqual((RealmObject.sorted(by: "name", ascending: true).first().find().firstObject() as! RealmObject).name, "Realmy", "The name of the first object returned should be Realmy")
XCTAssertEqual((RealmObject.sorted(by: "name", ascending: true).last().find().firstObject() as! RealmObject).name, "Realmy2", "The name of the first object returned should be Realmy2")
XCTAssertEqual(RealmObject.sorted(by: "name", ascending: true).firsts(20).find().count, 2, "The number of fetched elements using firsts should be equal to 2")
XCTAssertEqual(RealmObject.sorted(by: "name", ascending: true).lasts(20).find().count, 2, "The number of fetched elements using lasts should be equal to 2")
realmObject!.beginWriting().delete().endWriting()
realmObject2!.beginWriting().delete().endWriting()
}
func testObjectsCount()
{
var realmObject: RealmObject? = nil
var realmObject2: RealmObject? = nil
realmObject = RealmObject.create() as? RealmObject
realmObject!.name = "Realmy"
realmObject!.age = 22
realmObject!.email = "test@mail.com"
realmObject!.city = "TestCity"
realmObject!.birthday = NSDate()
let saved: Bool = realmObject!.save()
realmObject2 = RealmObject.create() as? RealmObject
realmObject2!.name = "Realmy2"
realmObject2!.age = 22
realmObject2!.email = "test@mail.com"
realmObject2!.city = "TestCity2"
realmObject2!.birthday = NSDate()
let saved2: Bool = realmObject2!.save()
XCTAssertEqual(RealmObject.count(), 2, "The count should be equal to 2")
XCTAssertEqual(RealmObject.by("name", equalTo: "'Realmy2'").count(), 1, "The count should be equal to 1")
realmObject!.beginWriting().delete().endWriting()
realmObject2!.beginWriting().delete().endWriting()
}
func testObjectsWritingCancellation()
{
var realmObject: RealmObject? = nil
realmObject = RealmObject.create() as? RealmObject
realmObject!.name = "Realmy"
realmObject!.age = 22
realmObject!.email = "test@mail.com"
realmObject!.city = "TestCity"
realmObject!.birthday = NSDate()
_ = realmObject!.save()
realmObject!.beginWriting().delete().cancelWriting()
XCTAssertEqual(RealmObject.all().find().count, 1, "It should return 1 element because the writing transaction was cancelled")
let objects = RealmObject.all().find()
(objects.firstObject() as! RealmObject).beginWriting().delete().endWriting()
XCTAssertEqual(RealmObject.all().find().count, 0, "It should return 0 element because the writing transaction was commited")
}
}
| mit |
vadymmarkov/Faker | Sources/Fakery/Config.swift | 3 | 282 | public struct Config {
public static let defaultLocale: String = "en"
public static let pathExtension: String = "json"
public static var dirPath: String = "Resources/Locales"
public static var dirFrameworkPath: String = ""
public static var dirResourcePath: String = ""
}
| mit |
Aioria1314/WeiBo | WeiBo/WeiBo/Classes/Views/Home/ZXCHomeToolBarView.swift | 1 | 3307 | //
// ZXCHomeToolBarView.swift
// WeiBo
//
// Created by Aioria on 2017/3/30.
// Copyright © 2017年 Aioria. All rights reserved.
//
import UIKit
class ZXCHomeToolBarView: UIView {
var statusViewModel: ZXCStatusViewModel? {
didSet {
let retweetCountStr = statusViewModel?.retweetCountStr
let commentCountStr = statusViewModel?.commentCountStr
let unlikeCountStr = statusViewModel?.unlikeCountStr
btnRetweet?.setTitle(retweetCountStr, for: .normal)
btnComment?.setTitle(commentCountStr, for: .normal)
btnUnlike?.setTitle(unlikeCountStr, for: .normal)
}
}
var btnRetweet: UIButton?
var btnComment: UIButton?
var btnUnlike: UIButton?
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI() {
// backgroundColor = UIColor.white
btnRetweet = addChildButton(imgName: "timeline_icon_retweet", title: "转发")
btnComment = addChildButton(imgName: "timeline_icon_comment", title: "评论")
btnUnlike = addChildButton(imgName: "timeline_icon_unlike", title: "赞")
let firstLine = addChildLineView()
let secondLine = addChildLineView()
btnRetweet!.snp.makeConstraints { (make) in
make.top.left.bottom.equalTo(self)
make.width.equalTo(btnComment!)
}
btnComment!.snp.makeConstraints { (make) in
make.top.bottom.equalTo(self)
make.left.equalTo(btnRetweet!.snp.right)
make.width.equalTo(btnUnlike!)
}
btnUnlike!.snp.makeConstraints { (make) in
make.top.bottom.equalTo(self)
make.left.equalTo(btnComment!.snp.right)
make.right.equalTo(self)
}
firstLine.snp.makeConstraints { (make) in
make.centerX.equalTo(btnComment!.snp.left)
make.centerY.equalTo(self)
}
secondLine.snp.makeConstraints { (make) in
make.centerX.equalTo(btnUnlike!.snp.left)
make.centerY.equalTo(self)
}
}
fileprivate func addChildButton(imgName: String, title: String) -> UIButton {
let btn = UIButton()
btn.setImage(UIImage(named: imgName), for: .normal)
btn.setTitle(title, for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
btn.setBackgroundImage(UIImage(named: "timeline_card_bottom_background"), for: .normal)
// btn.setBackgroundImage(UIImage(named: "timeline_card_bottom_background_highlighted"), for: .highlighted)
btn.setTitleColor(UIColor.darkGray, for: .normal)
addSubview(btn)
return btn
}
fileprivate func addChildLineView() -> UIImageView {
let imgView = UIImageView(image: UIImage(named: "timeline_card_bottom_line"))
addSubview(imgView)
return imgView
}
}
| mit |
scheib/chromium | ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_action_group.swift | 2 | 946 | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import SwiftUI
/// A model class representing a group of `OverflowMenuActions`.
@objcMembers public class OverflowMenuActionGroup: NSObject, ObservableObject {
/// An internal name for the group. This is not displayed to the user, but is
/// used to identify the group.
public let groupName: String
/// The actions for this group.
@Published public var actions: [OverflowMenuAction]
/// The footer at bottom.
public var footer: OverflowMenuFooter?
public init(groupName: String, actions: [OverflowMenuAction], footer: OverflowMenuFooter?) {
self.groupName = groupName
self.actions = actions
self.footer = footer
}
}
// MARK: - Identifiable
extension OverflowMenuActionGroup: Identifiable {
public var id: String {
return groupName
}
}
| bsd-3-clause |
TechnologySpeaks/smile-for-life | smile-for-life/TimersViewController.swift | 1 | 2619 | //
// TimersViewController.swift
// smile-for-life
//
// Created by Lisa Swanson on 2/29/16.
// Copyright © 2016 Technology Speaks. All rights reserved.
//
import UIKit
class TimersViewController: UIViewController {
var timerCount: Int = 0
var timerRunning = false
var timer = Timer()
var countDownTimer: Int = 0
func timerRun() {
var minuts: Int
var seconds: Int
timerRunning = true
timerCount -= 1
minuts = timerCount / 60
seconds = timerCount - (minuts * 60)
let formatedTime = NSString(format: "%2d:%2d", minuts, seconds)
timerLabel.text = String(formatedTime)
if (timerCount == 0) {
timer.invalidate()
timerRunning = false
timerLabel.text = "00:00"
timerCount = 0
flossPopUp()
}
}
func setTimer(){
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(TimersViewController.timerRun), userInfo: nil, repeats: true)
}
func flossPopUp() {
let flossAlert = UIAlertController(title: "Congratulations", message: "I will update your calendar.", preferredStyle: UIAlertControllerStyle.alert)
flossAlert.addAction(UIAlertAction(title: "Close", style: .default, handler: {(action) -> Void in
self.dismiss(animated: true, completion: nil)
}))
self.present(flossAlert, animated: true, completion: nil)
}
@IBOutlet weak var timerLabel: UILabel!
@IBAction func startBrushTimer(_ sender: AnyObject) {
if timerRunning == false {
timerCount = 15
setTimer()
}
}
@IBAction func startFlossTimer(_ sender: AnyObject) {
if timerRunning == false {
timerCount = 180
setTimer()
}
}
@IBAction func cancelTimers(_ sender: AnyObject) {
if timerRunning == true {
timer.invalidate()
timerRunning = false
timerLabel.text = "00:00"
timerCount = 0
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
macshome/cocoaCrypt | CocoaCrypt/CocoaCrypt/CipherSolver.swift | 1 | 196 | //
// CipherSolver.swift
// CocoaCrypt
//
// Created by Josh Wisenbaker on 12/16/14.
// Copyright (c) 2014 Josh Wisenbaker. All rights reserved.
//
import Foundation
class CipherSolver {
}
| mit |
cornerstonecollege/401_02 | 401_swift_examples/FirstPlayground.playground/Contents.swift | 1 | 1550 | var thatIsAVar:Int = 0;
var thatIsMySecondVar = 2
var 🖖 = 2
var 🖖😈🖖 = 3
let 🙏🖖 = 🖖😈🖖 + 🖖
let sum = thatIsAVar + thatIsMySecondVar;
if (sum > 4)
{
print("Hello Sreekanth and Tomoko")
}
else
{
print("Oh oh")
}
func printMyString()
{
print("That is my string")
func secondString()
{
print("Hello")
}
secondString()
}
printMyString()
func U😎U (😡: String, 😴: Bool) -> String
{
if 😴
{
return "I am \(😡) and \(thatIsAVar)"
}
else
{
return "I am not \(😡)"
}
}
let resultFromFunction:String = U😎U("Angry", 😴: false)
print(resultFromFunction)
func add(x:Float, y:Float) -> Float
{
return x + y;
}
let summation:Float = add(3, y:2)
for var i in 0 ..< 3
{
print("Hello \(i)")
}
var array = ["orange", "lime", "banana"]
for var fruit in array
{
print(fruit)
}
var dictionary = ["fruit 1" : "orange", "fruit 2" : "lime", "fruit 3": "banana"]
for var (key, value) in dictionary
{
print("The key is \(key) and the value is \(value)")
}
var i = 0
while i < 3
{
print("While \(i)")
i++
}
i = 4
repeat
{
print("Repeat \(i)")
i++
}while i < 3
let type = "My Type"
switch type
{
case "1": print("1")
case "2", "3", "4": print("2, 3 and 4")
case let x where x.hasPrefix("My"): print("start with my")
default: print("Default Type")
}
switch i
{
case (-2...3): print("From -2 to 3")
case (3...10): print("From 3 to 10")
default: print("Non computable value")
} | gpl-2.0 |
MaticConradi/Blink | Blink/AppDelegate.swift | 1 | 1618 | //
// AppDelegate.swift
// Blink
//
// Created by Matic Conradi on 06/08/2016.
// Copyright © 2016 Conradi.si. All rights reserved.
//
import UIKit
import SystemConfiguration
import UserNotifications
import UserNotificationsUI
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//Notifications
let center = UNUserNotificationCenter.current()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UIApplication.shared.applicationIconBadgeNumber = 0
center.requestAuthorization(options: [.badge, .sound, .alert]) { (granted, error) in }
return true
}
func applicationDidReceiveMemoryWarning(_ application: UIApplication) {
SDImageCache.shared().clearMemory()
}
func applicationWillResignActive(_ application: UIApplication) {
print("ℹ️ App will resign active.")
}
func applicationDidEnterBackground(_ application: UIApplication) {
print("ℹ️ App did enter background.")
}
func applicationWillEnterForeground(_ application: UIApplication) {
print("ℹ️ App will enter foreground.")
}
func applicationDidBecomeActive(_ application: UIApplication) {
print("ℹ️ App did become active.")
}
func applicationWillTerminate(_ application: UIApplication) {
SDImageCache.shared().clearMemory()
//SDImageCache.shared().clearDisk()
print("ℹ️ App will terminate.")
}
}
| gpl-3.0 |
22377832/ccyswift | WebViewDemo/WebViewDemo/ViewController.swift | 1 | 628 | //
// ViewController.swift
// WebViewDemo
//
// Created by sks on 17/2/9.
// Copyright © 2017年 chen. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.loadRequest(URLRequest(url: URL(string:"http://www.ccyag.com")!))
// 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.
}
}
| mit |
chenliang2016/CLCore | CLCore/RouterConfig.swift | 1 | 735 | //
// RouterConfig.swift
// CLIOSFrame
//
// Created by chenliang on 2017/1/1.
// Copyright © 2017年 chenliang. All rights reserved.
//
import Foundation
enum RouterOpenType {
case push
case present
}
public struct Router {
var routerUrl : String
var routerVC : String
var openType : RouterOpenType
var needToValidataToken : Bool = false
}
open class RouterConfig {
static let instance = RouterConfig()
var routers : [String:Router] = [:]
}
extension RouterConfig {
public func initRouter(routers : [String:Router]) {
self.routers = routers
}
public func getRouterFromKey(routerKey:String) -> Router? {
return RouterConfig.instance.routers[routerKey]
}
}
| mit |
github/codeql | swift/ql/test/extractor-tests/errors/overloaded.swift | 1 | 82 | //codeql-extractor-expected-status: 1
func foo() {}
func foo(_: Int) {}
_ = foo
| mit |
miradesne/gamepoll | gamepoll/Constants.swift | 1 | 538 | //
// Constants.swift
// gamepoll
//
// Created by Mohd Irtefa on 1/24/16.
// Copyright © 2016 gamepollstudio. All rights reserved.
//
import Foundation
struct Constants {
static let QUESTION = "Question"
static let QUESTION_TYPE = "QuestionType"
static let QUESTION_CHOICES = "Choices"
static let QUESTION_IMAGE_URL = "ImageUrl"
struct Parse {
static let APPLICATION_ID = "g7e0UmhRuHrLSeEhghy6qz3pMKNLyLRURFpH02te"
static let CLIENT_KEY = "Wa00hS7omwVkGUk9rvMKrRHSgmUjj1ncm9ROuc4P"
}
} | mit |
skonmeme/Reservation | Reservation/NewBranchViewController.swift | 1 | 6050 | //
// NewBranchViewController.swift
// Reservation
//
// Created by Sung Gon Yi on 26/12/2016.
// Copyright © 2016 skon. All rights reserved.
//
import UIKit
import CoreData
protocol AddressViewControllerDelegate {
func addressSearched(_ addressViewController: AddressViewController, address: String)
}
class NewBranchViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, AddressViewControllerDelegate {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var phoneTextField: UITextField!
@IBOutlet weak var addressTextField: UITextField!
@IBOutlet weak var photoView: UIImageView!
@IBOutlet weak var saveButton: UIBarButtonItem!
@IBOutlet weak var searchAddressButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.nameTextField.becomeFirstResponder()
}
override func viewWillAppear(_ animated: Bool) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func activateSaveWhenAllTextFieldFilled() {
guard let name = self.nameTextField.text, let phone = self.phoneTextField.text, let address = self.addressTextField.text else {
self.saveButton.isEnabled = false
return
}
if name != "" && phone != "" && address != "" {
self.saveButton.isEnabled = true
} else {
self.saveButton.isEnabled = false
}
}
@IBAction func searchAddress(_ sender: Any) {
}
@IBAction func photoTapped(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
self.present(imagePicker, animated: true)
}
@IBAction func cancel(_ sender: Any) {
self.dismiss(animated: true)
}
@IBAction func addBranch(_ sender: Any) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Branch", in: managedContext)
let branch = NSManagedObject(entity: entity!, insertInto: managedContext)
branch.setValue(self.nameTextField.text, forKey: "name")
branch.setValue(self.phoneTextField.text, forKey: "phone")
branch.setValue(self.addressTextField.text, forKey: "address")
if let image = self.photoView.image, let imageData = UIImagePNGRepresentation(image) {
var photoName: String
var photoURL: URL
let photoDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
repeat {
photoName = UUID().uuidString + ".png"
photoURL = photoDirectory.appendingPathComponent(photoName)
} while (FileManager.default.fileExists(atPath: photoURL.path))
FileManager.default.createFile(atPath: photoURL.path, contents: imageData, attributes: nil)
branch.setValue(photoName, forKey: "photo")
}
do {
try managedContext.save()
self.dismiss(animated: true)
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
let alertController = UIAlertController(title: "Could not save.", message: "\(error), \(error.userInfo)", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alertController, animated: true)
}
}
// ImagePicker Delegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
self.photoView.image = info["UIImagePickerControllerOriginalImage"] as! UIImage?
self.dismiss(animated: true)
}
// TextField Delegate
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField.tag == 2000 {
self.searchAddressButton.isHidden = false
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField.tag == 2000 {
self.searchAddressButton.isHidden = true
}
self.activateSaveWhenAllTextFieldFilled()
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard var text = textField.text else { return false }
if let range = text.range(from: range) {
text = text.replacingCharacters(in: range, with: string)
textField.text = text
}
self.activateSaveWhenAllTextFieldFilled()
return false
}
// AddressView Delegate
func addressSearched(_ addressViewController: AddressViewController, address: String) {
self.addressTextField.text = address
self.activateSaveWhenAllTextFieldFilled()
}
// Segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let naviagationController = segue.destination as! UINavigationController
let destinationViewController = naviagationController.viewControllers.first as! AddressViewController
if let address = self.addressTextField.text {
destinationViewController.address = address
destinationViewController.delegate = self
}
}
}
| mit |
mcberros/VirtualTourist | VirtualTourist/FlickrApiConveniences.swift | 1 | 4634 | //
// FlickrApiConveniences.swift
// VirtualTourist
//
// Created by Carmen Berros on 10/07/16.
// Copyright © 2016 mcberros. All rights reserved.
//
import Foundation
import UIKit
extension FlickrApiClient {
func getImageFromFlickrBySearch(boundingBoxString: String, completionHandler: (success: Bool, photosArray: [[String: AnyObject]],errorString: String?) -> Void) {
let session = NSURLSession.sharedSession()
let methodArguments = [
"method": FlickrApiClient.Methods.SearchPhotos,
"api_key": FlickrApiClient.Constants.ApiKey,
"bbox": boundingBoxString,
"safe_search": FlickrApiClient.ParameterValues.SafeSearch,
"extras": FlickrApiClient.ParameterValues.Extras,
"format": FlickrApiClient.ParameterValues.Format,
"nojsoncallback": FlickrApiClient.ParameterValues.NoJsonCallback,
"per_page": FlickrApiClient.ParameterValues.PerPage
]
let urlString = FlickrApiClient.Constants.BaseURL + escapedParameters(methodArguments)
let url = NSURL(string: urlString)!
let request = NSURLRequest(URL: url)
let task = session.dataTaskWithRequest(request) { (data, response, error) in
/* GUARD: Was there an error? */
guard (error == nil) else {
print("There was an error with your request: \(error)")
return
}
/* GUARD: Did we get a successful 2XX response? */
guard let statusCode = (response as? NSHTTPURLResponse)?.statusCode where statusCode >= 200 && statusCode <= 299 else {
if let response = response as? NSHTTPURLResponse {
print("Your request returned an invalid response! Status code: \(response.statusCode)!")
} else if let response = response {
print("Your request returned an invalid response! Response: \(response)!")
} else {
print("Your request returned an invalid response!")
}
return
}
/* GUARD: Was there any data returned? */
guard let data = data else {
print("No data was returned by the request!")
return
}
/* Parse the data! */
let parsedResult: AnyObject!
do {
parsedResult = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
} catch {
parsedResult = nil
print("Could not parse the data as JSON: '\(data)'")
return
}
/* GUARD: Did Flickr return an error? */
guard let stat = parsedResult["stat"] as? String where stat == "ok" else {
print("Flickr API returned an error. See error code and message in \(parsedResult)")
return
}
/* GUARD: Is "photos" key in our result? */
guard let photosDictionary = parsedResult["photos"] as? NSDictionary else {
print("Cannot find keys 'photos' in \(parsedResult)")
return
}
/* GUARD: Is the "total" key in photosDictionary? */
guard let totalPhotos = (photosDictionary["total"] as? NSString)?.integerValue else {
print("Cannot find key 'total' in \(photosDictionary)")
return
}
if totalPhotos > 0 {
/* GUARD: Is the "photo" key in photosDictionary? */
guard let photosArray = photosDictionary["photo"] as? [[String: AnyObject]] else {
print("Cannot find key 'photo' in \(photosDictionary)")
return
}
completionHandler(success: true, photosArray: photosArray, errorString: "")
}
}
task.resume()
}
// MARK: Escape HTML Parameters
func escapedParameters(parameters: [String : AnyObject]) -> String {
var urlVars = [String]()
for (key, value) in parameters {
/* Make sure that it is a string value */
let stringValue = "\(value)"
/* Escape it */
let escapedValue = stringValue.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
/* Append it */
urlVars += [key + "=" + "\(escapedValue!)"]
}
return (!urlVars.isEmpty ? "?" : "") + urlVars.joinWithSeparator("&")
}
} | mit |
rukano/cantina | Sources/App/Controllers/CantinaController.swift | 1 | 1231 | //
// CantinaController.swift
// cantina
//
// Created by Romero, Juan, SEVEN PRINCIPLES on 02.09.17.
//
//
import Vapor
import Kanna
enum TextFormat {
case mattermost
case prosa
}
final class CantinaController {
private let externalUrl: String = "http://www.friendskantine.de/index.php/speiseplan/speiseplan-bockenheim"
var drop: Droplet
init(drop: Droplet) {
self.drop = drop
}
func alexa(_ req: Request) throws -> ResponseRepresentable {
return try requestMenuText(.prosa)
}
func text(_ req: Request) throws -> ResponseRepresentable {
return try requestMenuText(.mattermost)
}
func today(_ req: Request) throws -> ResponseRepresentable {
let text = try requestMenuText(.mattermost)
return try CantinaMattermost(text).makeJson()
}
private func requestMenuText(_ format: TextFormat) throws -> String {
let response = try drop.client.request(.get, externalUrl)
guard let bytes = response.body.bytes else {
throw Abort.serverError
}
let content = String(bytes: bytes)
let cantina = try Cantina(fromWeb: content)
let text = try cantina.currentDayMenu(format)
return text
}
}
| mit |
AlbertWu0212/MyDailyTodo | MyDailyTodo/MyDailyTodo/DataModel.swift | 1 | 2686 | //
// DataModel.swift
// MyDailyTodo
//
// Created by WuZhengBin on 16/7/4.
// Copyright © 2016年 WuZhengBin. All rights reserved.
//
import Foundation
class DataModel {
var lists = [Checklist]()
var indexOfSelectedChecklist: Int {
get {
return NSUserDefaults.standardUserDefaults().integerForKey("ChecklistIndex")
}
set {
NSUserDefaults.standardUserDefaults().setInteger(newValue, forKey: "ChecklistIndex")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
func documentsDirectory() -> String {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
return paths[0]
}
func dataFilePath() -> String {
let directory = documentsDirectory() as NSString
return directory.stringByAppendingPathComponent("Checklists.plist")
}
func saveChecklists() {
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWithMutableData: data)
archiver.encodeObject(lists, forKey: "Checklists")
archiver.finishEncoding()
data.writeToFile(dataFilePath(), atomically: true)
}
func loadChecklist() {
let path = dataFilePath()
if NSFileManager.defaultManager().fileExistsAtPath(path) {
if let data = NSData(contentsOfFile: path) {
let unarchiver = NSKeyedUnarchiver(forReadingWithData: data)
lists = unarchiver.decodeObjectForKey("Checklists") as! [Checklist]
unarchiver.finishDecoding()
sortChecklist()
}
}
}
func registerDefaults() {
let dictionary = [ "ChecklistIndex": -1 ,
"FirstTime": true,
"ChecklistItemID": 0 ]
NSUserDefaults.standardUserDefaults().registerDefaults(dictionary)
}
func handleFirstTime() {
let userDefaults = NSUserDefaults.standardUserDefaults()
let firstTime = userDefaults.boolForKey("FirstTime")
if firstTime {
let checklist = Checklist(name: "List")
lists.append(checklist)
indexOfSelectedChecklist = 0
userDefaults.setBool(false, forKey: "FirstTime")
userDefaults.synchronize()
}
}
func sortChecklist() {
lists.sortInPlace({ checklist1, checklist2 in return
checklist1.name.localizedStandardCompare(checklist2.name) == .OrderedAscending
})
}
class func nextChecklistItemID() -> Int {
let userDefaults = NSUserDefaults.standardUserDefaults()
let itemID = userDefaults.integerForKey("ChecklistItemID")
userDefaults.setInteger(itemID + 1, forKey: "ChecklistItemID")
userDefaults.synchronize()
return itemID
}
init() {
loadChecklist()
registerDefaults()
handleFirstTime()
}
}
| mit |
eflyjason/word-counter-tools | WordCounter/ViewController.swift | 1 | 34703 | //
// ViewController.swift
// WordCounter
//
// Created by Arefly on 5/7/2015.
// Copyright (c) 2015 Arefly. All rights reserved.
//
import UIKit
import Foundation
import MBProgressHUD
import EAIntroView
class ViewController: UIViewController, UITextViewDelegate, EAIntroDelegate {
// MARK: - Basic var
let appDelegate = (UIApplication.shared.delegate as! AppDelegate)
let defaults = UserDefaults.standard
let sharedData = UserDefaults(suiteName: "group.com.arefly.WordCounter")
// MARK: - Init var
// MARK: - IBOutlet var
@IBOutlet var tv: UITextView!
// MARK: - Navbar var
var topBarCountButton: UIBarButtonItem!
var topBarCountButtonType: CountByType!
var shareButton: UIBarButtonItem!
var clearButton: UIBarButtonItem!
// MARK: - keyboardButton var
override var canBecomeFirstResponder: Bool {
get {
return true
}
}
override var inputAccessoryView: CustomInputAccessoryWithToolbarView? {
if keyBoardToolBar == nil {
// https://stackoverflow.com/a/58524360/2603230
keyBoardToolBar = CustomInputAccessoryWithToolbarView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 44))
}
return keyBoardToolBar
}
var keyBoardToolBar: CustomInputAccessoryWithToolbarView!
var showedKeyboardButtons = [CountByType: Bool]()
// We have to keep both `countingKeyboardBarButtonItemsNames` and `countingKeyboardBarButtonItems` as `countingKeyboardBarButtonItems` is not ordered.
var countingKeyboardBarButtonItemsNames = [CountByType]()
var countingKeyboardBarButtonItems = [CountByType: UIBarButtonItem]()
var stableKeyboardBarButtonItemsNames = [String]()
var stableKeyboardBarButtonItems = [String: UIBarButtonItem]()
// MARK: - Bool var
var isTextViewActive: Bool {
get {
return self.tv.isFirstResponder
}
}
var appFirstLaunch = false
var appJustUpdate = false
var presentingOtherView = false
// MARK: - UI var
var tvPlaceholderLabel: UILabel!
// MARK: - Welcome page var
var intro = EAIntroView()
// MARK: - Color
var toolbarButtonTintColor: UIColor = {
if #available(iOS 13, *) {
return .label
} else {
return .black
}
}()
// MARK: - Override func
override func viewDidLoad() {
super.viewDidLoad()
print("準備加載 View Controller 之 viewDidLoad")
self.title = NSLocalizedString("Main.NavBar.Title", comment: "Word Counter")
if #available(iOS 13.0, *) {
self.view.backgroundColor = .systemBackground
}
topBarCountButton = UIBarButtonItem()
topBarCountButton.tintColor = toolbarButtonTintColor
if WordCounter.isChineseUser() {
topBarCountButtonType = .chineseWord
} else {
topBarCountButtonType = .word
}
topBarCountButton.title = WordCounter.getHumanReadableCountString(of: "", by: topBarCountButtonType)
topBarCountButton.action = #selector(self.topBarCountingButtonClicked(_:))
topBarCountButton.target = self
self.navigationItem.setLeftBarButton(topBarCountButton, animated: true)
clearButton = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(self.clearButtonClicked(_:)))
shareButton = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(self.shareButtonClicked(sender:)))
clearButton.tintColor = .systemRed
self.navigationItem.setRightBarButtonItems([shareButton, clearButton], animated: true)
if isAppFirstLaunch() {
appFirstLaunch = true
}
let version: String = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
if defaults.object(forKey: "nowVersion") == nil {
defaults.setValue(version, forKey: "nowVersion")
appFirstLaunch = true
} else {
if defaults.string(forKey: "nowVersion") != version {
appJustUpdate = true
defaults.setValue(version, forKey: "nowVersion")
}
}
self.tv.delegate = self
self.tv.layoutManager.allowsNonContiguousLayout = false
if #available(iOS 13.0, *) {
self.tv.backgroundColor = .systemBackground
self.tv.textColor = .label
}
tvPlaceholderLabel = UILabel()
tvPlaceholderLabel.text = NSLocalizedString("Global.TextView.PlaceHolder.Text", comment: "Type or paste here...")
tvPlaceholderLabel.font = UIFont.systemFont(ofSize: tv.font!.pointSize)
tvPlaceholderLabel.sizeToFit()
tv.addSubview(tvPlaceholderLabel)
tvPlaceholderLabel.frame.origin = CGPoint(x: 5, y: tv.font!.pointSize / 2)
if #available(iOS 13.0, *) {
tvPlaceholderLabel.textColor = .placeholderText
} else {
tvPlaceholderLabel.textColor = UIColor(white: 0, alpha: 0.3)
}
tvPlaceholderLabel.isHidden = !tv.text.isEmpty
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("準備加載 View Controller 之 viewWillAppear")
addToolBarToKeyboard()
let countMenuItem = UIMenuItem(title: NSLocalizedString("Global.TextView.MenuItem.Count", comment: "Count..."), action: #selector(self.countSelectionWord))
UIMenuController.shared.menuItems = [countMenuItem]
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillChangeFrame(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidChangeFrame(_:)), name: UIResponder.keyboardDidChangeFrameNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.doAfterRotate), name: UIDevice.orientationDidChangeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
//2015-12-11: Change to DidEnterBackgroundNotification as it is more suiable in Slide Over view
NotificationCenter.default.addObserver(self, selector: #selector(self.didEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.setContentToTextBeforeEnterBackground), name: .catnapSetContentToTextBeforeEnterBackground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.setContentFromClipBoard), name: .catnapSetContentFromClipBoard, object: nil)
doAfterRotate()
//checkScreenWidthToSetButton()
if defaults.object(forKey: "noAd") == nil {
defaults.set(false, forKey: "noAd")
}
if defaults.object(forKey: "appLaunchTimes") == nil {
defaults.set(1, forKey: "appLaunchTimes")
} else {
defaults.set(defaults.integer(forKey: "appLaunchTimes") + 1, forKey: "appLaunchTimes")
}
print("已設定appLaunchTimes值爲\(defaults.integer(forKey: "appLaunchTimes"))")
if defaults.object(forKey: "everShowPresentReviewAgain") == nil {
defaults.set(true, forKey: "everShowPresentReviewAgain")
}
//appJustUpdate = true
if defaults.object(forKey: "appLaunchTimesAfterUpdate") == nil {
defaults.set(-1, forKey: "appLaunchTimesAfterUpdate")
}
if appJustUpdate {
defaults.set(1, forKey: "appLaunchTimesAfterUpdate")
}
if defaults.integer(forKey: "appLaunchTimesAfterUpdate") != -1 {
defaults.set(defaults.integer(forKey: "appLaunchTimesAfterUpdate") + 1, forKey: "appLaunchTimesAfterUpdate")
}
print("已設定appLaunchTimesAfterUpdate值爲\(defaults.integer(forKey: "appLaunchTimesAfterUpdate"))")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("準備加載 View Controller 之 viewDidAppear")
if appFirstLaunch || appJustUpdate {
presentingOtherView = true
// So that the toolbar will not be shown.
self.resignFirstResponder()
presentIntroView()
}
//defaults.setBool(true, forKey: "everShowPresentReviewAgain")
//var everShowPresentReviewAgain = defaults.boolForKey("everShowPresentReviewAgain")
//var appLaunchTimes = defaults.integerForKey("appLaunchTimes")
print("everShowPresentReviewAgain的值爲"+String(defaults.bool(forKey: "everShowPresentReviewAgain")))
if defaults.bool(forKey: "everShowPresentReviewAgain") {
if !presentingOtherView {
print("appLaunchTimes的值爲\(defaults.integer(forKey: "appLaunchTimes"))")
//defaults.setInteger(8, forKey: "appLaunchTimes")
if defaults.integer(forKey: "appLaunchTimes") % 50 == 0 {
presentingOtherView = true
presentReviewAlert()
//defaults.setInteger(defaults.integerForKey("appLaunchTimes") + 1, forKey: "appLaunchTimes")
}
}
}
if defaults.integer(forKey: "appLaunchTimesAfterUpdate") != -1 {
if !presentingOtherView {
print("appLaunchTimesAfterUpdate的值爲\(defaults.integer(forKey: "appLaunchTimesAfterUpdate"))")
if defaults.integer(forKey: "appLaunchTimesAfterUpdate") % 88 == 0 {
presentingOtherView = true
presentUpdateReviewAlert()
//defaults.setInteger(defaults.integerForKey("appLaunchTimes") + 1, forKey: "appLaunchTimes")
}
}
}
if !presentingOtherView {
startEditing()
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("準備加載 View Controller 之 viewWillDisappear")
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidChangeFrameNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: .catnapSetContentToTextBeforeEnterBackground, object: nil)
NotificationCenter.default.removeObserver(self, name: .catnapSetContentFromClipBoard, object: nil)
//NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
endEditing()
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(self.countSelectionWord) {
if !(getTextViewSelectionText(self.tv).isEmpty) {
return true
}
return false
}
return super.canPerformAction(action, withSender: sender)
}
// MARK: - Screen config func
func checkScreenWidthToSetButton () {
print("準備加載 checkScreenWidthToSetButton")
showedKeyboardButtons = [
.word: false,
.character: false,
.characterWithSpaces: false,
.sentence: false,
.paragraph: false,
.chineseWord: false,
.chineseWordWithoutPunctuation: false,
]
let bounds = UIApplication.shared.keyWindow?.bounds
let width = bounds!.size.width
let height = bounds!.size.height
print("屏幕高度:\(height)、屏幕寬度:\(width)")
switch width {
case 0..<330:
showedKeyboardButtons[.sentence] = true
break
case 330..<750:
showedKeyboardButtons[WordCounter.isChineseUser() ? .chineseWordWithoutPunctuation : .character] = true
showedKeyboardButtons[.sentence] = true
break
default:
if (WordCounter.isChineseUser()) {
showedKeyboardButtons[.chineseWord] = true
showedKeyboardButtons[.chineseWordWithoutPunctuation] = true
}
showedKeyboardButtons[.word] = true
showedKeyboardButtons[.character] = true
showedKeyboardButtons[.characterWithSpaces] = width > 1000
showedKeyboardButtons[.sentence] = true
showedKeyboardButtons[.paragraph] = true
}
updateToolBar()
//updateTextViewCounting()
handleTextViewChange(self.tv) // Call handleTextViewChange manually
}
@objc func doAfterRotate() {
print("準備加載 doAfterRotate")
// If text view is active, `keyboardWillChangeFrame` will handle everything.
checkScreenWidthToSetButton()
}
// MARK: - Keyboard func
@objc func keyboardWillChangeFrame(_ notification: Notification) {
print("keyboardWillChangeFrame")
guard let userInfo = notification.userInfo else { return }
// https://stackoverflow.com/a/27135992/2603230
let endFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
let endFrameY = endFrame?.origin.y ?? 0
//print(self.view.convert(endFrame!, to: self.view.window))
//print(self.view.frame.height - endFrameY)
//print(endFrameY)
var height: CGFloat = self.inputAccessoryView?.frame.height ?? 0.0
if endFrameY >= UIScreen.main.bounds.size.height - (self.inputAccessoryView?.frame.height ?? 0.0) {
// If the keyboard is closed.
// Do nothing
} else {
if let endFrameHeight = endFrame?.size.height {
height = endFrameHeight
}
}
if #available(iOS 11.0, *) {
// https://stackoverflow.com/a/48693623/2603230
height -= self.view.safeAreaInsets.bottom
}
self.tv.contentInset.bottom = height
self.tv.scrollIndicatorInsets.bottom = height
checkScreenWidthToSetButton()
handleTextViewChange(self.tv)
}
@objc func keyboardDidChangeFrame(_ notification: Notification) {
// For updating the "Done" button.
updateToolBar()
}
func addToolBarToKeyboard(){
stableKeyboardBarButtonItemsNames = [String]() //Empty stableKeyboardBarButtonItemsNames first
stableKeyboardBarButtonItems["FlexSpace"] = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
stableKeyboardBarButtonItemsNames.append("FlexSpace")
stableKeyboardBarButtonItems["Done"] = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.doneButtonAction))
stableKeyboardBarButtonItemsNames.append("Done")
let infoButton: UIButton = UIButton(type: UIButton.ButtonType.infoLight)
infoButton.addTarget(self, action: #selector(self.infoButtonAction), for: UIControl.Event.touchUpInside)
stableKeyboardBarButtonItems["Info"] = UIBarButtonItem(customView: infoButton)
stableKeyboardBarButtonItemsNames.append("Info")
countingKeyboardBarButtonItemsNames = [.chineseWord, .chineseWordWithoutPunctuation, .word, .character, .characterWithSpaces, .sentence, .paragraph];
for name in countingKeyboardBarButtonItemsNames {
// We have to set some text in `title` to make sure the button is rendered at the correct position.
countingKeyboardBarButtonItems[name] = UIBarButtonItem(title: "_", style: .plain, target: self, action: #selector(self.countResultButtonAction))
countingKeyboardBarButtonItems[name]!.tintColor = toolbarButtonTintColor
}
updateToolBar()
// TODO: not sure if we need it here
self.tv.inputAccessoryView = keyBoardToolBar
}
func updateToolBar() {
var barItems = [UIBarButtonItem]()
for name in countingKeyboardBarButtonItemsNames {
if showedKeyboardButtons[name] == true {
barItems.append(countingKeyboardBarButtonItems[name]!)
}
}
for name in stableKeyboardBarButtonItemsNames {
if name == "Done" && !isTextViewActive {
// Do not add the "Done" button if the text view is not active.
continue
}
barItems.append(stableKeyboardBarButtonItems[name]!)
}
if keyBoardToolBar != nil {
keyBoardToolBar.toolbar.setItems(barItems, animated: true)
keyBoardToolBar.toolbar.setNeedsLayout()
}
updateTextViewCounting()
}
// MARK: - Textview related func
/*
func endEditingIfFullScreen() {
let isFullScreen = CGRectEqualToRect((UIApplication.sharedApplication().keyWindow?.bounds)!, UIScreen.mainScreen().bounds)
print("目前窗口是否處於全屏狀態:\(isFullScreen)")
if isFullScreen {
endEditing()
}
}
*/
@objc func countSelectionWord() {
print("準備加載 countSelectionWord")
print("即:已準備顯示所選文字區域的字數統計")
let selectedText = getTextViewSelectionText(self.tv)
showCountResultAlert(selectedText)
}
func getTextViewSelectionText(_ tv: UITextView) -> String {
if let selectedRange = tv.selectedTextRange {
if let selectedText = tv.text(in: selectedRange) {
return selectedText
}
}
return ""
}
func replaceTextViewContent(_ text: String) {
self.tv.text = text
self.textViewDidChange(self.tv) // Call textViewDidChange manually
}
func endEditing() {
self.tv.resignFirstResponder()
//self.tv.endEditing(true)
//self.view.endEditing(true)
}
func startEditing() {
self.tv.becomeFirstResponder()
}
func clearContent() {
endEditing()
self.replaceTextViewContent("")
doAfterRotate()
}
func textViewDidChange(_ textView: UITextView) {
handleTextViewChange(textView)
self.storeText(textView.text)
}
func handleTextViewChange(_ textView: UITextView) {
tvPlaceholderLabel.isHidden = !textView.text.isEmpty
updateTextViewCounting()
}
func updateTextViewCounting() {
//var wordTitle = ""
var titles: [CountByType: String] = [:]
if let myText = self.tv.text {
DispatchQueue.global(qos: .background).async {
if (WordCounter.isChineseUser()) {
if myText.isEmptyOrContainsChineseCharacters {
self.topBarCountButtonType = .chineseWord
} else {
self.topBarCountButtonType = .word
}
}
titles[self.topBarCountButtonType] = WordCounter.getHumanReadableCountString(of: myText, by: self.topBarCountButtonType, shouldUseShortForm: true)
for (type, enabled) in self.showedKeyboardButtons {
if (!enabled) {
continue
}
titles[type] = WordCounter.getHumanReadableCountString(of: myText, by: type, shouldUseShortForm: true)
}
DispatchQueue.main.async {
self.topBarCountButton.title = titles[self.topBarCountButtonType]
for name in self.countingKeyboardBarButtonItemsNames {
self.countingKeyboardBarButtonItems[name]!.title = "_"
self.countingKeyboardBarButtonItems[name]!.title = titles[name]
}
//print(titles["Sentence"])
}
}
}
}
@objc func setContentFromClipBoard() {
print("準備加載 setContentFromClipBoard")
if let clipBoard = UIPasteboard.general.string {
print("已獲取用戶剪貼簿內容:\(clipBoard)")
if (self.tv.text.isEmpty) || (self.tv.text == clipBoard) {
DispatchQueue.main.async {
self.replaceTextViewContent(clipBoard)
}
} else {
let replaceContentAlert = UIAlertController(
title: NSLocalizedString("Global.Alert.BeforeReplaceTextViewToClipboard.Title", comment: "Replace current contents with clipboard contents?"),
message: NSLocalizedString("Global.Alert.BeforeReplaceTextViewToClipboard.Content", comment: "NOTICE: This action is irreversible!"),
preferredStyle: .alert)
replaceContentAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Button.Yes", comment: "Yes"), style: .default, handler: { (action: UIAlertAction) in
print("用戶已按下確定替換內容為剪切版內容")
self.replaceTextViewContent(clipBoard)
}))
replaceContentAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Button.Close", comment: "Close"), style: .cancel, handler: { (action: UIAlertAction) in
print("用戶已按下取消按鈕")
}))
DispatchQueue.main.async {
self.present(replaceContentAlert, animated: true, completion: nil)
}
}
}
}
@objc func setContentToTextBeforeEnterBackground() {
print("準備加載 setContentToTextBeforeEnterBackground")
if let textBeforeEnterBackground = defaults.string(forKey: "textBeforeEnterBackground") {
if textBeforeEnterBackground != self.tv.text {
DispatchQueue.main.async {
self.replaceTextViewContent(textBeforeEnterBackground)
}
}
}
}
// MARK: - Button action func
@objc func clearButtonClicked(_ sender: AnyObject) {
let keyboardShowingBefore = isTextViewActive
endEditing()
let clearContentAlert = UIAlertController(
title: NSLocalizedString("Global.Alert.BeforeClear.Title", comment: "Clear all content?"),
message: NSLocalizedString("Global.Alert.BeforeClear.Content", comment: "WARNING: This action is irreversible!"),
preferredStyle: .alert)
clearContentAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Button.Yes", comment: "Yes"), style: .destructive, handler: { (action: UIAlertAction) in
print("用戶已按下確定清空按鈕")
self.clearContent()
self.startEditing()
}))
clearContentAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Button.Close", comment: "Close"), style: .cancel, handler: { (action: UIAlertAction) in
print("用戶已按下取消清空按鈕")
if keyboardShowingBefore {
self.startEditing()
}
}))
DispatchQueue.main.async {
self.present(clearContentAlert, animated: true, completion: nil)
}
}
@objc func shareButtonClicked(sender: UIBarButtonItem) {
endEditing()
// https://stackoverflow.com/a/37939782/2603230
let activityViewController: UIActivityViewController = UIActivityViewController(
activityItems: [self.tv.text ?? ""], applicationActivities: nil)
activityViewController.popoverPresentationController?.barButtonItem = sender
//activityViewController.popoverPresentationController?.permittedArrowDirections = .up
if #available(iOS 13.0, *) {
/*activityViewController.activityItemsConfiguration = [
UIActivity.ActivityType.copyToPasteboard
] as? UIActivityItemsConfigurationReading*/
}
DispatchQueue.main.async {
self.present(activityViewController, animated: true, completion: nil)
}
}
@objc func infoButtonAction() {
self.performSegue(withIdentifier: "goInfo", sender: nil)
}
@objc func countResultButtonAction() {
showCountResultAlert(self.tv.text)
}
func showCountResultAlert(_ text: String) {
let keyboardShowingBefore = isTextViewActive
endEditing()
let progressHUD = MBProgressHUD.showAdded(to: self.view.window!, animated: true)
progressHUD.label.text = NSLocalizedString("Global.ProgressingHUD.Label.Counting", comment: "Counting...")
var message: String = ""
DispatchQueue.global(qos: .background).async {
message = WordCounter.getHumanReadableSummary(of: text, by: WordCounter.getAllTypes(for: text))
DispatchQueue.main.async {
MBProgressHUD.hide(for: self.view.window!, animated: true)
let alertTitle = NSLocalizedString("Global.Alert.Counter.Title", comment: "Counter")
let countingResultAlert = UIAlertController(title: alertTitle, message: message, preferredStyle: .alert)
countingResultAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Button.Done", comment: "Done"), style: .cancel, handler: { (action: UIAlertAction) in
print("用戶已按下確定按鈕")
if keyboardShowingBefore {
self.startEditing()
}
}))
self.present(countingResultAlert, animated: true, completion: nil)
}
}
}
@objc func topBarCountingButtonClicked(_ sender: AnyObject) {
countResultButtonAction()
}
@objc func doneButtonAction() {
endEditing()
}
// MARK: - Intro View
func presentIntroView() {
let screenWidth = self.view.bounds.size.width
let screenHeight = self.view.bounds.size.height
var imagesLangPrefix = "en"
if WordCounter.isChineseUser() {
if WordCounter.isSimplifiedChineseUser() {
imagesLangPrefix = "zh-Hans"
} else {
imagesLangPrefix = "zh-Hant"
}
}
var contentImages = [
"\(imagesLangPrefix)-1-4-DarkMode.png",
"\(imagesLangPrefix)-1-4-MoreCountingType.png",
"\(imagesLangPrefix)-1-4-ActionExtension.png",
"\(imagesLangPrefix)-1-4-About.png",
]
var contentTitleTexts = [
NSLocalizedString("Welcome.Version.1-4-1.Title.DarkMode", comment: ""),
NSLocalizedString("Welcome.Version.1-4-1.Title.MoreCountingType", comment: ""),
NSLocalizedString("Welcome.Version.1-4-1.Title.ActionExtension", comment: ""),
NSLocalizedString("Welcome.Global.Title.About", comment: "Thanks!"),
]
var contentDetailTexts = [
NSLocalizedString("Welcome.Version.1-4-1.Text.DarkMode", comment: ""),
NSLocalizedString("Welcome.Version.1-4-1.Text.MoreCountingType", comment: ""),
NSLocalizedString("Welcome.Version.1-4-1.Text.ActionExtension", comment: ""),
NSLocalizedString("Welcome.Global.Text.About", comment: ""),
]
if #available(iOS 13.0, *) {
// Do nothing
} else {
// Do not include dark mode below iOS 13.
contentImages.removeFirst()
contentTitleTexts.removeFirst()
contentDetailTexts.removeFirst()
}
var introPages = [EAIntroPage]()
for (index, _) in contentTitleTexts.enumerated() {
let page = EAIntroPage()
page.title = contentTitleTexts[index]
page.desc = contentDetailTexts[index]
if (index == contentImages.count-1) {
//About Content
page.descFont = UIFont(name: (page.descFont?.fontName)!, size: 12)
}
//print("WOW!: \(page.titlePositionY)")
let titlePositionFromBottom = page.titlePositionY
let imageView = UIImageView(image: UIImage(named: contentImages[index]))
imageView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight-titlePositionFromBottom-100)
imageView.contentMode = .scaleAspectFit
page.titleIconView = imageView
//page.titleIconPositionY = 30
page.bgColor = self.view.tintColor
introPages.append(page)
}
intro = EAIntroView(frame: self.view.bounds, andPages: introPages)
intro.delegate = self
intro.show(in: self.view, animateDuration: 0.5)
intro.showFullscreen()
intro.skipButton.setTitle(NSLocalizedString("Welcome.Global.Button.Skip", comment: "Skip"), for: UIControl.State())
intro.pageControlY = 50
}
func introDidFinish(_ introView: EAIntroView!, wasSkipped: Bool) {
presentingOtherView = false
appFirstLaunch = false
appJustUpdate = false
// So that the toolbar at the bottom will show.
self.becomeFirstResponder()
startEditing()
}
// MARK: - General func
@objc func didBecomeActive() {
print("準備加載 didBecomeActive")
doAfterRotate()
}
func storeText(_ tvText: String) {
//print("準備 storeText \(tvText)")
defaults.set(tvText, forKey: "textBeforeEnterBackground")
}
@objc func didEnterBackground() {
print("準備加載 didEnterBackground")
self.storeText(self.tv.text)
}
func isAppFirstLaunch() -> Bool{ //檢測App是否首次開啓
print("準備加載 isAppFirstLaunch")
if let _ = defaults.string(forKey: "isAppAlreadyLaunchedOnce") {
print("App於本機並非首次開啓")
return false
} else {
defaults.set(true, forKey: "isAppAlreadyLaunchedOnce")
print("App於本機首次開啓")
return true
}
}
func presentReviewAlert() {
let reviewAlert = UIAlertController(
title: NSLocalizedString("Global.Alert.PlzRate.Title", comment: "Thanks!"),
message: String.localizedStringWithFormat(
NSLocalizedString("Global.Alert.PlzRate.Content", comment: "You have used Word Counter Tool for %d times! Love it? Can you take a second to rate our app?"),
defaults.integer(forKey: "appLaunchTimes")),
preferredStyle: .alert)
reviewAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Alert.PlzRate.Button.Yes", comment: "Sure!"), style: .default, handler: { (action: UIAlertAction) in
print("用戶已按下發表評論按鈕")
self.defaults.set(-1, forKey: "appLaunchTimesAfterUpdate") // Do not show update alert for this version too
self.defaults.set(false, forKey: "everShowPresentReviewAgain")
UIApplication.shared.openURL(BasicConfig.appStoreReviewUrl! as URL)
self.presentingOtherView = false
}))
reviewAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Alert.PlzRate.Button.Later", comment: "Not now"), style: .default, handler: { (action: UIAlertAction) in
print("用戶已按下以後再說按鈕")
self.defaults.set(true, forKey: "everShowPresentReviewAgain")
self.startEditing()
self.presentingOtherView = false
}))
reviewAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Alert.PlzRate.Button.Cancel", comment: "No, thanks!"), style: .cancel, handler: { (action: UIAlertAction) in
print("用戶已按下永遠再不顯示按鈕")
self.defaults.set(-1, forKey: "appLaunchTimesAfterUpdate") // Do not show update alert for this version too
self.defaults.set(false, forKey: "everShowPresentReviewAgain")
self.startEditing()
self.presentingOtherView = false
}))
DispatchQueue.main.async {
self.present(reviewAlert, animated: true, completion: nil)
}
}
func presentUpdateReviewAlert() {
let reviewAlert = UIAlertController(
title: NSLocalizedString("Global.Alert.PlzRateUpdate.Title", comment: "Thanks for update!"),
message: String.localizedStringWithFormat(
NSLocalizedString("Global.Alert.PlzRateUpdate.Content", comment: "You have used Word Counter Tool for %1$d times since you updated to Version %2$@! Love this update? Can you take a second to rate our app?"),
defaults.integer(forKey: "appLaunchTimesAfterUpdate"),
Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
),
preferredStyle: .alert)
reviewAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Alert.PlzRateUpdate.Button.Yes", comment: "Sure!"), style: .default, handler: { (action: UIAlertAction) in
print("用戶已按下發表評論按鈕")
self.defaults.set(-1, forKey: "appLaunchTimesAfterUpdate")
UIApplication.shared.openURL(BasicConfig.appStoreReviewUrl! as URL)
self.presentingOtherView = false
}))
reviewAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Alert.PlzRateUpdate.Button.Later", comment: "Not now"), style: .default, handler: { (action: UIAlertAction) in
print("用戶已按下以後再說按鈕")
self.startEditing()
self.presentingOtherView = false
}))
reviewAlert.addAction(UIAlertAction(title: NSLocalizedString("Global.Alert.PlzRateUpdate.Button.Cancel", comment: "No for this version, thanks!"), style: .cancel, handler: { (action: UIAlertAction) in
print("用戶已按下此版本永遠再不顯示按鈕")
self.defaults.set(-1, forKey: "appLaunchTimesAfterUpdate")
self.startEditing()
self.presentingOtherView = false
}))
DispatchQueue.main.async {
self.present(reviewAlert, animated: true, completion: nil)
}
}
}
| gpl-3.0 |
arvedviehweger/swift | stdlib/public/core/SequenceWrapper.swift | 4 | 3732 | //===--- 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
associatedtype Iterator = Base.Iterator
associatedtype SubSequence = Base.SubSequence
var _base: Base { get }
}
extension _SequenceWrapper {
public var underestimatedCount: Int {
return _base.underestimatedCount
}
public func _preprocessingPass<R>(
_ preprocess: () throws -> R
) rethrows -> R? {
return try _base._preprocessingPass(preprocess)
}
}
extension _SequenceWrapper where Iterator == Base.Iterator {
public func makeIterator() -> Iterator {
return self._base.makeIterator()
}
@discardableResult
public func _copyContents(
initializing buf: UnsafeMutableBufferPointer<Iterator.Element>
) -> (Iterator, UnsafeMutableBufferPointer<Iterator.Element>.Index) {
return _base._copyContents(initializing: buf)
}
}
extension _SequenceWrapper where Iterator.Element == Base.Iterator.Element {
public func map<T>(
_ transform: (Iterator.Element) throws -> T
) rethrows -> [T] {
return try _base.map(transform)
}
public func filter(
_ isIncluded: (Iterator.Element) throws -> Bool
) rethrows -> [Iterator.Element] {
return try _base.filter(isIncluded)
}
public func forEach(_ body: (Iterator.Element) throws -> Void) rethrows {
return try _base.forEach(body)
}
public func _customContainsEquatableElement(
_ element: Iterator.Element
) -> Bool? {
return _base._customContainsEquatableElement(element)
}
public func _copyToContiguousArray()
-> ContiguousArray<Iterator.Element> {
return _base._copyToContiguousArray()
}
}
extension _SequenceWrapper where SubSequence == Base.SubSequence {
public func dropFirst(_ n: Int) -> SubSequence {
return _base.dropFirst(n)
}
public func dropLast(_ n: Int) -> SubSequence {
return _base.dropLast(n)
}
public func prefix(_ maxLength: Int) -> SubSequence {
return _base.prefix(maxLength)
}
public func suffix(_ maxLength: Int) -> SubSequence {
return _base.suffix(maxLength)
}
}
extension _SequenceWrapper
where SubSequence == Base.SubSequence, Iterator.Element == Base.Iterator.Element {
public func drop(
while predicate: (Iterator.Element) throws -> Bool
) rethrows -> SubSequence {
return try _base.drop(while: predicate)
}
public func prefix(
while predicate: (Iterator.Element) throws -> Bool
) rethrows -> SubSequence {
return try _base.prefix(while: predicate)
}
public func suffix(_ maxLength: Int) -> SubSequence {
return _base.suffix(maxLength)
}
public func split(
maxSplits: Int, omittingEmptySubsequences: Bool,
whereSeparator isSeparator: (Iterator.Element) throws -> Bool
) rethrows -> [SubSequence] {
return try _base.split(
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences,
whereSeparator: isSeparator
)
}
}
| apache-2.0 |
xedin/swift | test/Parse/recovery.swift | 2 | 32726 | // RUN: %target-typecheck-verify-swift
//===--- Helper types used in this file.
protocol FooProtocol {}
//===--- Tests.
func garbage() -> () {
var a : Int
] this line is invalid, but we will stop at the keyword below... // expected-error{{expected expression}}
return a + "a" // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}}
}
func moreGarbage() -> () {
) this line is invalid, but we will stop at the declaration... // expected-error{{expected expression}}
func a() -> Int { return 4 }
return a() + "a" // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}}
}
class Container<T> {
func exists() -> Bool { return true }
}
func useContainer() -> () {
var a : Container<not a type [skip this greater: >] >, b : Int // expected-error{{expected '>' to complete generic argument list}} expected-note{{to match this opening '<'}}
b = 5 // no-warning
a.exists()
}
@xyz class BadAttributes { // expected-error{{unknown attribute 'xyz'}}
func exists() -> Bool { return true }
}
// expected-note @+2 {{did you mean 'test'?}}
// expected-note @+1 {{'test' declared here}}
func test(a: BadAttributes) -> () {
_ = a.exists() // no-warning
}
// Here is an extra random close-brace!
} // expected-error{{extraneous '}' at top level}} {{1-3=}}
//===--- Recovery for braced blocks.
func braceStmt1() {
{ braceStmt1(); } // expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }}
}
func braceStmt2() {
{ () in braceStmt2(); } // expected-error {{closure expression is unused}}
}
func braceStmt3() {
{ // expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }}
undefinedIdentifier {} // expected-error {{use of unresolved identifier 'undefinedIdentifier'}}
}
}
//===--- Recovery for misplaced 'static'.
static func toplevelStaticFunc() {} // expected-error {{static methods may only be declared on a type}} {{1-8=}}
static struct StaticStruct {} // expected-error {{declaration cannot be marked 'static'}} {{1-8=}}
static class StaticClass {} // expected-error {{declaration cannot be marked 'static'}} {{1-8=}}
static protocol StaticProtocol {} // expected-error {{declaration cannot be marked 'static'}} {{1-8=}}
static typealias StaticTypealias = Int // expected-error {{declaration cannot be marked 'static'}} {{1-8=}}
class ClassWithStaticDecls {
class var a = 42 // expected-error {{class stored properties not supported}}
}
//===--- Recovery for missing controlling expression in statements.
func missingControllingExprInIf() {
if // expected-error {{expected expression, var, or let in 'if' condition}}
if { // expected-error {{missing condition in an 'if' statement}}
}
if // expected-error {{missing condition in an 'if' statement}}
{
}
if true {
} else if { // expected-error {{missing condition in an 'if' statement}}
}
// It is debatable if we should do recovery here and parse { true } as the
// body, but the error message should be sensible.
if { true } { // expected-error {{missing condition in an 'if' statement}} expected-error{{consecutive statements on a line must be separated by ';'}} {{14-14=;}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{15-15=do }} expected-warning {{boolean literal is unused}}
}
if { true }() { // expected-error {{missing condition in an 'if' statement}} expected-error 2 {{consecutive statements on a line must be separated by ';'}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{17-17=do }} expected-warning {{boolean literal is unused}}
}
// <rdar://problem/18940198>
if { { } } // expected-error{{missing condition in an 'if' statement}} expected-error{{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{8-8=do }}
}
func missingControllingExprInWhile() {
while // expected-error {{expected expression, var, or let in 'while' condition}}
while { // expected-error {{missing condition in a 'while' statement}}
}
while // expected-error {{missing condition in a 'while' statement}}
{
}
// It is debatable if we should do recovery here and parse { true } as the
// body, but the error message should be sensible.
while { true } { // expected-error {{missing condition in a 'while' statement}} expected-error{{consecutive statements on a line must be separated by ';'}} {{17-17=;}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{18-18=do }} expected-warning {{boolean literal is unused}}
}
while { true }() { // expected-error {{missing condition in a 'while' statement}} expected-error 2 {{consecutive statements on a line must be separated by ';'}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{20-20=do }} expected-warning {{boolean literal is unused}}
}
// <rdar://problem/18940198>
while { { } } // expected-error{{missing condition in a 'while' statement}} expected-error{{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{11-11=do }}
}
func missingControllingExprInRepeatWhile() {
repeat {
} while // expected-error {{missing condition in a 'while' statement}}
{ // expected-error{{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }}
missingControllingExprInRepeatWhile();
}
repeat {
} while { true }() // expected-error{{missing condition in a 'while' statement}} expected-error{{consecutive statements on a line must be separated by ';'}} {{10-10=;}} expected-warning {{result of call to closure returning 'Bool' is unused}}
}
// SR-165
func missingWhileInRepeat() {
repeat {
} // expected-error {{expected 'while' after body of 'repeat' statement}}
}
func acceptsClosure<T>(t: T) -> Bool { return true }
func missingControllingExprInFor() {
for ; { // expected-error {{C-style for statement has been removed in Swift 3}}
}
for ; // expected-error {{C-style for statement has been removed in Swift 3}}
{
}
for ; true { // expected-error {{C-style for statement has been removed in Swift 3}}
}
for var i = 0; true { // expected-error {{C-style for statement has been removed in Swift 3}}
i += 1
}
}
func missingControllingExprInForEach() {
// expected-error @+3 {{expected pattern}}
// expected-error @+2 {{expected Sequence expression for for-each loop}}
// expected-error @+1 {{expected '{' to start the body of for-each loop}}
for
// expected-error @+2 {{expected pattern}}
// expected-error @+1 {{expected Sequence expression for for-each loop}}
for {
}
// expected-error @+2 {{expected pattern}}
// expected-error @+1 {{expected Sequence expression for for-each loop}}
for
{
}
// expected-error @+2 {{expected 'in' after for-each pattern}}
// expected-error @+1 {{expected Sequence expression for for-each loop}}
for i {
}
// expected-error @+2 {{expected 'in' after for-each pattern}}
// expected-error @+1 {{expected Sequence expression for for-each loop}}
for var i {
}
// expected-error @+2 {{expected pattern}}
// expected-error @+1 {{expected Sequence expression for for-each loop}}
for in {
}
// expected-error @+1 {{expected pattern}}
for 0..<12 {
}
// expected-error @+3 {{expected pattern}}
// expected-error @+2 {{expected Sequence expression for for-each loop}}
// expected-error @+1 {{expected '{' to start the body of for-each loop}}
for for in {
}
for i in { // expected-error {{expected Sequence expression for for-each loop}}
}
// The #if block is used to provide a scope for the for stmt to force it to end
// where necessary to provoke the crash.
#if true // <rdar://problem/21679557> compiler crashes on "for{{"
// expected-error @+2 {{expected pattern}}
// expected-error @+1 {{expected Sequence expression for for-each loop}}
for{{ // expected-note 2 {{to match this opening '{'}}
#endif // expected-error {{expected '}' at end of closure}} expected-error {{expected '}' at end of brace statement}}
#if true
// expected-error @+2 {{expected pattern}}
// expected-error @+1 {{expected Sequence expression for for-each loop}}
for{
var x = 42
}
#endif
// SR-5943
struct User { let name: String? }
let users = [User]()
for user in users whe { // expected-error {{expected '{' to start the body of for-each loop}}
if let name = user.name {
let key = "\(name)"
}
}
for // expected-error {{expected pattern}} expected-error {{Sequence expression for for-each loop}}
; // expected-error {{expected '{' to start the body of for-each loop}}
}
func missingControllingExprInSwitch() {
switch // expected-error {{expected expression in 'switch' statement}} expected-error {{expected '{' after 'switch' subject expression}}
switch { // expected-error {{expected expression in 'switch' statement}} expected-error {{'switch' statement body must have at least one 'case' or 'default' block}}
}
switch // expected-error {{expected expression in 'switch' statement}} expected-error {{'switch' statement body must have at least one 'case' or 'default' block}}
{
}
switch { // expected-error {{expected expression in 'switch' statement}}
case _: return
}
switch { // expected-error {{expected expression in 'switch' statement}}
case Int: return // expected-error {{'is' keyword required to pattern match against type name}} {{10-10=is }}
case _: return
}
switch { 42 } { // expected-error {{expected expression in 'switch' statement}} expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} expected-error{{consecutive statements on a line must be separated by ';'}} {{16-16=;}} expected-error{{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{17-17=do }} // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}}
case _: return // expected-error{{'case' label can only appear inside a 'switch' statement}}
}
switch { 42 }() { // expected-error {{expected expression in 'switch' statement}} expected-error {{all statements inside a switch must be covered by a 'case' or 'default'}} expected-error 2 {{consecutive statements on a line must be separated by ';'}} expected-error{{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{19-19=do }} // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}}
case _: return // expected-error{{'case' label can only appear inside a 'switch' statement}}
}
}
//===--- Recovery for missing braces in nominal type decls.
struct NoBracesStruct1() // expected-error {{expected '{' in struct}}
enum NoBracesUnion1() // expected-error {{expected '{' in enum}}
class NoBracesClass1() // expected-error {{expected '{' in class}}
protocol NoBracesProtocol1() // expected-error {{expected '{' in protocol type}}
extension NoBracesStruct1() // expected-error {{expected '{' in extension}}
struct NoBracesStruct2 // expected-error {{expected '{' in struct}}
enum NoBracesUnion2 // expected-error {{expected '{' in enum}}
class NoBracesClass2 // expected-error {{expected '{' in class}}
protocol NoBracesProtocol2 // expected-error {{expected '{' in protocol type}}
extension NoBracesStruct2 // expected-error {{expected '{' in extension}}
//===--- Recovery for multiple identifiers in decls
protocol Multi ident {}
// expected-error @-1 {{found an unexpected second identifier in protocol declaration; is there an accidental break?}}
// expected-note @-2 {{join the identifiers together}} {{10-21=Multiident}}
// expected-note @-3 {{join the identifiers together with camel-case}} {{10-21=MultiIdent}}
class CCC CCC<T> {}
// expected-error @-1 {{found an unexpected second identifier in class declaration; is there an accidental break?}}
// expected-note @-2 {{join the identifiers together}} {{7-14=CCCCCC}}
enum EE EE<T> where T : Multi {
// expected-error @-1 {{found an unexpected second identifier in enum declaration; is there an accidental break?}}
// expected-note @-2 {{join the identifiers together}} {{6-11=EEEE}}
case a a
// expected-error @-1 {{found an unexpected second identifier in enum 'case' declaration; is there an accidental break?}}
// expected-note @-2 {{join the identifiers together}} {{8-11=aa}}
// expected-note @-3 {{join the identifiers together with camel-case}} {{8-11=aA}}
case b
}
struct SS SS : Multi {
// expected-error @-1 {{found an unexpected second identifier in struct declaration; is there an accidental break?}}
// expected-note @-2 {{join the identifiers together}} {{8-13=SSSS}}
private var a b : Int = ""
// expected-error @-1 {{found an unexpected second identifier in variable declaration; is there an accidental break?}}
// expected-note @-2 {{join the identifiers together}} {{15-18=ab}}
// expected-note @-3 {{join the identifiers together with camel-case}} {{15-18=aB}}
// expected-error @-4 {{cannot convert value of type 'String' to specified type 'Int'}}
func f() {
var c d = 5
// expected-error @-1 {{found an unexpected second identifier in variable declaration; is there an accidental break?}}
// expected-note @-2 {{join the identifiers together}} {{9-12=cd}}
// expected-note @-3 {{join the identifiers together with camel-case}} {{9-12=cD}}
// expected-warning @-4 {{initialization of variable 'c' was never used; consider replacing with assignment to '_' or removing it}}
let _ = 0
}
}
let (efg hij, foobar) = (5, 6)
// expected-error @-1 {{found an unexpected second identifier in constant declaration; is there an accidental break?}}
// expected-note @-2 {{join the identifiers together}} {{6-13=efghij}}
// expected-note @-3 {{join the identifiers together with camel-case}} {{6-13=efgHij}}
_ = foobar // OK.
//===--- Recovery for parse errors in types.
struct ErrorTypeInVarDecl1 {
var v1 : // expected-error {{expected type}} {{11-11= <#type#>}}
}
struct ErrorTypeInVarDecl2 {
var v1 : Int. // expected-error {{expected member name following '.'}}
var v2 : Int
}
struct ErrorTypeInVarDecl3 {
var v1 : Int< // expected-error {{expected type}}
var v2 : Int
}
struct ErrorTypeInVarDecl4 {
var v1 : Int<, // expected-error {{expected type}} {{16-16= <#type#>}}
var v2 : Int
}
struct ErrorTypeInVarDecl5 {
var v1 : Int<Int // expected-error {{expected '>' to complete generic argument list}} expected-note {{to match this opening '<'}}
var v2 : Int
}
struct ErrorTypeInVarDecl6 {
var v1 : Int<Int, // expected-note {{to match this opening '<'}}
Int // expected-error {{expected '>' to complete generic argument list}}
var v2 : Int
}
struct ErrorTypeInVarDecl7 {
var v1 : Int<Int, // expected-error {{expected type}}
var v2 : Int
}
struct ErrorTypeInVarDecl8 {
var v1 : protocol<FooProtocol // expected-error {{expected '>' to complete protocol-constrained type}} expected-note {{to match this opening '<'}}
var v2 : Int
}
struct ErrorTypeInVarDecl9 {
var v1 : protocol // expected-error {{expected type}}
var v2 : Int
}
struct ErrorTypeInVarDecl10 {
var v1 : protocol<FooProtocol // expected-error {{expected '>' to complete protocol-constrained type}} expected-note {{to match this opening '<'}}
var v2 : Int
}
struct ErrorTypeInVarDecl11 {
var v1 : protocol<FooProtocol, // expected-error {{expected identifier for type name}}
var v2 : Int
}
func ErrorTypeInPattern1(_: protocol<) { } // expected-error {{expected identifier for type name}}
func ErrorTypeInPattern2(_: protocol<F) { } // expected-error {{expected '>' to complete protocol-constrained type}}
// expected-note@-1 {{to match this opening '<'}}
// expected-error@-2 {{use of undeclared type 'F'}}
func ErrorTypeInPattern3(_: protocol<F,) { } // expected-error {{expected identifier for type name}}
// expected-error@-1 {{use of undeclared type 'F'}}
struct ErrorTypeInVarDecl12 {
var v1 : FooProtocol & // expected-error{{expected identifier for type name}}
var v2 : Int
}
struct ErrorTypeInVarDecl13 { // expected-note {{in declaration of 'ErrorTypeInVarDecl13'}}
var v1 : & FooProtocol // expected-error {{expected type}} expected-error {{consecutive declarations on a line must be separated by ';'}} expected-error{{expected declaration}}
var v2 : Int
}
struct ErrorTypeInVarDecl16 {
var v1 : FooProtocol & // expected-error {{expected identifier for type name}}
var v2 : Int
}
func ErrorTypeInPattern4(_: FooProtocol & ) { } // expected-error {{expected identifier for type name}}
struct ErrorGenericParameterList1< // expected-error {{expected an identifier to name generic parameter}} expected-error {{expected '{' in struct}}
struct ErrorGenericParameterList2<T // expected-error {{expected '>' to complete generic parameter list}} expected-note {{to match this opening '<'}} expected-error {{expected '{' in struct}}
struct ErrorGenericParameterList3<T, // expected-error {{expected an identifier to name generic parameter}} expected-error {{expected '{' in struct}}
// Note: Don't move braces to a different line here.
struct ErrorGenericParameterList4< // expected-error {{expected an identifier to name generic parameter}}
{
}
// Note: Don't move braces to a different line here.
struct ErrorGenericParameterList5<T // expected-error {{expected '>' to complete generic parameter list}} expected-note {{to match this opening '<'}}
{
}
// Note: Don't move braces to a different line here.
struct ErrorGenericParameterList6<T, // expected-error {{expected an identifier to name generic parameter}}
{
}
struct ErrorTypeInVarDeclFunctionType1 {
var v1 : () -> // expected-error {{expected type for function result}}
var v2 : Int
}
struct ErrorTypeInVarDeclArrayType1 { // expected-note{{in declaration of 'ErrorTypeInVarDeclArrayType1'}}
var v1 : Int[+] // expected-error {{expected declaration}} expected-error {{consecutive declarations on a line must be separated by ';'}}
// expected-error @-1 {{expected expression after unary operator}}
// expected-error @-2 {{expected expression}}
var v2 : Int
}
struct ErrorTypeInVarDeclArrayType2 {
var v1 : Int[+ // expected-error {{unary operator cannot be separated from its operand}}
var v2 : Int // expected-error {{expected expression}}
}
struct ErrorTypeInVarDeclArrayType3 {
var v1 : Int[
; // expected-error {{expected expression}}
var v2 : Int
}
struct ErrorTypeInVarDeclArrayType4 {
var v1 : Int[1 // expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}}
}
struct ErrorInFunctionSignatureResultArrayType1 {
func foo() -> Int[ { // expected-error {{expected '{' in body of function declaration}}
return [0]
}
}
struct ErrorInFunctionSignatureResultArrayType2 {
func foo() -> Int[0 { // expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}}
return [0] // expected-error {{cannot convert return expression of type '[Int]' to return type 'Int'}}
}
}
struct ErrorInFunctionSignatureResultArrayType3 {
func foo() -> Int[0] { // expected-error {{array types are now written with the brackets around the element type}} {{17-17=[}} {{20-21=}}
return [0]
}
}
struct ErrorInFunctionSignatureResultArrayType4 {
func foo() -> Int[0_1] { // expected-error {{array types are now written with the brackets around the element type}} {{17-17=[}} {{20-21=}}
return [0]
}
}
struct ErrorInFunctionSignatureResultArrayType5 {
func foo() -> Int[0b1] { // expected-error {{array types are now written with the brackets around the element type}} {{17-17=[}} {{20-21=}}
return [0]
}
}
struct ErrorInFunctionSignatureResultArrayType11 { // expected-note{{in declaration of 'ErrorInFunctionSignatureResultArrayType11'}}
func foo() -> Int[(a){a++}] { // expected-error {{consecutive declarations on a line must be separated by ';'}} {{29-29=;}} expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}} expected-error {{use of unresolved operator '++'; did you mean '+= 1'?}} expected-error {{use of unresolved identifier 'a'}} expected-error {{expected declaration}}
}
}
//===--- Recovery for missing initial value in var decls.
struct MissingInitializer1 {
var v1 : Int = // expected-error {{expected initial value after '='}}
}
//===--- Recovery for expr-postfix.
func exprPostfix1(x : Int) {
x. // expected-error {{expected member name following '.'}}
}
func exprPostfix2() {
_ = .42 // expected-error {{'.42' is not a valid floating point literal; it must be written '0.42'}} {{7-7=0}}
}
//===--- Recovery for expr-super.
class Base {}
class ExprSuper1 {
init() {
super // expected-error {{expected '.' or '[' after 'super'}}
}
}
class ExprSuper2 {
init() {
super. // expected-error {{expected member name following '.'}}
}
}
//===--- Recovery for braces inside a nominal decl.
struct BracesInsideNominalDecl1 { // expected-note{{in declaration of 'BracesInsideNominalDecl1'}}
{ // expected-error {{expected declaration}}
aaa
}
typealias A = Int
}
func use_BracesInsideNominalDecl1() {
// Ensure that the typealias decl is not skipped.
var _ : BracesInsideNominalDecl1.A // no-error
}
class SR771 { // expected-note {{in declaration of 'SR771'}}
print("No one else was in the room where it happened") // expected-error {{expected declaration}}
}
extension SR771 { // expected-note {{in extension of 'SR771'}}
print("The room where it happened, the room where it happened") // expected-error {{expected declaration}}
}
//===--- Recovery for wrong decl introducer keyword.
class WrongDeclIntroducerKeyword1 { // expected-note{{in declaration of 'WrongDeclIntroducerKeyword1'}}
notAKeyword() {} // expected-error {{expected declaration}}
func foo() {}
class func bar() {}
}
//===--- Recovery for wrong inheritance clause.
class Base2<T> {
}
class SubModule {
class Base1 {}
class Base2<T> {}
}
// expected-error@+1 {{expected ':' to begin inheritance clause}} {{30-31=: }} {{34-35=}}
class WrongInheritanceClause1(Int) {}
// expected-error@+1 {{expected ':' to begin inheritance clause}} {{30-31=: }} {{41-42=}}
class WrongInheritanceClause2(Base2<Int>) {}
// expected-error@+1 {{expected ':' to begin inheritance clause}} {{33-34=: }} {{49-50=}}
class WrongInheritanceClause3<T>(SubModule.Base1) where T:AnyObject {}
// expected-error@+1 {{expected ':' to begin inheritance clause}} {{30-31=: }} {{51-52=}}
class WrongInheritanceClause4(SubModule.Base2<Int>) {}
// expected-error@+1 {{expected ':' to begin inheritance clause}} {{33-34=: }} {{54-55=}}
class WrongInheritanceClause5<T>(SubModule.Base2<Int>) where T:AnyObject {}
// expected-error@+1 {{expected ':' to begin inheritance clause}} {{30-31=: }}
class WrongInheritanceClause6(Int {}
// expected-error@+1 {{expected ':' to begin inheritance clause}} {{33-34=: }}
class WrongInheritanceClause7<T>(Int where T:AnyObject {}
// <rdar://problem/18502220> [swift-crashes 078] parser crash on invalid cast in sequence expr
Base=1 as Base=1 // expected-error {{cannot assign to immutable expression of type 'Base.Type'}}
// <rdar://problem/18634543> Parser hangs at swift::Parser::parseType
public enum TestA {
// expected-error @+1{{expected '{' in body of function declaration}}
public static func convertFromExtenndition( // expected-error {{expected parameter name followed by ':'}}
// expected-error@+1{{expected parameter name followed by ':'}}
s._core.count != 0, "Can't form a Character from an empty String")
}
public enum TestB {
// expected-error@+1{{expected '{' in body of function declaration}}
public static func convertFromExtenndition( // expected-error {{expected parameter name followed by ':'}}
// expected-error@+1 {{expected parameter name followed by ':'}}
s._core.count ?= 0, "Can't form a Character from an empty String")
}
// <rdar://problem/18634543> Infinite loop and unbounded memory consumption in parser
class bar {}
var baz: bar
// expected-error@+1{{unnamed parameters must be written with the empty name '_'}}
func foo1(bar!=baz) {} // expected-note {{did you mean 'foo1'?}}
// expected-error@+1{{unnamed parameters must be written with the empty name '_'}}
func foo2(bar! = baz) {}// expected-note {{did you mean 'foo2'?}}
// rdar://19605567
// expected-error@+1{{use of unresolved identifier 'esp'; did you mean 'test'?}}
switch esp {
case let (jeb):
// expected-error@+5{{top-level statement cannot begin with a closure expression}}
// expected-error@+4{{closure expression is unused}}
// expected-note@+3{{did you mean to use a 'do' statement?}}
// expected-error@+2{{expected an identifier to name generic parameter}}
// expected-error@+1{{expected '{' in class}}
class Ceac<}> {}
// expected-error@+1{{extraneous '}' at top level}} {{1-2=}}
}
#if true
// rdar://19605164
// expected-error@+2{{use of undeclared type 'S'}}
struct Foo19605164 {
func a(s: S[{{g) -> Int {}
// expected-error@+2 {{expected parameter name followed by ':'}}
// expected-error@+1 {{expected ',' separator}}
}}}
#endif
// rdar://19605567
// expected-error@+3{{expected '(' for initializer parameters}}
// expected-error@+2{{initializers may only be declared within a type}}
// expected-error@+1{{expected an identifier to name generic parameter}}
func F() { init<( } )} // expected-note {{did you mean 'F'?}}
struct InitializerWithName {
init x() {} // expected-error {{initializers cannot have a name}} {{8-9=}}
}
struct InitializerWithNameAndParam {
init a(b: Int) {} // expected-error {{initializers cannot have a name}} {{8-9=}}
init? c(_ d: Int) {} // expected-error {{initializers cannot have a name}} {{9-10=}}
init e<T>(f: T) {} // expected-error {{initializers cannot have a name}} {{8-9=}}
init? g<T>(_: T) {} // expected-error {{initializers cannot have a name}} {{9-10=}}
}
struct InitializerWithLabels {
init c d: Int {}
// expected-error @-1 {{expected '(' for initializer parameters}}
// expected-error @-2 {{expected declaration}}
// expected-error @-3 {{consecutive declarations on a line must be separated by ';'}}
// expected-note @-5 {{in declaration of 'InitializerWithLabels'}}
}
// rdar://20337695
func f1() {
// expected-error @+6 {{use of unresolved identifier 'C'}}
// expected-note @+5 {{did you mean 'n'?}}
// expected-error @+4 {{unary operator cannot be separated from its operand}} {{11-12=}}
// expected-error @+3 {{'==' is not a prefix unary operator}}
// expected-error @+2 {{consecutive statements on a line must be separated by ';'}} {{8-8=;}}
// expected-error@+1 {{type annotation missing in pattern}}
let n == C { get {} // expected-error {{use of unresolved identifier 'get'}}
}
}
// <rdar://problem/20489838> QoI: Nonsensical error and fixit if "let" is missing between 'if let ... where' clauses
func testMultiPatternConditionRecovery(x: Int?) {
// expected-error@+1 {{expected ',' joining parts of a multi-clause condition}} {{15-21=,}}
if let y = x where y == 0, let z = x {
_ = y
_ = z
}
if var y = x, y == 0, var z = x {
z = y; y = z
}
if var y = x, z = x { // expected-error {{expected 'var' in conditional}} {{17-17=var }}
z = y; y = z
}
// <rdar://problem/20883210> QoI: Following a "let" condition with boolean condition spouts nonsensical errors
guard let x: Int? = 1, x == 1 else { }
// expected-warning @-1 {{explicitly specified type 'Int?' adds an additional level of optional to the initializer, making the optional check always succeed}} {{16-20=Int}}
}
// rdar://20866942
func testRefutableLet() {
var e : Int?
let x? = e // expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}}
// expected-error @-1 {{expected expression}}
// expected-error @-2 {{type annotation missing in pattern}}
}
// <rdar://problem/19833424> QoI: Bad error message when using Objective-C literals (@"Hello") in Swift files
let myString = @"foo" // expected-error {{string literals in Swift are not preceded by an '@' sign}} {{16-17=}}
// <rdar://problem/16990885> support curly quotes for string literals
// expected-error @+1 {{unicode curly quote found, replace with '"'}} {{35-38="}}
let curlyQuotes1 = “hello world!” // expected-error {{unicode curly quote found, replace with '"'}} {{20-23="}}
// expected-error @+1 {{unicode curly quote found, replace with '"'}} {{20-23="}}
let curlyQuotes2 = “hello world!"
// <rdar://problem/21196171> compiler should recover better from "unicode Specials" characters
let tryx = 123 // expected-error 2 {{invalid character in source file}} {{5-8= }}
// <rdar://problem/21369926> Malformed Swift Enums crash playground service
enum Rank: Int { // expected-error {{'Rank' declares raw type 'Int', but does not conform to RawRepresentable and conformance could not be synthesized}}
case Ace = 1
case Two = 2.1 // expected-error {{cannot convert value of type 'Double' to raw type 'Int'}}
}
// rdar://22240342 - Crash in diagRecursivePropertyAccess
class r22240342 {
lazy var xx: Int = {
foo { // expected-error {{use of unresolved identifier 'foo'}}
let issueView = 42
issueView.delegate = 12
}
return 42
}()
}
// <rdar://problem/22387625> QoI: Common errors: 'let x= 5' and 'let x =5' could use Fix-its
func r22387625() {
let _= 5 // expected-error{{'=' must have consistent whitespace on both sides}} {{8-8= }}
let _ =5 // expected-error{{'=' must have consistent whitespace on both sides}} {{10-10= }}
}
// <https://bugs.swift.org/browse/SR-3135>
func SR3135() {
let _: Int= 5 // expected-error{{'=' must have consistent whitespace on both sides}} {{13-13= }}
let _: Array<Int>= [] // expected-error{{'=' must have consistent whitespace on both sides}} {{20-20= }}
}
// <rdar://problem/23086402> Swift compiler crash in CSDiag
protocol A23086402 {
var b: B23086402 { get }
}
protocol B23086402 {
var c: [String] { get }
}
func test23086402(a: A23086402) {
print(a.b.c + "") // should not crash but: expected-error {{}}
}
// <rdar://problem/23550816> QoI: Poor diagnostic in argument list of "print" (varargs related)
// The situation has changed. String now conforms to the RangeReplaceableCollection protocol
// and `ss + s` becomes ambiguous. Diambiguation is provided with the unavailable overload
// in order to produce a meaningful diagnostics. (Related: <rdar://problem/31763930>)
func test23550816(ss: [String], s: String) {
print(ss + s) // expected-error {{'+' is unavailable: Operator '+' cannot be used to append a String to a sequence of strings}}
}
// <rdar://problem/23719432> [practicalswift] Compiler crashes on &(Int:_)
func test23719432() {
var x = 42
&(Int:x) // expected-error {{use of extraneous '&'}}
}
// <rdar://problem/19911096> QoI: terrible recovery when using '·' for an operator
infix operator · { // expected-error {{'·' is considered to be an identifier, not an operator}}
associativity none precedence 150
}
// <rdar://problem/21712891> Swift Compiler bug: String subscripts with range should require closing bracket.
func r21712891(s : String) -> String {
let a = s.startIndex..<s.startIndex
_ = a
// The specific errors produced don't actually matter, but we need to reject this.
return "\(s[a)" // expected-error {{expected ']' in expression list}} expected-note {{to match this opening '['}}
}
// <rdar://problem/24029542> "Postfix '.' is reserved" error message" isn't helpful
func postfixDot(a : String) {
_ = a.utf8
_ = a. utf8 // expected-error {{extraneous whitespace after '.' is not permitted}} {{9-12=}}
_ = a. // expected-error {{expected member name following '.'}}
a. // expected-error {{expected member name following '.'}}
}
// <rdar://problem/22290244> QoI: "UIColor." gives two issues, should only give one
func f() {
_ = ClassWithStaticDecls. // expected-error {{expected member name following '.'}}
}
| apache-2.0 |
mihyaeru21/RxTwift | Pod/Classes/Objects/Place.swift | 1 | 1272 | //
// Place.swift
// Pods
//
// Created by Mihyaeru on 2/19/16.
//
//
import Foundation
import Argo
import Curry
// https://dev.twitter.com/overview/api/places
public struct Place {
public struct Box : Decodable {
public let coordinates: [[[Float]]]
public let type: String
public static func decode(json: JSON) -> Decoded<Box> {
return curry(Box.init)
<^> pure([[[0]]]) // FIXME
<*> json <| "type"
}
}
public let attributes: [String: String] // to complex...
public let boundingBox: Box
public let country: String
public let countryCode: String
public let fullName: String
public let id: String
public let name: String
public let placeType: String
public let url: String
}
extension Place : Decodable {
public static func decode(json: JSON) -> Decoded<Place> {
let a = curry(Place.init)
<^> json <||| "attributes"
<*> json <| "bounding_box"
<*> json <| "country"
<*> json <| "country_code"
<*> json <| "full_name"
<*> json <| "id"
return a <*> json <| "name"
<*> json <| "place_type"
<*> json <| "url"
}
}
| mit |
SeptiyanAndika/ViewPager---Swift | ViewPagerUITests/ViewPagerUITests.swift | 1 | 1250 | //
// ViewPagerUITests.swift
// ViewPagerUITests
//
// Created by Septiyan Andika on 6/26/16.
// Copyright © 2016 sailabs. All rights reserved.
//
import XCTest
class ViewPagerUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
dineybomfim/Nippur | Templates/File Templates/Nippur/Frontend File.xctemplate/UIViewControllerXIBSwift/___FILEBASENAME___.swift | 1 | 1786 | /*
* ___FILENAME___
* ___PROJECTNAME___
*
* Created by ___FULLUSERNAME___ on ___DATE___.
* Copyright ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
*/
import UIKit
//**********************************************************************************************************
//
// MARK: - Constants -
//
//**********************************************************************************************************
//**********************************************************************************************************
//
// MARK: - Definitions -
//
//**********************************************************************************************************
//**********************************************************************************************************
//
// MARK: - Class -
//
//**********************************************************************************************************
class ___FILEBASENAMEASIDENTIFIER___ : ___VARIABLE_cocoaTouchSubclass___ {
//**************************************************
// MARK: - Properties
//**************************************************
//**************************************************
// MARK: - Constructors
//**************************************************
//**************************************************
// MARK: - Private Methods
//**************************************************
//**************************************************
// MARK: - Self Public Methods
//**************************************************
//**************************************************
// MARK: - Override Public Methods
//**************************************************
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| mit |
barrymcandrews/aurora-ios | Aurora/UILabel+Animations.swift | 1 | 454 | //
// UILabel+Animations.swift
// Aurora
//
// Created by Barry McAndrews on 4/15/17.
// Copyright © 2017 Barry McAndrews. All rights reserved.
//
import UIKit
extension UILabel {
func setText(_ newText: String, color: UIColor) {
UIView.transition(with: self, duration: 0.25, options: [.transitionCrossDissolve], animations: {
self.text = newText
self.textColor = color
}, completion: nil)
}
}
| bsd-2-clause |
seem-sky/ios-charts | Charts/Classes/Renderers/ChartXAxisRenderer.swift | 1 | 11272 | //
// ChartXAxisRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
public class ChartXAxisRenderer: ChartAxisRendererBase
{
internal var _xAxis: ChartXAxis!;
public init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!)
{
super.init(viewPortHandler: viewPortHandler, transformer: transformer);
_xAxis = xAxis;
}
public func computeAxis(#xValAverageLength: Float, xValues: [String])
{
var a = "";
var max = Int(round(xValAverageLength + Float(_xAxis.spaceBetweenLabels)));
for (var i = 0; i < max; i++)
{
a += "h";
}
var widthText = a as NSString;
var heightText = "Q" as NSString;
_xAxis.labelWidth = widthText.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont]).width;
_xAxis.labelHeight = _xAxis.labelFont.lineHeight;
_xAxis.values = xValues;
}
public override func renderAxisLabels(#context: CGContext)
{
if (!_xAxis.isEnabled || !_xAxis.isDrawLabelsEnabled)
{
return;
}
var yoffset = CGFloat(4.0);
if (_xAxis.labelPosition == .Top)
{
drawLabels(context: context, pos: viewPortHandler.offsetTop - _xAxis.labelHeight - yoffset);
}
else if (_xAxis.labelPosition == .Bottom)
{
drawLabels(context: context, pos: viewPortHandler.contentBottom + yoffset * 1.5);
}
else if (_xAxis.labelPosition == .BottomInside)
{
drawLabels(context: context, pos: viewPortHandler.contentBottom - _xAxis.labelHeight - yoffset);
}
else if (_xAxis.labelPosition == .TopInside)
{
drawLabels(context: context, pos: viewPortHandler.offsetTop + yoffset);
}
else
{ // BOTH SIDED
drawLabels(context: context, pos: viewPortHandler.offsetTop - _xAxis.labelHeight - yoffset);
drawLabels(context: context, pos: viewPortHandler.contentBottom + yoffset * 1.6);
}
}
private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint());
public override func renderAxisLine(#context: CGContext)
{
if (!_xAxis.isEnabled || !_xAxis.isDrawAxisLineEnabled)
{
return;
}
CGContextSaveGState(context);
CGContextSetStrokeColorWithColor(context, _xAxis.axisLineColor.CGColor);
CGContextSetLineWidth(context, _xAxis.axisLineWidth);
if (_xAxis.axisLineDashLengths != nil)
{
CGContextSetLineDash(context, _xAxis.axisLineDashPhase, _xAxis.axisLineDashLengths, _xAxis.axisLineDashLengths.count);
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0);
}
if (_xAxis.labelPosition == .Top
|| _xAxis.labelPosition == .TopInside
|| _xAxis.labelPosition == .BothSided)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft;
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop;
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight;
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentTop;
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2);
}
if (_xAxis.labelPosition == .Bottom
|| _xAxis.labelPosition == .BottomInside
|| _xAxis.labelPosition == .BothSided)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft;
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentBottom;
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight;
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom;
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2);
}
CGContextRestoreGState(context);
}
/// draws the x-labels on the specified y-position
internal func drawLabels(#context: CGContext, pos: CGFloat)
{
var labelFont = _xAxis.labelFont;
var labelTextColor = _xAxis.labelTextColor;
var valueToPixelMatrix = transformer.valueToPixelMatrix;
var position = CGPoint(x: 0.0, y: 0.0);
var maxx = self._maxX;
var minx = self._minX;
if (maxx >= _xAxis.values.count)
{
maxx = _xAxis.values.count - 1;
}
if (minx < 0)
{
minx = 0;
}
for (var i = minx; i <= maxx; i += _xAxis.axisLabelModulus)
{
position.x = CGFloat(i);
position.y = 0.0;
position = CGPointApplyAffineTransform(position, valueToPixelMatrix);
if (viewPortHandler.isInBoundsX(position.x))
{
var label = _xAxis.values[i];
var labelns = label as NSString;
if (_xAxis.isAvoidFirstLastClippingEnabled)
{
// avoid clipping of the last
if (i == _xAxis.values.count - 1 && _xAxis.values.count > 1)
{
var width = labelns.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont]).width;
if (width > viewPortHandler.offsetRight * 2.0
&& position.x + width > viewPortHandler.chartWidth)
{
position.x -= width / 2.0;
}
}
else if (i == 0)
{ // avoid clipping of the first
var width = labelns.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont]).width;
position.x += width / 2.0;
}
}
ChartUtils.drawText(context: context, text: label, point: CGPoint(x: position.x, y: pos), align: .Center, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]);
}
}
}
private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint());
public override func renderGridLines(#context: CGContext)
{
if (!_xAxis.isDrawGridLinesEnabled || !_xAxis.isEnabled)
{
return;
}
CGContextSaveGState(context);
CGContextSetStrokeColorWithColor(context, _xAxis.gridColor.CGColor);
CGContextSetLineWidth(context, _xAxis.gridLineWidth);
if (_xAxis.gridLineDashLengths != nil)
{
CGContextSetLineDash(context, _xAxis.gridLineDashPhase, _xAxis.gridLineDashLengths, _xAxis.gridLineDashLengths.count);
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0);
}
var valueToPixelMatrix = transformer.valueToPixelMatrix;
var position = CGPoint(x: 0.0, y: 0.0);
for (var i = _minX; i <= _maxX; i += _xAxis.axisLabelModulus)
{
position.x = CGFloat(i);
position.y = 0.0;
position = CGPointApplyAffineTransform(position, valueToPixelMatrix);
if (position.x >= viewPortHandler.offsetLeft
&& position.x <= viewPortHandler.chartWidth)
{
_gridLineSegmentsBuffer[0].x = position.x;
_gridLineSegmentsBuffer[0].y = viewPortHandler.contentTop;
_gridLineSegmentsBuffer[1].x = position.x;
_gridLineSegmentsBuffer[1].y = viewPortHandler.contentBottom;
CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2);
}
}
CGContextRestoreGState(context);
}
private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint());
public override func renderLimitLines(#context: CGContext)
{
var limitLines = _xAxis.limitLines;
if (limitLines.count == 0)
{
return;
}
CGContextSaveGState(context);
var trans = transformer.valueToPixelMatrix;
var position = CGPoint(x: 0.0, y: 0.0);
for (var i = 0; i < limitLines.count; i++)
{
var l = limitLines[i];
position.x = CGFloat(l.limit);
position.y = 0.0;
position = CGPointApplyAffineTransform(position, trans);
_limitLineSegmentsBuffer[0].x = position.x;
_limitLineSegmentsBuffer[0].y = viewPortHandler.contentTop;
_limitLineSegmentsBuffer[1].x = position.y;
_limitLineSegmentsBuffer[1].y = viewPortHandler.contentBottom;
CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor);
CGContextSetLineWidth(context, l.lineWidth);
if (l.lineDashLengths != nil)
{
CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count);
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0);
}
CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2);
var label = l.label;
// if drawing the limit-value label is enabled
if (label.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) > 0)
{
var labelLineHeight = l.valueFont.lineHeight;
let add = CGFloat(4.0);
var xOffset: CGFloat = l.lineWidth;
var yOffset: CGFloat = add / 2.0;
if (l.labelPosition == .Right)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x + xOffset,
y: viewPortHandler.contentBottom - labelLineHeight - yOffset),
align: .Left,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]);
}
else
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x + xOffset,
y: viewPortHandler.contentTop + yOffset),
align: .Left,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]);
}
}
}
CGContextRestoreGState(context);
}
} | apache-2.0 |
numist/Tetris | CoreTetrisTests/TetriminoGeneratorTests.swift | 1 | 1072 | import XCTest
import CoreTetris
class TetriminoGeneratorTests: XCTestCase {
func testRandomGenerator() {
var shapes: [TetriminoShape] = []
let generator = RandomGenerator(generator: FibonacciLinearFeedbackShiftRegister16())
for _ in 0..<TetriminoShape.allValues.count {
let next = generator.next()
XCTAssert(!shapes.contains(next))
shapes.append(next)
}
for _ in 0..<TetriminoShape.allValues.count {
let next = generator.next()
XCTAssert(shapes.contains(next))
if let index = shapes.indexOf(next) {
shapes.removeAtIndex(index)
}
}
XCTAssert(shapes.count == 0)
}
func testCopiesProduceSameValuesAsOriginal() {
let generator1 = RandomGenerator(generator: FibonacciLinearFeedbackShiftRegister16())
let generator2 = generator1.copy()
for _ in 0..<(TetriminoShape.allValues.count * 2) {
XCTAssertEqual(generator1.next(), generator2.next())
}
}
}
| mit |
practicalswift/swift | test/decl/protocol/typealias_inference.swift | 32 | 491 | // RUN: %target-typecheck-verify-swift
// SR-8813
// By itself in this file because this particular expected error is omitted if there have been any other diagnostics.
protocol BaseProtocol {
associatedtype Value
typealias Closure = () -> Value
init(closure: Closure)
}
struct Base<Value>: BaseProtocol {
private let closure: Closure
init(closure: Closure) { //expected-error {{reference to invalid type alias 'Closure' of type 'Base<Value>'}}
self.closure = closure
}
}
| apache-2.0 |
hironytic/Kiretan0 | Kiretan0/Config.swift | 1 | 1559 | //
// Config.swift
// Kiretan0
//
// Copyright (c) 2018 Hironori Ichimiya <hiron@hironytic.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 struct Config: Codable {
public let teamID: String
public static let bundled: Config = {
let url = URL(fileURLWithPath: Bundle.main.path(forResource: "Config", ofType: "plist")!)
let data = try! Data(contentsOf: url)
let config = try! PropertyListDecoder().decode(Config.self, from: data)
return config
}()
}
| mit |
jopamer/swift | test/TBD/specialization.swift | 1 | 1718 | // Validate the the specializations actually exist (if they don't then we're not
// validating that they end up with the correct linkages):
// RUN: %target-swift-frontend -emit-sil -o- -O -validate-tbd-against-ir=none %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-ir -o/dev/null -O -validate-tbd-against-ir=all %s
// RUN: %target-swift-frontend -emit-ir -o/dev/null -O -validate-tbd-against-ir=all -enable-resilience %s
// With -enable-testing:
// RUN: %target-swift-frontend -emit-ir -o/dev/null -O -validate-tbd-against-ir=all -enable-testing %s
// RUN: %target-swift-frontend -emit-ir -o/dev/null -O -validate-tbd-against-ir=all -enable-resilience -enable-testing %s
// rdar://problem/40738913
open class Foo {
@inline(never)
fileprivate func foo<T>(_: T.Type) {}
}
open class Bar<T> {
public init() {
bar()
}
@inline(never)
fileprivate func bar() {}
}
public func f() {
Foo().foo(Int.self)
Bar<Int>().bar()
}
// Generic specialization, from the foo call in f
// CHECK-LABEL: // specialized Foo.foo<A>(_:)
// CHECK-NEXT: sil private [noinline] @$S14specialization3FooC3foo33_A6E3E43DB6679655BDF5A878ABC489A0LLyyxmlFSi_Tg5Tf4dd_n : $@convention(thin) () -> ()
// Function signature specialization, from the bar call in Bar.init
// CHECK-LABEL: // specialized Bar.bar()
// CHECK-NEXT: sil private [noinline] @$S14specialization3BarC3bar33_A6E3E43DB6679655BDF5A878ABC489A0LLyyFTf4d_n : $@convention(thin) () -> () {
// Generic specialization, from the bar call in f
// CHECK-LABEL: // specialized Bar.bar()
// CHECK-NEXT: sil private [noinline] @$S14specialization3BarC3bar33_A6E3E43DB6679655BDF5A878ABC489A0LLyyFSi_Tg5Tf4d_n : $@convention(thin) () -> ()
| apache-2.0 |
sebastienh/SwiftFlux | DemoApp/CreateTodoViewController.swift | 1 | 794 | //
// CreateTodoViewController.swift
// SwiftFlux
//
// Created by Kenichi Yonekawa on 11/20/15.
// Copyright © 2015 mog2dev. All rights reserved.
//
import UIKit
import SwiftFlux
class CreateTodoViewController: UITableViewController {
@IBOutlet weak var titleTextField: UITextField?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
titleTextField?.becomeFirstResponder()
}
@IBAction func createTodo() {
guard let title = titleTextField?.text else { return }
guard title.characters.count > 0 else { return }
ActionCreator.invoke(action: TodoAction.Create(title: title))
self.dismiss()
}
@IBAction func dismiss() {
self.dismiss(animated: true, completion: nil)
}
}
| mit |
easyui/SwiftMan | SwiftMan/Extension/Swift/Dictionary+Man.swift | 1 | 965 | //
// Dictionary+Man.swift
// SwiftMan
//
// Created by yangjun on 16/5/4.
// Copyright © 2016年 yangjun. All rights reserved.
//
extension Dictionary {
/// 转JSON
///
/// - Returns: 可选的格式化的JSON字符串
public func m_prettyJSONString() -> String?{
return m_JSONString(option: [.prettyPrinted])
}
/// 转JSON
///
/// - Returns: 可选的一行JSON字符串
public func m_JSONStringRepresentation() -> String?{
return m_JSONString(option: [])
}
/// 转JSON
///
/// - Returns: 可选的JSON字符串
public func m_JSONString(option: JSONSerialization.WritingOptions,encoding:String.Encoding = String.Encoding.utf8) -> String?{
do{
let data = try JSONSerialization.data(withJSONObject: self, options: option)
return String(data: data, encoding: encoding)
} catch {
return nil
}
}
}
| mit |
czechboy0/Buildasaur | BuildaKit/SyncPairResolver.swift | 2 | 14948 | //
// SyncPair_BotLogic.swift
// Buildasaur
//
// Created by Honza Dvorsky on 19/05/15.
// Copyright (c) 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import XcodeServerSDK
import BuildaGitServer
import BuildaUtils
public class SyncPairResolver {
public init() {
//
}
public func resolveActionsForCommitAndIssueWithBotIntegrations(
commit: String,
issue: IssueType?,
bot: Bot,
hostname: String,
buildStatusCreator: BuildStatusCreator,
integrations: [Integration]) -> SyncPair.Actions {
var integrationsToCancel: [Integration] = []
let startNewIntegration: Bool = false
//------------
// Split integrations into two groups: 1) for this SHA, 2) the rest
//------------
let uniqueIntegrations = Set(integrations)
//1) for this SHA
let headCommitIntegrations = Set(self.headCommitIntegrationsFromAllIntegrations(commit, allIntegrations: integrations))
//2) the rest
let otherCommitIntegrations = uniqueIntegrations.subtract(headCommitIntegrations)
let noncompletedOtherCommitIntegrations: Set<Integration> = otherCommitIntegrations.filterSet {
return $0.currentStep != .Completed
}
//2.1) Ok, now first cancel all unfinished integrations of the non-current commits
integrationsToCancel += Array(noncompletedOtherCommitIntegrations)
//------------
// Now we're resolving Integrations for the current commit only
//------------
/*
The resolving logic goes like this now. We have an array of integrations I for the latest commits.
A. is array empty?
A1. true -> there are no integrations for this commit. kick one off! we're done.
A2. false -> keep resolving (all references to "integrations" below mean only integrations of the current commit
B. take all pending integrations, keep the most recent one, if it's there, cancel all the other ones.
C. take the running integration, if it's there
D. take all completed integrations
resolve the status of the PR as follows
E. is there a latest pending integration?
E1. true -> status is ["Pending": "Waiting on the queue"]. also, if there's a running integration, cancel it.
E2. false ->
F. is there a running integration?
F1. true -> status is ["Pending": "Integration in progress..."]. update status and do nothing else.
F2. false ->
G. are there any completed integrations?
G1. true -> based on the result of the integrations create the PR status
G2. false -> this shouldn't happen, print a very angry message.
*/
//A. is this array empty?
if headCommitIntegrations.count == 0 {
//A1. - it's empty, kick off an integration for the latest commit
return SyncPair.Actions(
integrationsToCancel: integrationsToCancel,
statusToSet: nil,
startNewIntegrationBot: bot
)
}
//A2. not empty, keep resolving
//B. get pending Integrations
let pending = headCommitIntegrations.filterSet {
$0.currentStep == .Pending
}
var latestPendingIntegration: Integration?
if pending.count > 0 {
//we should cancel all but the most recent one
//turn the pending set into an array and sort by integration number in ascending order
var pendingSortedArray: Array<Integration> = Array(pending).sort({ (integrationA, integrationB) -> Bool in
return integrationA.number < integrationB.number
})
//keep the latest, which will be the last in the array
//let this one run, it might have been a force rebuild.
latestPendingIntegration = pendingSortedArray.removeLast()
//however, cancel the rest of the pending integrations
integrationsToCancel += pendingSortedArray
}
//Get the running integration, if it's there
let runningIntegration = headCommitIntegrations.filterSet {
$0.currentStep != .Completed && $0.currentStep != .Pending
}.first
//Get all completed integrations for this commit
let completedIntegrations = headCommitIntegrations.filterSet {
$0.currentStep == .Completed
}
let link = { (integration: Integration) -> String? in
SyncPairResolver.linkToServer(hostname, bot: bot, integration: integration)
}
//resolve to a status
let actions = self.resolveCommitStatusFromLatestIntegrations(
commit,
issue: issue,
pending: latestPendingIntegration,
running: runningIntegration,
link: link,
statusCreator: buildStatusCreator,
completed: completedIntegrations)
//merge in nested actions
return SyncPair.Actions(
integrationsToCancel: integrationsToCancel + (actions.integrationsToCancel ?? []),
statusToSet: actions.statusToSet,
startNewIntegrationBot: actions.startNewIntegrationBot ?? (startNewIntegration ? bot : nil)
)
}
func headCommitIntegrationsFromAllIntegrations(headCommit: String, allIntegrations: [Integration]) -> [Integration] {
let uniqueIntegrations = Set(allIntegrations)
//1) for this SHA
let headCommitIntegrations = uniqueIntegrations.filterSet {
(integration: Integration) -> Bool in
//if it's not pending, we need to take a look at the blueprint and inspect the SHA.
if let blueprint = integration.blueprint, let sha = blueprint.commitSHA {
return sha.hasPrefix(headCommit) //headCommit is sometimes a short version only
}
//when an integration is Pending, Preparing or Checking out, it doesn't have a blueprint, but it is, by definition, a headCommit
//integration (because it will check out the latest commit on the branch when it starts running)
if
integration.currentStep == .Pending ||
integration.currentStep == .Preparing ||
integration.currentStep == .Checkout
{
return true
}
if integration.currentStep == .Completed {
if let result = integration.result {
//if the result doesn't have a SHA yet and isn't pending - take a look at the result
//if it's a checkout-error, assume that it is a malformed SSH key bot, so don't keep
//restarting integrations - at least until someone fixes it (by closing the PR and fixing
//their SSH keys in Buildasaur so that when the next bot gets created, it does so with the right
//SSH keys.
if result == .CheckoutError {
Log.error("Integration #\(integration.number) finished with a checkout error - please check that your SSH keys setup in Buildasaur are correct! If you need to fix them, please do so and then you need to recreate the bot - e.g. by closing the Pull Request, waiting for a sync (bot will disappear) and then reopening the Pull Request - should do the job!")
return true
}
if result == .Canceled {
//another case is when the integration gets doesn't yet have a blueprint AND was cancelled -
//we should assume it belongs to the latest commit, because we can't tell otherwise.
return true
}
}
}
return false
}
let sortedHeadCommitIntegrations = Array(headCommitIntegrations).sort {
(a: Integration, b: Integration) -> Bool in
return a.number > b.number
}
return sortedHeadCommitIntegrations
}
class func linkToServer(hostname: String, bot: Bot, integration: Integration) -> String {
//unfortunately, since github doesn't allow non-https links anywhere, we
//must proxy through Satellite (https://github.com/czechboy0/satellite)
//all it does is it redirects to the desired xcbot://... url, which in
//turn opens Xcode on the integration page. all good!
// let link = "xcbot://\(hostname)/botID/\(bot.id)/integrationID/\(integration.id)"
let link = "https://stlt.herokuapp.com/v1/xcs_deeplink/\(hostname)/\(bot.id)/\(integration.id)"
return link
}
func resolveCommitStatusFromLatestIntegrations(
commit: String,
issue: IssueType?,
pending: Integration?,
running: Integration?,
link: (Integration) -> String?,
statusCreator: BuildStatusCreator,
completed: Set<Integration>) -> SyncPair.Actions {
let statusWithComment: StatusAndComment
var integrationsToCancel: [Integration] = []
//if there's any pending integration, we're ["Pending" - Waiting in the queue]
if let pending = pending {
//TODO: show how many builds are ahead in the queue and estimate when it will be
//started and when finished? (there is an average running time on each bot, it should be easy)
let status = statusCreator.createStatusFromState(.Pending, description: "Build waiting in the queue...", targetUrl: link(pending))
statusWithComment = StatusAndComment(status: status, comment: nil)
//also, cancel the running integration, if it's there any
if let running = running {
integrationsToCancel.append(running)
}
} else {
//there's no pending integration, it's down to running and completed
if let running = running {
//there is a running integration.
//TODO: estimate, based on the average running time of this bot and on the started timestamp, when it will finish. add that to the description.
let currentStepString = running.currentStep.rawValue
let status = statusCreator.createStatusFromState(.Pending, description: "Integration step: \(currentStepString)...", targetUrl: link(running))
statusWithComment = StatusAndComment(status: status, comment: nil)
} else {
//there no running integration, we're down to completed integration.
if completed.count > 0 {
//we have some completed integrations
statusWithComment = self.resolveStatusFromCompletedIntegrations(completed, statusCreator: statusCreator, link: link)
} else {
//this shouldn't happen.
Log.error("LOGIC ERROR! This shouldn't happen, there are no completed integrations!")
let status = statusCreator.createStatusFromState(.Error, description: "* UNKNOWN STATE, Builda ERROR *", targetUrl: nil)
statusWithComment = StatusAndComment(status: status, comment: "Builda error, unknown state!")
}
}
}
return SyncPair.Actions(
integrationsToCancel: integrationsToCancel,
statusToSet: (status: statusWithComment, commit: commit, issue: issue),
startNewIntegrationBot: nil
)
}
func resolveStatusFromCompletedIntegrations(
integrations: Set<Integration>,
statusCreator: BuildStatusCreator,
link: (Integration) -> String?
) -> StatusAndComment {
//get integrations sorted by number
let sortedDesc = Array(integrations).sort { $0.number > $1.number }
let summary = SummaryBuilder()
summary.linkBuilder = link
summary.statusCreator = statusCreator
//if there are any succeeded, it wins - iterating from the end
if let passingIntegration = sortedDesc.filter({
(integration: Integration) -> Bool in
switch integration.result! {
case .Succeeded, .Warnings, .AnalyzerWarnings:
return true
default:
return false
}
}).first {
return summary.buildPassing(passingIntegration)
}
//ok, no succeeded, warnings or analyzer warnings, get down to test failures
if let testFailingIntegration = sortedDesc.filter({
$0.result! == .TestFailures
}).first {
return summary.buildFailingTests(testFailingIntegration)
}
//ok, the build didn't even run then. it either got cancelled or failed
if let errorredIntegration = sortedDesc.filter({
$0.result! != .Canceled
}).first {
return summary.buildErrorredIntegration(errorredIntegration)
}
//cool, not even build error. it must be just canceled ones then.
if let canceledIntegration = sortedDesc.filter({
$0.result! == .Canceled
}).first {
return summary.buildCanceledIntegration(canceledIntegration)
}
//hmm no idea, if we got all the way here. just leave it with no state.
return summary.buildEmptyIntegration()
}
}
| mit |
roop/GiveAndTake | Take/Take/Helpers/ObservationHelper.swift | 1 | 2767 | //
// ObservationHelper.swift
// Take
//
// Created by Roopesh Chander on 01/08/14.
// Copyright (c) 2014 Roopesh Chander. All rights reserved.
//
import Foundation
// Usage:
// var observer1 = object.onChange("property") { change in
// doSomethingWithChangeDict(change)
// }
// var observer2 = object.onNotification(NSMetadataQueryDidFinishGatheringNotification) {
// notification in
// doSomethingWithNotificationDict(notification.userInfo)
// }
// // Keep a strong reference to the returned observer objects
// // as long as you want to observe said thingie.
extension NSObject {
func onChange(keyPath: String, options: NSKeyValueObservingOptions,
_ block: (change: [NSObject : AnyObject]!) -> ()) -> AnyObject {
return KeyValueObserver(object: self, keyPath: keyPath, options: options, block: block)
as AnyObject
}
func onChange(keyPath: String,
_ block: (change: [NSObject : AnyObject]!) -> ()) -> AnyObject {
return KeyValueObserver(object: self, keyPath: keyPath, options: nil, block: block)
as AnyObject
}
func onNotification(name: String, _ block: ((NSNotification!) -> ())) -> AnyObject {
return NotificationObserver(object: self, name: name, queue: NSOperationQueue.currentQueue(), block: block)
as AnyObject
}
}
class KeyValueObserver: NSObject {
weak var _object: NSObject?
var _keyPath: String
var _block: (change: [NSObject : AnyObject]!) -> ()
init(object: NSObject, keyPath: String, options: NSKeyValueObservingOptions,
block: (change: [NSObject : AnyObject]!) -> ()) {
_object = object
_keyPath = keyPath
_block = block
super.init()
object.addObserver(self, forKeyPath: keyPath, options: options, context: nil)
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject,
change: [NSObject : AnyObject], context: UnsafeMutablePointer<()>) {
assert(keyPath == _keyPath)
_block(change: change)
}
deinit {
_object?.removeObserver(self, forKeyPath: _keyPath, context: nil)
}
}
class NotificationObserver: NSObject {
var _observerObject: AnyObject?
init(object: NSObject, name: String!, queue: NSOperationQueue!,
block: ((NSNotification!) -> ())) {
super.init()
_observerObject = NSNotificationCenter.defaultCenter().addObserverForName(name, object: object,
queue: queue, usingBlock: block)
}
deinit {
if let observer: AnyObject = _observerObject {
NSNotificationCenter.defaultCenter().removeObserver(observer)
}
}
}
| mit |
ernieb4768/VelocityCBT | CBT Velocity/AppDelegate.swift | 1 | 6229 | //
// AppDelegate.swift
// CBT Velocity
//
// Created by Ryan Hoffman on 3/20/16.
// Copyright © 2016 Ryan Hoffman. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("json_table_view_images", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("json_table_view_images.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
} | apache-2.0 |
335g/Mattress | Sources/Lift.swift | 1 | 246 |
public func lift<C, T, U, V>(_ f: @escaping (T, U) -> V) -> Parser<C, (T) -> (U) -> V> {
return .pure(curry(f))
}
public func lift<C, T, U, V, W>(_ f: @escaping (T, U, V) -> W) -> Parser< C, (T) -> (U) -> (V) -> W> {
return .pure(curry(f))
}
| mit |
SeriousChoice/SCSwift | Example/Pods/RxSwift/RxSwift/Traits/Infallible/Infallible+Operators.swift | 1 | 34639 | //
// Infallible+Operators.swift
// RxSwift
//
// Created by Shai Mishali on 27/08/2020.
// Copyright © 2020 Krunoslav Zaher. All rights reserved.
//
// MARK: - Static allocation
extension InfallibleType {
/**
Returns an infallible sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting infallible sequence.
- returns: An infallible sequence containing the single specified element.
*/
public static func just(_ element: Element) -> Infallible<Element> {
Infallible(.just(element))
}
/**
Returns an infallible sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting infallible sequence.
- parameter scheduler: Scheduler to send the single element on.
- returns: An infallible sequence containing the single specified element.
*/
public static func just(_ element: Element, scheduler: ImmediateSchedulerType) -> Infallible<Element> {
Infallible(.just(element, scheduler: scheduler))
}
/**
Returns a non-terminating infallible sequence, which can be used to denote an infinite duration.
- seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An infallible sequence whose observers will never get called.
*/
public static func never() -> Infallible<Element> {
Infallible(.never())
}
/**
Returns an empty infallible sequence, using the specified scheduler to send out the single `Completed` message.
- seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An infallible sequence with no elements.
*/
public static func empty() -> Infallible<Element> {
Infallible(.empty())
}
/**
Returns an infallible sequence that invokes the specified factory function whenever a new observer subscribes.
- seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html)
- parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence.
- returns: An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
public static func deferred(_ observableFactory: @escaping () throws -> Infallible<Element>)
-> Infallible<Element> {
Infallible(.deferred { try observableFactory().asObservable() })
}
}
// MARK: From & Of
extension Infallible {
/**
This method creates a new Infallible instance with a variable number of elements.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- parameter elements: Elements to generate.
- parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediately on subscription.
- returns: The Infallible sequence whose elements are pulled from the given arguments.
*/
public static func of(_ elements: Element ..., scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Infallible<Element> {
Infallible(Observable.from(elements, scheduler: scheduler))
}
}
extension Infallible {
/**
Converts an array to an Infallible sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The Infallible sequence whose elements are pulled from the given enumerable sequence.
*/
public static func from(_ array: [Element], scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Infallible<Element> {
Infallible(Observable.from(array, scheduler: scheduler))
}
/**
Converts a sequence to an Infallible sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The Infallible sequence whose elements are pulled from the given enumerable sequence.
*/
public static func from<Sequence: Swift.Sequence>(_ sequence: Sequence, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Infallible<Element> where Sequence.Element == Element {
Infallible(Observable.from(sequence, scheduler: scheduler))
}
}
// MARK: - Filter
extension InfallibleType {
/**
Filters the elements of an observable sequence based on a predicate.
- seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html)
- parameter predicate: A function to test each source element for a condition.
- returns: An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
public func filter(_ predicate: @escaping (Element) -> Bool)
-> Infallible<Element> {
Infallible(asObservable().filter(predicate))
}
}
// MARK: - Map
extension InfallibleType {
/**
Projects each element of an observable sequence into a new form.
- seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html)
- parameter transform: A transform function to apply to each source element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
public func map<Result>(_ transform: @escaping (Element) -> Result)
-> Infallible<Result> {
Infallible(asObservable().map(transform))
}
/**
Projects each element of an observable sequence into an optional form and filters all optional results.
- parameter transform: A transform function to apply to each source element and which returns an element or nil.
- returns: An observable sequence whose elements are the result of filtering the transform function for each element of the source.
*/
public func compactMap<Result>(_ transform: @escaping (Element) -> Result?)
-> Infallible<Result> {
Infallible(asObservable().compactMap(transform))
}
}
// MARK: - Distinct
extension InfallibleType where Element: Comparable {
/**
Returns an observable sequence that contains only distinct contiguous elements according to equality operator.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence.
*/
public func distinctUntilChanged()
-> Infallible<Element> {
Infallible(asObservable().distinctUntilChanged())
}
}
extension InfallibleType {
/**
Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- parameter keySelector: A function to compute the comparison key for each element.
- returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
public func distinctUntilChanged<Key: Equatable>(_ keySelector: @escaping (Element) throws -> Key)
-> Infallible<Element> {
Infallible(self.asObservable().distinctUntilChanged(keySelector, comparer: { $0 == $1 }))
}
/**
Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- parameter comparer: Equality comparer for computed key values.
- returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence.
*/
public func distinctUntilChanged(_ comparer: @escaping (Element, Element) throws -> Bool)
-> Infallible<Element> {
Infallible(self.asObservable().distinctUntilChanged({ $0 }, comparer: comparer))
}
/**
Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- parameter keySelector: A function to compute the comparison key for each element.
- parameter comparer: Equality comparer for computed key values.
- returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence.
*/
public func distinctUntilChanged<K>(_ keySelector: @escaping (Element) throws -> K, comparer: @escaping (K, K) throws -> Bool)
-> Infallible<Element> {
Infallible(asObservable().distinctUntilChanged(keySelector, comparer: comparer))
}
/**
Returns an observable sequence that contains only contiguous elements with distinct values in the provided key path on each object.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- returns: An observable sequence only containing the distinct contiguous elements, based on equality operator on the provided key path
*/
public func distinctUntilChanged<Property: Equatable>(at keyPath: KeyPath<Element, Property>) ->
Infallible<Element> {
Infallible(asObservable().distinctUntilChanged { $0[keyPath: keyPath] == $1[keyPath: keyPath] })
}
}
// MARK: - Throttle
extension InfallibleType {
/**
Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers.
- seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html)
- parameter dueTime: Throttling duration for each element.
- parameter scheduler: Scheduler to run the throttle timers on.
- returns: The throttled sequence.
*/
public func debounce(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> Infallible<Element> {
Infallible(asObservable().debounce(dueTime, scheduler: scheduler))
}
/**
Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration.
This operator makes sure that no two elements are emitted in less then dueTime.
- seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html)
- parameter dueTime: Throttling duration for each element.
- parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted.
- parameter scheduler: Scheduler to run the throttle timers on.
- returns: The throttled sequence.
*/
public func throttle(_ dueTime: RxTimeInterval, latest: Bool = true, scheduler: SchedulerType)
-> Infallible<Element> {
Infallible(asObservable().throttle(dueTime, latest: latest, scheduler: scheduler))
}
}
// MARK: - FlatMap
extension InfallibleType {
/**
Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
- seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to each element.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.
*/
public func flatMap<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source)
-> Infallible<Source.Element> {
Infallible(asObservable().flatMap(selector))
}
/**
Projects each element of an observable sequence into a new sequence of observable sequences and then
transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
It is a combination of `map` + `switchLatest` operator
- seealso: [flatMapLatest operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to each element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an
Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
public func flatMapLatest<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source)
-> Infallible<Source.Element> {
Infallible(asObservable().flatMapLatest(selector))
}
/**
Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
If element is received while there is some projected observable sequence being merged it will simply be ignored.
- seealso: [flatMapFirst operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated.
*/
public func flatMapFirst<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source)
-> Infallible<Source.Element> {
Infallible(asObservable().flatMapFirst(selector))
}
}
// MARK: - Concat
extension InfallibleType {
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func concat<Source: ObservableConvertibleType>(_ second: Source) -> Infallible<Element> where Source.Element == Element {
Infallible(Observable.concat([self.asObservable(), second.asObservable()]))
}
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<Sequence: Swift.Sequence>(_ sequence: Sequence) -> Infallible<Element>
where Sequence.Element == Infallible<Element> {
Infallible(Observable.concat(sequence.map { $0.asObservable() }))
}
/**
Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<Collection: Swift.Collection>(_ collection: Collection) -> Infallible<Element>
where Collection.Element == Infallible<Element> {
Infallible(Observable.concat(collection.map { $0.asObservable() }))
}
/**
Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat(_ sources: Infallible<Element> ...) -> Infallible<Element> {
Infallible(Observable.concat(sources.map { $0.asObservable() }))
}
/**
Projects each element of an observable sequence to an observable sequence and concatenates the resulting observable sequences into one observable sequence.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
public func concatMap<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source)
-> Infallible<Source.Element> {
Infallible(asObservable().concatMap(selector))
}
}
// MARK: - Merge
extension InfallibleType {
/**
Merges elements from all observable sequences from collection into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge<Collection: Swift.Collection>(_ sources: Collection) -> Infallible<Element> where Collection.Element == Infallible<Element> {
Infallible(Observable.concat(sources.map { $0.asObservable() }))
}
/**
Merges elements from all infallible sequences from array into a single infallible sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Array of infallible sequences to merge.
- returns: The infallible sequence that merges the elements of the infallible sequences.
*/
public static func merge(_ sources: [Infallible<Element>]) -> Infallible<Element> {
Infallible(Observable.merge(sources.map { $0.asObservable() }))
}
/**
Merges elements from all infallible sequences into a single infallible sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of infallible sequences to merge.
- returns: The infallible sequence that merges the elements of the infallible sequences.
*/
public static func merge(_ sources: Infallible<Element>...) -> Infallible<Element> {
Infallible(Observable.merge(sources.map { $0.asObservable() }))
}
}
// MARK: - Do
extension Infallible {
/**
Invokes an action for each event in the infallible sequence, and propagates all observer messages through the result sequence.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter afterNext: Action to invoke for each element after the observable has passed an onNext event along to its downstream.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter afterCompleted: Action to invoke after graceful termination of the observable sequence.
- parameter onSubscribe: Action to invoke before subscribing to source observable sequence.
- parameter onSubscribed: Action to invoke after subscribing to source observable sequence.
- parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed.
- returns: The source sequence with the side-effecting behavior applied.
*/
public func `do`(onNext: ((Element) throws -> Void)? = nil, afterNext: ((Element) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, afterCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil) -> Infallible<Element> {
Infallible(asObservable().do(onNext: onNext, afterNext: afterNext, onCompleted: onCompleted, afterCompleted: afterCompleted, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose))
}
}
// MARK: - Scan
extension InfallibleType {
/**
Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value.
For aggregation behavior with no intermediate results, see `reduce`.
- seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html)
- parameter seed: The initial accumulator value.
- parameter accumulator: An accumulator function to be invoked on each element.
- returns: An observable sequence containing the accumulated values.
*/
public func scan<Seed>(into seed: Seed, accumulator: @escaping (inout Seed, Element) -> Void)
-> Infallible<Seed> {
Infallible(asObservable().scan(into: seed, accumulator: accumulator))
}
/**
Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value.
For aggregation behavior with no intermediate results, see `reduce`.
- seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html)
- parameter seed: The initial accumulator value.
- parameter accumulator: An accumulator function to be invoked on each element.
- returns: An observable sequence containing the accumulated values.
*/
public func scan<Seed>(_ seed: Seed, accumulator: @escaping (Seed, Element) -> Seed)
-> Infallible<Seed> {
Infallible(asObservable().scan(seed, accumulator: accumulator))
}
}
// MARK: - Start with
extension InfallibleType {
/**
Prepends a value to an observable sequence.
- seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html)
- parameter element: Element to prepend to the specified sequence.
- returns: The source sequence prepended with the specified values.
*/
public func startWith(_ element: Element) -> Infallible<Element> {
Infallible(asObservable().startWith(element))
}
}
// MARK: - Take and Skip {
extension InfallibleType {
/**
Returns the elements from the source observable sequence until the other observable sequence produces an element.
- seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html)
- parameter other: Observable sequence that terminates propagation of elements of the source sequence.
- returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
public func take<Source: InfallibleType>(until other: Source)
-> Infallible<Element> {
Infallible(asObservable().take(until: other.asObservable()))
}
/**
Returns the elements from the source observable sequence until the other observable sequence produces an element.
- seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html)
- parameter other: Observable sequence that terminates propagation of elements of the source sequence.
- returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
public func take<Source: ObservableType>(until other: Source)
-> Infallible<Element> {
Infallible(asObservable().take(until: other))
}
/**
Returns elements from an observable sequence until the specified condition is true.
- seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html)
- parameter predicate: A function to test each element for a condition.
- parameter behavior: Whether or not to include the last element matching the predicate. Defaults to `exclusive`.
- returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test passes.
*/
public func take(until predicate: @escaping (Element) throws -> Bool,
behavior: TakeBehavior = .exclusive)
-> Infallible<Element> {
Infallible(asObservable().take(until: predicate, behavior: behavior))
}
/**
Returns elements from an observable sequence as long as a specified condition is true.
- seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html)
- parameter predicate: A function to test each element for a condition.
- returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
public func take(while predicate: @escaping (Element) throws -> Bool,
behavior: TakeBehavior = .exclusive)
-> Infallible<Element> {
Infallible(asObservable().take(while: predicate, behavior: behavior))
}
/**
Returns a specified number of contiguous elements from the start of an observable sequence.
- seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html)
- parameter count: The number of elements to return.
- returns: An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
public func take(_ count: Int) -> Infallible<Element> {
Infallible(asObservable().take(count))
}
/**
Takes elements for the specified duration from the start of the infallible source sequence, using the specified scheduler to run timers.
- seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html)
- parameter duration: Duration for taking elements from the start of the sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An infallible sequence with the elements taken during the specified duration from the start of the source sequence.
*/
public func take(for duration: RxTimeInterval, scheduler: SchedulerType)
-> Infallible<Element> {
Infallible(asObservable().take(for: duration, scheduler: scheduler))
}
/**
Bypasses elements in an infallible sequence as long as a specified condition is true and then returns the remaining elements.
- seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html)
- parameter predicate: A function to test each element for a condition.
- returns: An infallible sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
public func skip(while predicate: @escaping (Element) throws -> Bool) -> Infallible<Element> {
Infallible(asObservable().skip(while: predicate))
}
/**
Returns the elements from the source infallible sequence that are emitted after the other infallible sequence produces an element.
- seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html)
- parameter other: Infallible sequence that starts propagation of elements of the source sequence.
- returns: An infallible sequence containing the elements of the source sequence that are emitted after the other sequence emits an item.
*/
public func skip<Source: ObservableType>(until other: Source)
-> Infallible<Element> {
Infallible(asObservable().skip(until: other))
}
}
// MARK: - Share
extension InfallibleType {
/**
Returns an observable sequence that **shares a single subscription to the underlying sequence**, and immediately upon subscription replays elements in buffer.
This operator is equivalent to:
* `.whileConnected`
```
// Each connection will have it's own subject instance to store replay events.
// Connections will be isolated from each another.
source.multicast(makeSubject: { Replay.create(bufferSize: replay) }).refCount()
```
* `.forever`
```
// One subject will store replay events for all connections to source.
// Connections won't be isolated from each another.
source.multicast(Replay.create(bufferSize: replay)).refCount()
```
It uses optimized versions of the operators for most common operations.
- parameter replay: Maximum element count of the replay buffer.
- parameter scope: Lifetime scope of sharing subject. For more information see `SubjectLifetimeScope` enum.
- seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html)
- returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
public func share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected)
-> Infallible<Element> {
Infallible(asObservable().share(replay: replay, scope: scope))
}
}
// MARK: - withUnretained
extension InfallibleType {
/**
Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence.
In the case the provided object cannot be retained successfully, the sequence will complete.
- note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle.
- parameter obj: The object to provide an unretained reference on.
- parameter resultSelector: A function to combine the unretained referenced on `obj` and the value of the observable sequence.
- returns: An observable sequence that contains the result of `resultSelector` being called with an unretained reference on `obj` and the values of the original sequence.
*/
public func withUnretained<Object: AnyObject, Out>(
_ obj: Object,
resultSelector: @escaping (Object, Element) -> Out
) -> Infallible<Out> {
Infallible(self.asObservable().withUnretained(obj, resultSelector: resultSelector))
}
/**
Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence.
In the case the provided object cannot be retained successfully, the sequence will complete.
- note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle.
- parameter obj: The object to provide an unretained reference on.
- returns: An observable sequence of tuples that contains both an unretained reference on `obj` and the values of the original sequence.
*/
public func withUnretained<Object: AnyObject>(_ obj: Object) -> Infallible<(Object, Element)> {
withUnretained(obj) { ($0, $1) }
}
}
extension InfallibleType {
// MARK: - withLatestFrom
/**
Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any.
- seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
- note: Elements emitted by self before the second source has emitted any values will be omitted.
- parameter second: Second observable source.
- parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any.
- returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function.
*/
public func withLatestFrom<Source: InfallibleType, ResultType>(_ second: Source, resultSelector: @escaping (Element, Source.Element) throws -> ResultType) -> Infallible<ResultType> {
Infallible(self.asObservable().withLatestFrom(second.asObservable(), resultSelector: resultSelector))
}
/**
Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emits an element.
- seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
- note: Elements emitted by self before the second source has emitted any values will be omitted.
- parameter second: Second observable source.
- returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function.
*/
public func withLatestFrom<Source: InfallibleType>(_ second: Source) -> Infallible<Source.Element> {
withLatestFrom(second) { $1 }
}
}
| mit |
biohazardlover/ROer | Roer/MapViewerViewController.swift | 1 | 7196 |
import UIKit
import GLKit
import MBProgressHUD
import SwiftyJSON
class MapViewerViewController: UIViewController {
fileprivate var mapView: GLKView!
@IBOutlet var panGestureRecognizer: UIPanGestureRecognizer!
@IBOutlet var twoFingersPanGestureRecognizer: UIPanGestureRecognizer!
@IBOutlet var pinchGestureRecognizer: UIPinchGestureRecognizer!
@IBOutlet var rotationGestureRecognizer: UIRotationGestureRecognizer!
fileprivate var panStartTranslation: (x: Float, y: Float) = (0, 0)
fileprivate var pinchStartScale: Float = 0
fileprivate var rotationStartRotation: Float = 0
@IBOutlet var mapListView: UITableView!
fileprivate var hud: MBProgressHUD?
fileprivate var mapList: JSON {
let url = Bundle.main.url(forResource: "MapList", withExtension: "json")!
let data = try! Data(contentsOf: url)
return JSON(data: data)
}
fileprivate var renderer: MapRenderer!
override func viewDidLoad() {
super.viewDidLoad()
title = "MapViewer".localized
var context = EAGLContext(api: .openGLES3)
if context == nil {
context = EAGLContext(api: .openGLES2)
}
mapView = GLKView(frame: view.bounds, context: context!)
mapView.addGestureRecognizer(panGestureRecognizer)
mapView.addGestureRecognizer(twoFingersPanGestureRecognizer)
mapView.addGestureRecognizer(pinchGestureRecognizer)
mapView.addGestureRecognizer(rotationGestureRecognizer)
EAGLContext.setCurrent(context)
let displayLink = CADisplayLink(target: self, selector: #selector(render(_:)))
displayLink.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
view.addSubview(mapView)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if renderer == nil {
renderer = MapRenderer(context: EAGLContext.current()!, size: mapView.bounds.size)
renderer.delegate = self
mapView.delegate = renderer
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
mapView.frame = UIEdgeInsetsInsetRect(view.bounds, UIEdgeInsets(top: 0, left: 0, bottom: 150, right: 0))
}
}
extension MapViewerViewController {
@objc func render(_ displayLink: CADisplayLink) {
mapView.setNeedsDisplay()
}
}
extension MapViewerViewController {
@IBAction func handlePan(_ sender: AnyObject) {
switch panGestureRecognizer.state {
case .began:
panStartTranslation = renderer.translation
case .changed:
let translation = panGestureRecognizer.translation(in: mapView)
renderer.translation.x = panStartTranslation.x + Float(translation.x) * 0.001
renderer.translation.y = panStartTranslation.y + Float(translation.y) * -0.001
renderer.updateModelView()
mapView.setNeedsDisplay()
default: break
}
}
@IBAction func handleTwoFingersPan(_ sender: AnyObject) {
switch twoFingersPanGestureRecognizer.state {
case .changed:
if twoFingersPanGestureRecognizer.location(in: mapView).y > 0 {
renderer.angle += 1
if renderer.angle > 90 {
renderer.angle = 90
}
} else {
renderer.angle -= 1
if renderer.angle < 5 {
renderer.angle = 5
}
}
renderer.updateModelView()
mapView.setNeedsDisplay()
default: break
}
}
@IBAction func handlePinch(_ sender: AnyObject) {
switch pinchGestureRecognizer.state {
case .began:
pinchStartScale = renderer.zoom
renderer.zoom = pinchStartScale * Float(pinchGestureRecognizer.scale)
renderer.updateModelView()
mapView.setNeedsDisplay()
case .changed:
renderer.zoom = pinchStartScale * Float(pinchGestureRecognizer.scale)
renderer.updateModelView()
mapView.setNeedsDisplay()
default: break
}
}
@IBAction func handleRotation(_ sender: AnyObject) {
switch rotationGestureRecognizer.state {
case .began:
rotationStartRotation = renderer.rotate
renderer.rotate = rotationStartRotation + GLKMathRadiansToDegrees(Float(-rotationGestureRecognizer.rotation))
renderer.updateModelView()
mapView.setNeedsDisplay()
case .changed:
renderer.rotate = rotationStartRotation + GLKMathRadiansToDegrees(Float(-rotationGestureRecognizer.rotation))
renderer.updateModelView()
mapView.setNeedsDisplay()
default: break
}
}
}
extension MapViewerViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mapList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MapListCell", for: indexPath)
cell.textLabel?.text = mapList[indexPath.row].arrayValue[1].stringValue
return cell
}
}
extension MapViewerViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let mapName = mapList[indexPath.row].arrayValue[0].stringValue
let downloader = MapDownloader(mapName: mapName)
downloader.delegate = self
downloader.download()
}
}
extension MapViewerViewController: MapDownloaderDelegate {
func mapDownloaderDidStartDownloading(_ mapDownloader: MapDownloader) {
hud = MBProgressHUD.showAdded(to: view, animated: true)
hud?.mode = .indeterminate
hud?.removeFromSuperViewOnHide = true
hud?.minShowTime = 0.5
}
func mapDownloader(_ mapDownloader: MapDownloader, completedUnitCount: Int, totalUnitCount: Int) {
hud?.mode = .determinateHorizontalBar
hud?.progress = Float(completedUnitCount) / Float(totalUnitCount)
hud?.label.text = "\(completedUnitCount) / \(totalUnitCount)"
}
func mapDownloaderDidFinishDownloading(_ mapDownloader: MapDownloader) {
hud?.hide(animated: true)
guard let indexPath = mapListView.indexPathForSelectedRow else { return }
let mapName = mapList[indexPath.row].arrayValue[0].stringValue
renderer.loadRsw(mapName)
}
}
extension MapViewerViewController: MapRendererDelegate {
func mapRendererDidStartRendering(_ mapRenderer: MapRenderer) {
hud = MBProgressHUD.showAdded(to: view, animated: true)
hud?.mode = .indeterminate
hud?.removeFromSuperViewOnHide = true
}
func mapRendererDidFinishRendering(_ mapRenderer: MapRenderer) {
hud?.hide(animated: true)
mapView.setNeedsDisplay()
}
}
| mit |
marekmatula/FontIcons.Swift | Pod/Classes/Extensions.swift | 1 | 4898 | //
// Extensions.swift
// FontIcons.swift
//
// Created by Marek Matula on 05.02.16.
// Copyright © 2016 Marek Matula. All rights reserved.
//
import Foundation
import UIKit
public let defaultFontIconSize:CGFloat = 23.0
public extension UIBarButtonItem {
func setFontIcon(_ icon: FontEnum, size: CGFloat = defaultFontIconSize) {
setFontIconText(prefix: "", icon: icon, postfix: "", size: size)
}
func setFontIconText(prefix: String, icon: FontEnum, postfix: String, size: CGFloat) {
let font = FontLoader.getFont(icon, iconSize: size)
setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal)
setTitleTextAttributes([NSAttributedString.Key.font: font], for: .highlighted)
setTitleTextAttributes([NSAttributedString.Key.font: font], for: .disabled)
#if giOS8OrGreater
setTitleTextAttributes([NSFontAttributeName: font], for: .focused)
#endif
title = FontLoader.concat(prefix: prefix, icon: icon, postfix: postfix)
}
}
public extension UIButton {
func setFontIcon(_ icon: FontEnum, forState: UIControl.State) {
if let label = titleLabel {
setFontIcon(icon, size: label.font.pointSize, forState: forState)
}
}
func setFontIcon(_ icon: FontEnum, size:CGFloat, forState: UIControl.State) {
setFontIconText(prefix: "", icon: icon, postfix: "", size: size, forState: forState)
}
func setFontIconText(prefix: String, icon: FontEnum, postfix: String, size: CGFloat, forState: UIControl.State) {
let font = FontLoader.getFont(icon, iconSize: size)
if let label = titleLabel {
label.font = font
let text = FontLoader.concat(prefix: prefix, icon: icon, postfix: postfix)
setTitle(text, for: forState)
}
}
}
public extension UILabel {
func setFontIcon(_ icon: FontEnum, size: CGFloat = defaultFontIconSize) {
setFontIconText(prefix: "", icon: icon, postfix: "", size: size)
}
func setFontIconText(prefix: String, icon: FontEnum, postfix: String, size: CGFloat) {
let font = FontLoader.getFont(icon, iconSize: size)
self.font = font
self.text = FontLoader.concat(prefix: prefix, icon: icon, postfix: postfix)
}
}
public extension UIImageView {
public func setFontIcon(_ icon: FontEnum, textColor: UIColor, backgroundColor: UIColor = UIColor.clear) {
self.image = UIImage(icon: icon, size: frame.size, textColor: textColor, backgroundColor: backgroundColor)
}
}
public extension UITabBarItem {
public func setFontIcon(_ icon: FontEnum) {
image = UIImage(icon: icon, size: CGSize(width: 30, height: 30))
}
}
public extension UISegmentedControl {
public func setFontIcon(_ icon: FontEnum, forSegmentAtIndex segment: Int) {
let font = FontLoader.getFont(icon, iconSize: defaultFontIconSize)
setTitleTextAttributes([NSAttributedString.Key.font: font], for: UIControl.State())
setTitle(icon.unicode(), forSegmentAt: segment)
}
}
public extension UIImage {
public convenience init(icon: FontEnum, size: CGSize, textColor: UIColor = UIColor.black, backgroundColor: UIColor = UIColor.clear) {
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = NSTextAlignment.center
// Taken from FontAwesome.io's Fixed Width Icon CSS
let fontAspectRatio: CGFloat = 1.28571429
let fontSize = min(size.width / fontAspectRatio, size.height)
let font = FontLoader.getFont(icon, iconSize: fontSize)
let attributes = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: textColor, NSAttributedString.Key.backgroundColor: backgroundColor, NSAttributedString.Key.paragraphStyle: paragraph]
let attributedString = NSAttributedString(string: icon.unicode(), attributes: attributes)
UIGraphicsBeginImageContextWithOptions(size, false , 0.0)
attributedString.draw(in: CGRect(x: 0, y: (size.height - fontSize) / 2, width: size.width, height: fontSize))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.init(cgImage: image!.cgImage!, scale: image!.scale, orientation: image!.imageOrientation)
}
}
public extension UISlider {
func setFontIconMaximumValueImage(_ icon: FontEnum, customSize: CGSize? = nil) {
maximumValueImage = UIImage(icon: icon, size: customSize ?? CGSize(width: 25, height: 25))
}
func setFontIconMinimumValueImage(_ icon: FontEnum, customSize: CGSize? = nil) {
minimumValueImage = UIImage(icon: icon, size: customSize ?? CGSize(width: 25, height: 25))
}
}
| mit |
linkedin/LayoutKit | Sources/ObjCSupport/Internal/ReverseWrappedLayout.swift | 1 | 1587 | // Copyright 2018 LinkedIn Corp.
// 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.
import CoreGraphics
class ReverseWrappedLayout: Layout {
func arrangement(within rect: CGRect, measurement: LayoutMeasurement) -> LayoutArrangement {
return layout.arrangement(within: rect, measurement: LOKLayoutMeasurement(wrappedLayout: layout, layoutMeasurement: measurement)).layoutArrangement
}
func measurement(within maxSize: CGSize) -> LayoutMeasurement {
let measurement: LOKLayoutMeasurement = layout.measurement(within: maxSize)
return LayoutMeasurement(layout: self, size: measurement.size, maxSize: measurement.maxSize, sublayouts: measurement.sublayouts.map { $0.measurement })
}
var needsView: Bool {
return layout.needsView
}
func makeView() -> View {
return layout.makeView()
}
func configure(baseTypeView: View) {
layout.configureView(baseTypeView)
}
var flexibility: Flexibility {
return layout.flexibility.flexibility
}
var viewReuseId: String? {
return layout.viewReuseId
}
let layout: LOKLayout
init(layout: LOKLayout) {
self.layout = layout
}
}
| apache-2.0 |
touchvie/sdk-front-ios | SDKFrontiOS/SDKFrontiOS/Cast.swift | 1 | 477 | //
// Cast.swift
// SDKFrontiOS
//
// Created by Sergio Girao on 17/10/16.
// Copyright © 2016 Tagsonomy. All rights reserved.
//
import UIKit
class Cast: HorizontalListModule {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| apache-2.0 |
WebAPIKit/WebAPIKit | Tests/WebAPIKitTests/Stub/StubResponder+PathTemplateSpec.swift | 1 | 3092 | /**
* WebAPIKit
*
* Copyright (c) 2017 Evan Liu. Licensed under the MIT license, as follows:
*
* 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 Alamofire
import Quick
import Nimble
import WebAPIKit
class StubResponderPathTemplateSpec: QuickSpec {
override func spec() {
let provider = StubProvider()
var client: StubHTTPClient!
beforeEach {
client = StubHTTPClient(provider: provider)
}
it("match path template") {
let stub = client.stub(template: "/users/{id}")
expect(stub.match(provider.request(path: "/users/1"))) == true
expect(stub.match(provider.request(path: "/users"))) == false
expect(stub.match(provider.request(path: "/repos/1"))) == false
let postStub = client.stub(template: "/users/{id}", method: .post)
expect(postStub.match(provider.request(path: "/users/1"))) == false
expect(postStub.match(provider.request(path: "/users/1", method: .put))) == false
expect(postStub.match(provider.request(path: "/users/1", method: .post))) == true
}
it("respond with path template variables") {
var result: [String: String]?
client.stub(template: "/users/{id}").withTemplatedJSON { ["userID": $0["id"] ?? ""] }
client.send(provider.request(path: "/users/1"), queue: nil) { data, _, _ in
if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) {
result = json as? [String: String]
}
}
expect(result?["userID"]) == "1"
}
}
}
private final class StubProvider: WebAPIProvider {
let baseURL = URL(string: "http://test.stub/api/v1")!
func request(path: String, method: HTTPMethod = .get) -> URLRequest {
let url = baseURL.appendingPathComponent(path)
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
return request
}
}
| mit |
silence0201/Swift-Study | SwiftLearn/MySwift19_Type_casting.playground/Contents.swift | 1 | 5060 | //: Playground - noun: a place where people can play
import UIKit
//Swift运行时的类型检查 is, 类与类之间的类型转换 as.
class MediaItem{
var name: String
init(name: String){
self.name = name
}
}
class Movie: MediaItem{
var genre: String //类型
init(name: String, genre: String){
self.genre = genre
super.init(name: name)
}
}
class Music: MediaItem{
var artist: String //演唱者
init(name: String, artistName: String){
self.artist = artistName
super.init(name: name)
}
}
class Game: MediaItem{
var developer: String //开发者
init(name: String, developer: String){
self.developer = developer
super.init(name: name)
}
}
let library: [MediaItem] = [
Movie(name: "Zootopia", genre: "Animation"),
Music(name: "Hello", artistName: "Adele"),
Game(name: "LIMBO", developer: "Playdead"),
Music(name: "See you agian", artistName: "Wiz Khalifa"),
Game(name: "The Bridge", developer: "The Quantum Astrophysicists Guild")
]
//类型检查 关键字 is
var musicCount = 0
var movieCount = 0
var gameCount = 0
for mediaItem in library{
if mediaItem is Movie{
movieCount += 1
}
else if mediaItem is Music{
musicCount += 1
}
else if mediaItem is Game{
gameCount += 1
}
}
//类型转换 关键字 as
let item0 = library[0] as? Movie //Movie? 尝试进行类型转换
let item00 = library[0] as? Music //nil
let item000 = library[0] as! Movie //已经确认是Movie类型.
//let item0000 = library[0] as! Music //如果确认失败, 会产生重大错误, 程序中止.
for mediaItem in library{
if let movie = mediaItem as? Movie{ //尝试进行类型转换并解包使用
print("Movie:", movie.name, "Genre:", movie.genre)
}
else if let music = mediaItem as? Music{
print("Music:", music.name, "Artist:", music.artist)
}
else if let game = mediaItem as? Game{
print("Game:", game.name, "Developer(s):", game.developer)
}
}
//类型判断 在协议中的应用 判断类型是否遵守了协议
protocol Shape{ //图形
var name: String{get}
}
protocol HasArea{ //面积
func area() -> Double
}
struct Point: Shape{
let name: String = "point"
var x: Double
var y: Double
}
struct Rectangle: Shape, HasArea{
let name: String = "rectangle"
var origin: Point
var width: Double
var height: Double
func area() -> Double{
return width * height
}
}
struct Circle: Shape, HasArea{
let name = "circle"
var center: Point
var radius: Double
func area() -> Double{
return M_PI * radius * radius
}
}
struct Line: Shape{
let name = "line"
var a: Point
var b: Point
}
let shapes:[Shape] = [
Rectangle(origin: Point(x:0.0,y:0.0), width: 3.0, height: 4.0),
Point(x: 0.0, y: 0.0),
Circle(center: Point(x:0.0,y:0.0), radius: 1.0),
Line(a: Point(x:1.0,y:1.0), b: Point(x:5.0,y:5.0))
]
for shape in shapes{
if shape is HasArea{
print("\(shape.name) has area.")
}
else{
print("\(shape.name) has no area.")
}
}
print("==========")
for shape in shapes{
if let areaShape = shape as? HasArea{
print("The area of \(shape.name) is \(areaShape.area()).")
}
else{
print("\(shape.name) has no area.")
}
}
//NSObject, AnyObject, Any
class Person{
var name: String
init(name: String){
self.name = name
}
}
var objects1 = [
CGFloat(3.1415926),
"imooc",
UIColor.blue,
NSDate(),
Int(32),
Array<Int>([1,2,3])
] as [Any]
// a1 为NSObject
let a1 = objects1[0]
var objects2 = [
CGFloat(3.1415926),
"imooc",
UIColor.blue,
NSDate(),
Int(32),
Array<Int>([1,2,3]),
Person(name: "liuyubobobo")
] as [Any]
// a2 为AnyObject
let a2 = objects2[0]
//AnyObject比NSObject还要高一层
//NSObject是OC语言中所有类的父类. AnyObject脱离了面向对象中继承树这个概念,
//任何的一个对象, 任何的一个Object都可以表述成AnyObject.
//实际上在底层AnyObject和OC语言中的ID概念是对应的.
//(简单来说ID就相当于C/C++中void * 相对应, 就相当于一个指针, 这个指针没有类型, 指向了这片内存空间.
//只要这个内存空间存的是一个对象, 我们就说这是一个AnyObject.
var objects3: [Any] = [
CGFloat(3.1415926),
"imooc",
UIColor.blue,
NSDate(),
Int(32),
Array<Int>([1,2,3]),
Person(name: "liuyubobobo")
]
//发生error, 因为函数不是一个AnyObject.
//objects3.append( {(a:Int) -> Int in
// return a*a
//})
var objects4: [Any] = [
CGFloat(3.1415926),
"imooc",
UIColor.blue,
NSDate(),
Int(32),
Array<Int>([1,2,3]),
Person(name: "liuyubobobo")
]
//没有错误, Any比AnyObject的范围还要广, Any不仅可以包含任何的对象, 还可以包含函数这样的逻辑.
objects4.append( { (a:Int) -> Int in
return a*a} )
| mit |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Base/Vender/XLPagerTabStrip/SwipeDirection.swift | 3 | 1327 | // SwipeDirection.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public enum SwipeDirection {
case left
case right
case none
}
| mit |
ctarda/Turnstile | Sources/TurnstileTests/StateTests.swift | 1 | 2223 | //
// StateTests.swift
// Turnstile
//
// Created by Cesar Tardaguila on 09/05/15.
//
import XCTest
import Turnstile
class StateTests: XCTestCase {
private struct Constants {
static let stateValue = "State under testing"
static let stringDiff = "💩"
}
var state: State<String>?
override func setUp() {
super.setUp()
state = State(value: Constants.stateValue)
}
override func tearDown() {
state = nil
super.tearDown()
}
func testStateIsCreated() {
XCTAssertNotNil(state, "State must not be nil")
}
func testStateValueIsSet() {
XCTAssertEqual(state!.value, Constants.stateValue, "value must be set properly")
}
func testStateWillEnterStateCanBeSet() {
var result = false
state!.willEnterState = { state in result = true }
state!.willEnterState?(state!)
XCTAssertTrue(result, "willEnterState must be set")
}
func testStateDidEnterStateCanBeSet() {
var result = false
state!.didEnterState = { state in result = true }
state!.didEnterState?(state!)
XCTAssertTrue(result, "didEnterState must be set")
}
func testStateWillExitStateCanBeSet() {
var result = false
state!.willExitState = { state in result = true }
state!.willExitState?(state!)
XCTAssertTrue(result, "willExitState must be set")
}
func testStateDidExitStateCanBeSet() {
var result = false
state!.didExitState = { state in result = true }
state!.didExitState?(state!)
XCTAssertTrue(result, "willExitState must be set")
}
func testStatesWithSameValueAreEqual() {
let secondState = State(value: Constants.stateValue)
XCTAssertTrue(state == secondState, "State with same value are equal")
}
func testStatesWithDifferentValueAreDifferent() {
let secondState = State(value: Constants.stateValue + Constants.stringDiff)
XCTAssertFalse(state == secondState, "State with differnet value are different")
}
}
| mit |
teanet/Nazabore | Nazabore/Models/Container.swift | 1 | 486 | @objc public class Container: NSObject {
@objc public lazy var rootVC: UINavigationController = {
let vc = NZBMapVC(router: self.router, markerFetcher: self.markerFetcher)
return UINavigationController(rootViewController: vc)
}()
lazy var api = APIService()
lazy var markerFetcher: MarkerFetcher = { [unowned self] in
return MarkerFetcher(service: self.api, router: self.router)
}()
lazy var router: Router = { [unowned self] in
return Router(container: self)
}()
}
| mit |
piemonte/Blurry | Blurry/AppDelegate.swift | 1 | 2212 | //
// AppDelegate.swift
// Blurry
//
// Copyright (c) 2016-present patrick piemonte (http://patrickpiemonte.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
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
// MARK: - UIApplicationDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame:UIScreen.main.bounds)
self.window!.backgroundColor = UIColor.black
let viewController = ViewController()
self.window!.rootViewController = viewController
self.window!.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/27698-swift-parser-parseexprimpl.swift | 4 | 267 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{class B<T where h:b{enum a{struct Q{class A{struct Q{let a=A{struct c{struct c{var e{let:{var:{l
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/14791-swift-sourcemanager-getmessage.swift | 11 | 239 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a {
end as S (
[ {
if true {
protocol A {
struct A {
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/26263-swift-protocoltype-canonicalizeprotocols.swift | 7 | 225 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class b<T where B:P{struct Q<h{var d{}struct A
let a=A{
| mit |
wangchao1992/Imitate-BiliBili | ImitateBilibili/ImitateBilibili/Classes/Main/TuiJian/View/RecommendCellDetail.swift | 1 | 1155 | //
// RecommendCellDetail.swift
// ImitateBilibili
//
// Created by xiaochao on 2016/11/14.
// Copyright © 2016年 godchao. All rights reserved.
//
import UIKit
import SDWebImage
class RecommendCellDetail: UIView {
@IBOutlet weak var coverImage: UIImageView!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var playCount: UILabel!
@IBOutlet weak var danmuku: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var dataModel:RecommendModel?{
didSet{
setData()
}
}
// MARK: - 设置数据
func setData(){
self.coverImage.sd_setImage(with: URL(string: (self.dataModel?.cover)!))
self.title.text = self.dataModel?.title
self.playCount.text = self.dataModel?.play
self.danmuku.text = self.dataModel?.danmaku
}
static func cellWithNib()->RecommendCellDetail{
return UINib.init(nibName: "RecommendCellDetail", bundle: nil).instantiate(withOwner: nil, options: nil).last as! RecommendCellDetail
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/27198-swift-substitutedtype-get.swift | 4 | 257 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class S<T{func a<h{func b<T where h.g=a{}}}struct c{struct S<b{class A{struct c{class a
| mit |
MaartenBrijker/project | project/External/AudioKit-master/AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Distortion.xcplaygroundpage/Contents.swift | 2 | 5422 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Distortion
//: ### This thing is a beast.
//:
import XCPlayground
import AudioKit
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("mixloop", ofType: "wav")
var player = AKAudioPlayer(file!)
player.looping = true
var distortion = AKDistortion(player)
//: Set the parameters here
distortion.delay = 0.1
distortion.decay = 1.0
distortion.delayMix = 0.5
distortion.linearTerm = 0.5
distortion.squaredTerm = 0.5
distortion.cubicTerm = 50
distortion.polynomialMix = 0.5
distortion.softClipGain = -6
distortion.finalMix = 0.5
AudioKit.output = distortion
AudioKit.start()
//: User Interface Set up
class PlaygroundView: AKPlaygroundView {
//: UI Elements we'll need to be able to access
var delayLabel: Label?
var decayLabel: Label?
var delayMixLabel: Label?
var linearTermLabel: Label?
var squaredTermLabel: Label?
var cubicTermLabel: Label?
var polynomialMixLabel: Label?
var softClipGainLabel: Label?
var finalMixLabel: Label?
override func setup() {
addTitle("Distortion")
addLabel("Audio Player")
addButton("Start", action: #selector(start))
addButton("Stop", action: #selector(stop))
addLabel("Distortion Parameters")
addButton("Process", action: #selector(process))
addButton("Bypass", action: #selector(bypass))
delayLabel = addLabel("Delay: \(distortion.delay) Milliseconds")
addSlider(#selector(setDelay), value: distortion.delay, minimum: 0.1, maximum: 500)
decayLabel = addLabel("Decay: \(distortion.decay) Rate")
addSlider(#selector(setDecay), value: distortion.decay, minimum: 0.1, maximum: 50)
delayMixLabel = addLabel("Delay Mix: \(distortion.delayMix)")
addSlider(#selector(setDelayMix), value: distortion.delayMix)
linearTermLabel = addLabel("Linear Term: \(distortion.linearTerm)")
addSlider(#selector(setLinearTerm), value: distortion.linearTerm)
squaredTermLabel = addLabel("Squared Term: \(distortion.squaredTerm)")
addSlider(#selector(setSquaredTerm), value: distortion.squaredTerm)
cubicTermLabel = addLabel("Cubic Term: \(distortion.cubicTerm)")
addSlider(#selector(setCubicTerm), value: distortion.cubicTerm)
polynomialMixLabel = addLabel("Polynomial Mix: \(distortion.polynomialMix)")
addSlider(#selector(setPolynomialMix), value: distortion.polynomialMix)
softClipGainLabel = addLabel("Soft Clip Gain: \(distortion.softClipGain) dB")
addSlider(#selector(setSoftClipGain), value: distortion.softClipGain, minimum: -80, maximum: 20)
finalMixLabel = addLabel("Final Mix: \(distortion.finalMix)")
addSlider(#selector(setFinalMix), value: distortion.finalMix)
}
//: Handle UI Events
func start() {
player.play()
}
func stop() {
player.stop()
}
func process() {
distortion.start()
}
func bypass() {
distortion.bypass()
}
func setDelay(slider: Slider) {
distortion.delay = Double(slider.value)
let delay = String(format: "%0.3f", distortion.delay)
delayLabel!.text = "Delay: \(delay) Milliseconds"
}
func setDecay(slider: Slider) {
distortion.decay = Double(slider.value)
let decay = String(format: "%0.3f", distortion.decay)
decayLabel!.text = "Decay: \(decay) Rate"
}
func setDelayMix(slider: Slider) {
distortion.delayMix = Double(slider.value)
let delayMix = String(format: "%0.3f", distortion.delayMix)
delayMixLabel!.text = "Delay Mix: \(delayMix)"
}
func setLinearTerm(slider: Slider) {
distortion.linearTerm = Double(slider.value)
let linearTerm = String(format: "%0.3f", distortion.linearTerm)
linearTermLabel!.text = "linearTerm: \(linearTerm)"
}
func setSquaredTerm(slider: Slider) {
distortion.squaredTerm = Double(slider.value)
let squaredTerm = String(format: "%0.3f", distortion.squaredTerm)
squaredTermLabel!.text = "squaredTerm: \(squaredTerm)"
}
func setCubicTerm(slider: Slider) {
distortion.cubicTerm = Double(slider.value)
let cubicTerm = String(format: "%0.3f", distortion.cubicTerm)
cubicTermLabel!.text = "cubicTerm: \(cubicTerm)"
}
func setPolynomialMix(slider: Slider) {
distortion.polynomialMix = Double(slider.value)
let polynomialMix = String(format: "%0.3f", distortion.polynomialMix)
polynomialMixLabel!.text = "polynomialMix: \(polynomialMix)"
}
func setSoftClipGain(slider: Slider) {
distortion.softClipGain = Double(slider.value)
let softClipGain = String(format: "%0.3f", distortion.softClipGain)
softClipGainLabel!.text = "softClipGain: \(softClipGain) dB"
}
func setFinalMix(slider: Slider) {
distortion.finalMix = Double(slider.value)
let finalMix = String(format: "%0.3f", distortion.finalMix)
finalMixLabel!.text = "finalMix: \(finalMix)"
}
}
let view = PlaygroundView(frame: CGRect(x: 0, y: 0, width: 500, height: 1000))
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = view
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| apache-2.0 |
jsslai/Action | Carthage/Checkouts/RxSwift/Rx.playground/Pages/Filtering_and_Conditional_Operators.xcplaygroundpage/Contents.swift | 3 | 8119 | /*:
> # IMPORTANT: To use **Rx.playground**:
1. Open **Rx.xcworkspace**.
1. Build the **RxSwift-OSX** scheme (**Product** → **Build**).
1. Open **Rx** playground in the **Project navigator**.
1. Show the Debug Area (**View** → **Debug Area** → **Show Debug Area**).
----
[Previous](@previous) - [Table of Contents](Table_of_Contents)
*/
import RxSwift
/*:
# Filtering and Conditional Operators
Operators that selectively emit elements from a source `Observable` sequence.
## `filter`
Emits only those elements from an `Observable` sequence that meet the specified condition. [More info](http://reactivex.io/documentation/operators/filter.html)

*/
example("filter") {
let disposeBag = DisposeBag()
Observable.of(
"🐱", "🐰", "🐶",
"🐸", "🐱", "🐰",
"🐹", "🐸", "🐱")
.filter {
$0 == "🐱"
}
.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
}
/*:
----
## `distinctUntilChanged`
Suppresses sequential duplicate elements emitted by an `Observable` sequence. [More info](http://reactivex.io/documentation/operators/distinct.html)

*/
example("distinctUntilChanged") {
let disposeBag = DisposeBag()
Observable.of("🐱", "🐷", "🐱", "🐱", "🐱", "🐵", "🐱")
.distinctUntilChanged()
.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
}
/*:
----
## `elementAt`
Emits only the element at the specified index of all elements emitted by an `Observable` sequence. [More info](http://reactivex.io/documentation/operators/elementat.html)

*/
example("elementAt") {
let disposeBag = DisposeBag()
Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵")
.elementAt(3)
.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
}
/*:
----
## `single`
Emits only the first element (or the first element that meets a condition) emitted by an `Observable` sequence. Will throw an error if the `Observable` sequence does not emit exactly one element.
*/
example("single") {
let disposeBag = DisposeBag()
Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵")
.single()
.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
}
example("single with conditions") {
let disposeBag = DisposeBag()
Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵")
.single { $0 == "🐸" }
.subscribe { print($0) }
.addDisposableTo(disposeBag)
Observable.of("🐱", "🐰", "🐶", "🐱", "🐰", "🐶")
.single { $0 == "🐰" }
.subscribe { print($0) }
.addDisposableTo(disposeBag)
Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵")
.single { $0 == "🔵" }
.subscribe { print($0) }
.addDisposableTo(disposeBag)
}
/*:
----
## `take`
Emits only the specified number of elements from the beginning of an `Observable` sequence. [More info](http://reactivex.io/documentation/operators/take.html)

*/
example("take") {
let disposeBag = DisposeBag()
Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵")
.take(3)
.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
}
/*:
----
## `takeLast`
Emits only the specified number of elements from the end of an `Observable` sequence. [More info](http://reactivex.io/documentation/operators/takelast.html)

*/
example("takeLast") {
let disposeBag = DisposeBag()
Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵")
.takeLast(3)
.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
}
/*:
----
## `takeWhile`
Emits elements from the beginning of an `Observable` sequence as long as the specified condition evaluates to `true`. [More info](http://reactivex.io/documentation/operators/takewhile.html)

*/
example("takeWhile") {
let disposeBag = DisposeBag()
Observable.of(1, 2, 3, 4, 5, 6)
.takeWhile { $0 < 4 }
.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
}
/*:
----
## `takeUntil`
Emits elements from a source `Observable` sequence until a reference `Observable` sequence emits an element. [More info](http://reactivex.io/documentation/operators/takeuntil.html)

*/
example("takeUntil") {
let disposeBag = DisposeBag()
let sourceSequence = PublishSubject<String>()
let referenceSequence = PublishSubject<String>()
sourceSequence
.takeUntil(referenceSequence)
.subscribe { print($0) }
.addDisposableTo(disposeBag)
sourceSequence.onNext("🐱")
sourceSequence.onNext("🐰")
sourceSequence.onNext("🐶")
referenceSequence.onNext("🔴")
sourceSequence.onNext("🐸")
sourceSequence.onNext("🐷")
sourceSequence.onNext("🐵")
}
/*:
----
## `skip`
Suppresses emitting the specified number of elements from the beginning of an `Observable` sequence. [More info](http://reactivex.io/documentation/operators/skip.html)

*/
example("skip") {
let disposeBag = DisposeBag()
Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵")
.skip(2)
.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
}
/*:
----
## `skipWhile`
Suppresses emitting the elements from the beginning of an `Observable` sequence that meet the specified condition. [More info](http://reactivex.io/documentation/operators/skipwhile.html)

*/
example("skipWhile") {
let disposeBag = DisposeBag()
Observable.of(1, 2, 3, 4, 5, 6)
.skipWhile { $0 < 4 }
.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
}
/*:
----
## `skipWhileWithIndex`
Suppresses emitting the elements from the beginning of an `Observable` sequence that meet the specified condition, and emits the remaining elements. The closure is also passed each element's index.
*/
example("skipWhileWithIndex") {
let disposeBag = DisposeBag()
Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵")
.skipWhileWithIndex { element, index in
index < 3
}
.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
}
/*:
----
## `skipUntil`
Suppresses emitting the elements from a source `Observable` sequence until a reference `Observable` sequence emits an element. [More info](http://reactivex.io/documentation/operators/skipuntil.html)

*/
example("skipUntil") {
let disposeBag = DisposeBag()
let sourceSequence = PublishSubject<String>()
let referenceSequence = PublishSubject<String>()
sourceSequence
.skipUntil(referenceSequence)
.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
sourceSequence.onNext("🐱")
sourceSequence.onNext("🐰")
sourceSequence.onNext("🐶")
referenceSequence.onNext("🔴")
sourceSequence.onNext("🐸")
sourceSequence.onNext("🐷")
sourceSequence.onNext("🐵")
}
//: [Next](@next) - [Table of Contents](Table_of_Contents)
| mit |
michalciurus/KatanaRouter | Pods/Katana/Katana/iOS/Typealiases.swift | 1 | 250 | //
// Typealiases.swift
// Katana
//
// Copyright © 2016 Bending Spoons.
// Distributed under the MIT License.
// See the LICENSE file for more information.
public typealias DefaultView = UIView
public typealias FloatEdgeInsets = UIEdgeInsets
| mit |
lauracpierre/FA_ReveaMenu | FA_RevealMenuTests/FA_RevealMenuTests.swift | 1 | 917 | //
// FA_RevealMenuTests.swift
// FA_RevealMenuTests
//
// Created by Pierre LAURAC on 09/05/2015.
// Copyright (c) 2015 Front. All rights reserved.
//
import UIKit
import XCTest
class FA_RevealMenuTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
ben-ng/swift | validation-test/compiler_crashers_fixed/26624-swift-typebase-getcanonicaltype.swift | 1 | 487 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
import c
struct Q<b{class d:b class B:d{class A{
}
let a
enum S{
var f:A{{
{}}}
func a<a
| apache-2.0 |
TakahiroTsuchiya/SampleFirebase | SampleFirebase/AppDelegate.swift | 1 | 2256 | //
// AppDelegate.swift
// SampleFirebase
//
// Created by Takahiro Tsuchiya on 5/28/16.
// Copyright © 2016 Takahiro Tsuchiya. All rights reserved.
//
import Firebase
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
// Use Firebase library to configure APIs
FIRApp.configure()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 |
cnoon/swift-compiler-crashes | fixed/01784-swift-constraints-constraintgraph-lookupnode.swift | 11 | 203 | // 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 c<b{class A
class B:A{let a=b | mit |
cnoon/swift-compiler-crashes | fixed/23619-swift-typechecker-typecheckexpression.swift | 11 | 2391 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
}
}}}
let f = j
}
println( 1 )
func b
}
}extension String{
class B, leng
class A{
}enum S<T>
let end = [Void{
deinit {
}
i>: B<T where B {
let f = F>: e>: B<T where T
}
class
typealias e : A<T where B : e
struct A {
typealias e : B<T where B : B
case ,
}class B : d
typealias e : a {
let end = [Void{
typealias e : a {{
protocol a {
}
let a {}
func e
var d where B : T>: A}
class B? {
case c<d<T.e = Int
typealias e : d<T where k.E
}}}
{
func f:a {
var d typealias F>: b {}}
}protocol b<T where k.h
pr
class B, leng
case c:A{
}
println( 1 )
func b<T>: e
}class b{
typealias
protocol B {
let end = F>: b {}
"
case c:a {
var d = j
}
func b<T where B : e
pr
typealias
let a
func b:T> ()
class B
let a {
struct c {
struct A{
}protocol A {
class B, leng
func g a<T where B : a {
}
func c:d<T where g:A{
}}enum A
let end = B
var b {
case ,
deinit {
class
class A {
class
}protocol a {
protocol B : d
let f = [[Void{
case c,
}
protocol A {
func b
class
}class A
class func b
class B, leng
"
{
case c
class
}}
class B:[Void{}extension NSSet{
let end = a
struct S<Int>()
class
case c{
typealias f = Int
typealias F>(v: A {
case ,
var b {
class A:f:T.a{
class b:d<d typealias E
class
class A<T where k.b where I.e : C {
}
func e
}
func g<T>: T? {
}
}typealias A{
struct A {
func f: b = [ {
}}
case c<f: (v: B<T> ()
class A {
class A<Int>: a :BooleanType
case c
{case=0.a
class
case c:f: b}
class A {{func e.b {
{var b {
case c,
}
func e.b {
class
extension String{
class B, leng
struct A {
}
protocol a {
func e.E =0.E
func a
func b<T> Bool {
deinit {
let h
{
}typealias e = a<T>:b
func e?)
protocol a<f: b {{
}class B, leng
protocol C {
}
typealias A{{
case c,
}}protocol a<T{
}}class d
}
let i: b { func b
}extension String{
{
protocol a {
let a {
protocol C {
func b<d<d where a {
func b
0.E
struct c {{
let a {
}typealias e : B? {
typealias F = [ {
{
class
let f = j
func e?)
{func f{a
{
let end = j
protocol A {
class
0.h
class A {
import Foundation
}
return nil
import a
{
typealias e : B<T where g:a {
deinit {
""
let f : b where T>: e : e
class A{
}
struct A {
{
protocol b:T> (v: A {
}
var b {
protocol a {var b {func a<d where T>(v: a :a {
enum S<T>) -> T.E
}class B<d where T
{
deinit {
let f = [ {
protocol B {
struct A
| mit |
CanBeMyQueen/DouYuZB | DouYu/DouYu/Classes/Main/View/BaseCollectionViewCell.swift | 1 | 873 | //
// BaseCollectionViewCell.swift
// DouYu
//
// Created by 张萌 on 2017/10/16.
// Copyright © 2017年 JiaYin. All rights reserved.
//
import UIKit
class BaseCollectionViewCell: UICollectionViewCell {
/// 属性设置
@IBOutlet weak var nickNameLabel: UILabel!
@IBOutlet weak var roomNameLabel: UILabel!
@IBOutlet weak var onlineNumberBtn: UIButton!
var anchorRoom : AnchorRoomModel? {
didSet {
self.nickNameLabel.text = anchorRoom?.nickname
self.roomNameLabel.text = anchorRoom?.room_name
guard let online = anchorRoom?.online else {return}
if online >= 10000 {
self.onlineNumberBtn .setTitle("\(online/10000)万在线", for: .normal)
} else {
self.onlineNumberBtn .setTitle("\(online)在线", for: .normal)
}
}
}
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/03128-swift-sourcemanager-getmessage.swift | 11 | 432 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct B<T>(v: T where g<T where S<T {
enum S.e : j { func a(")
if true {
protocol a(v: A? {
[k<T.e = ")
var e(v: d = compose(Any) {
protocol h : j { func a
class c : a {
struct B<T where g: AnyObject) {
func a(v: d where g: AnyObject) {
class
case c,
protocol A
| mit |
kripple/bti-watson | ios-app/Carthage/Checkouts/ios-sdk/WatsonDeveloperCloudTests/WatsonDeveloperCloudTests.swift | 1 | 1453 | /**
* Copyright IBM Corporation 2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import XCTest
@testable import WatsonDeveloperCloud
class WatsonDeveloperCloudTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| mit |
exponent/exponent | ios/vendored/sdk43/@stripe/stripe-react-native/ios/CardFormView.swift | 2 | 3223 | import Foundation
import UIKit
import Stripe
class CardFormView: UIView, STPCardFormViewDelegate {
public var cardForm: STPCardFormView?
public var cardParams: STPPaymentMethodCardParams? = nil
@objc var dangerouslyGetFullCardDetails: Bool = false
@objc var onFormComplete: ABI43_0_0RCTDirectEventBlock?
@objc var autofocus: Bool = false
@objc var isUserInteractionEnabledValue: Bool = true
override func didSetProps(_ changedProps: [String]!) {
if let cardForm = self.cardForm {
cardForm.removeFromSuperview()
}
let style = self.cardStyle["type"] as? String == "borderless" ? STPCardFormViewStyle.borderless : STPCardFormViewStyle.standard
let _cardForm = STPCardFormView(style: style)
_cardForm.delegate = self
// _cardForm.isUserInteractionEnabled = isUserInteractionEnabledValue
if autofocus == true {
let _ = _cardForm.becomeFirstResponder()
}
self.cardForm = _cardForm
self.addSubview(_cardForm)
setStyles()
}
@objc var cardStyle: NSDictionary = NSDictionary() {
didSet {
setStyles()
}
}
func cardFormView(_ form: STPCardFormView, didChangeToStateComplete complete: Bool) {
if onFormComplete != nil {
let brand = STPCardValidator.brand(forNumber: cardForm?.cardParams?.card?.number ?? "")
var cardData: [String: Any?] = [
"expiryMonth": cardForm?.cardParams?.card?.expMonth ?? NSNull(),
"expiryYear": cardForm?.cardParams?.card?.expYear ?? NSNull(),
"complete": complete,
"brand": Mappers.mapCardBrand(brand) ?? NSNull(),
"last4": cardForm?.cardParams?.card?.last4 ?? "",
"postalCode": cardForm?.cardParams?.billingDetails?.address?.postalCode ?? "",
"country": cardForm?.cardParams?.billingDetails?.address?.country
]
if (dangerouslyGetFullCardDetails) {
cardData["number"] = cardForm?.cardParams?.card?.number ?? ""
}
if (complete) {
self.cardParams = cardForm?.cardParams?.card
} else {
self.cardParams = nil
}
onFormComplete!(cardData as [AnyHashable : Any])
}
}
func focus() {
let _ = cardForm?.becomeFirstResponder()
}
func blur() {
let _ = cardForm?.resignFirstResponder()
}
func setStyles() {
if let backgroundColor = cardStyle["backgroundColor"] as? String {
cardForm?.backgroundColor = UIColor(hexString: backgroundColor)
}
// if let disabledBackgroundColor = cardStyle["disabledBackgroundColor"] as? String {
// cardForm?.disabledBackgroundColor = UIColor(hexString: disabledBackgroundColor)
// }
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override func layoutSubviews() {
cardForm?.frame = self.bounds
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| bsd-3-clause |
ccrama/Slide-iOS | Slide for Reddit/Fonts/LinkParser.swift | 1 | 11108 | //
// LinkParser.swift
// Slide for Reddit
//
// Created by Carlos Crane on 1/28/17.
// Copyright © 2017 Haptic Apps. All rights reserved.
//
import DTCoreText
import UIKit
import YYText
class LinkParser {
public static func parse(_ attributedString: NSAttributedString, _ color: UIColor, font: UIFont, bold: UIFont? = nil, fontColor: UIColor, linksCallback: ((URL) -> Void)?, indexCallback: (() -> Int)?) -> NSMutableAttributedString {
var finalBold: UIFont
if bold == nil {
finalBold = font.makeBold()
} else {
finalBold = bold!
}
let string = NSMutableAttributedString.init(attributedString: attributedString)
string.removeAttribute(convertToNSAttributedStringKey(kCTForegroundColorFromContextAttributeName as String), range: NSRange.init(location: 0, length: string.length))
if string.length > 0 {
while string.string.contains("slide://") {
do {
let match = try NSRegularExpression(pattern: "(slide:\\/\\/[a-zA-Z%?#0-9]+)", options: []).matches(in: string.string, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range: NSRange(location: 0, length: string.length))[0]
let matchRange: NSRange = match.range(at: 1)
if matchRange.location != NSNotFound {
let attributedText = string.attributedSubstring(from: match.range).mutableCopy() as! NSMutableAttributedString
let oldAttrs = attributedText.attributes(at: 0, effectiveRange: nil)
print(attributedText.string)
let newAttrs = [ NSAttributedString.Key.link: URL(string: attributedText.string)!] as [NSAttributedString.Key: Any]
let allParams = newAttrs.reduce(into: oldAttrs) { (r, e) in r[e.0] = e.1 }
let newText = NSMutableAttributedString(string: "Slide Theme", attributes: allParams)
string.replaceCharacters(in: match.range, with: newText)
}
} catch {
}
}
string.enumerateAttributes(in: NSRange.init(location: 0, length: string.length), options: .longestEffectiveRangeNotRequired, using: { (attrs, range, _) in
for attr in attrs {
if let isColor = attr.value as? UIColor {
if isColor.hexString() == "#0000FF" {
string.setAttributes([NSAttributedString.Key.foregroundColor: color, NSAttributedString.Key.backgroundColor: ColorUtil.theme.backgroundColor.withAlphaComponent(0.5), NSAttributedString.Key.font: UIFont(name: "Courier", size: font.pointSize) ?? font], range: range)
} else if isColor.hexString() == "#008000" {
string.setAttributes([NSAttributedString.Key.foregroundColor: fontColor, NSAttributedString.Key(rawValue: YYTextStrikethroughAttributeName): YYTextDecoration(style: YYTextLineStyle.single, width: 1, color: fontColor), NSAttributedString.Key.font: font], range: range)
}
} else if let url = attr.value as? URL {
if SettingValues.enlargeLinks {
string.addAttribute(NSAttributedString.Key.font, value: FontGenerator.boldFontOfSize(size: 18, submission: false), range: range)
}
string.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
string.addAttribute(convertToNSAttributedStringKey(kCTUnderlineColorAttributeName as String), value: UIColor.clear, range: range)
let type = ContentType.getContentType(baseUrl: url)
if SettingValues.showLinkContentType {
let typeString = NSMutableAttributedString.init(string: "", attributes: convertToOptionalNSAttributedStringKeyDictionary([:]))
switch type {
case .ALBUM:
typeString.mutableString.setString("(Album)")
case .REDDIT_GALLERY:
typeString.mutableString.setString("(Gallery)")
case .TABLE:
typeString.mutableString.setString("(Table)")
case .EXTERNAL:
typeString.mutableString.setString("(External link)")
case .LINK, .EMBEDDED, .NONE:
if url.absoluteString != string.mutableString.substring(with: range) {
typeString.mutableString.setString("(\(url.host ?? url.absoluteString))")
}
case .DEVIANTART, .IMAGE, .TUMBLR, .XKCD:
typeString.mutableString.setString("(Image)")
case .GIF:
typeString.mutableString.setString("(GIF)")
case .IMGUR:
typeString.mutableString.setString("(Imgur)")
case .VIDEO, .STREAMABLE, .VID_ME:
typeString.mutableString.setString("(Video)")
case .REDDIT:
typeString.mutableString.setString("(Reddit link)")
case .SPOILER:
typeString.mutableString.setString("")
default:
if url.absoluteString != string.mutableString.substring(with: range) {
typeString.mutableString.setString("(\(url.host!))")
}
}
string.insert(typeString, at: range.location + range.length)
string.addAttributes(convertToNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font): FontGenerator.boldFontOfSize(size: 12, submission: false), convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): ColorUtil.theme.fontColor]), range: NSRange.init(location: range.location + range.length, length: typeString.length))
}
if type != .SPOILER {
linksCallback?(url)
if let value = indexCallback?(), !SettingValues.disablePreviews {
let positionString = NSMutableAttributedString.init(string: " †\(value)", attributes: [NSAttributedString.Key.foregroundColor: fontColor, NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 10)])
string.insert(positionString, at: range.location + range.length)
}
}
string.yy_setTextHighlight(range, color: color, backgroundColor: nil, userInfo: ["url": url])
break
}
}
})
string.beginEditing()
string.enumerateAttribute(
.font,
in: NSRange(location: 0, length: string.length)
) { (value, range, _) in
if let f = value as? UIFont {
let isItalic = f.fontDescriptor.symbolicTraits.contains(UIFontDescriptor.SymbolicTraits.traitItalic)
let isBold = f.fontDescriptor.symbolicTraits.contains(UIFontDescriptor.SymbolicTraits.traitBold)
var newFont = UIFont(descriptor: font.fontDescriptor, size: f.pointSize)
if isBold {
newFont = UIFont(descriptor: finalBold.fontDescriptor, size: f.pointSize)
}
string.removeAttribute(.font, range: range)
if isItalic {
string.addAttributes([.font: newFont, convertToNSAttributedStringKey(YYTextGlyphTransformAttributeName): CGAffineTransform(a: 1, b: tan(0.degreesToRadians), c: tan(15.degreesToRadians), d: 1, tx: 0, ty: 0)], range: range)
string.yy_setColor(fontColor, range: range)
} else {
string.addAttribute(.font, value: newFont, range: range)
}
}
}
string.endEditing()
string.highlightTarget(color: color)
}
return string
}
}
// Used from https://gist.github.com/aquajach/4d9398b95a748fd37e88
extension NSMutableAttributedString {
func highlightTarget(color: UIColor) {
let regPattern = "\\[\\[s\\[(.*?)\\]s\\]\\]"
if let regex = try? NSRegularExpression(pattern: regPattern, options: []) {
let matchesArray = regex.matches(in: self.string, options: [], range: NSRange(location: 0, length: self.string.length))
for match in matchesArray.reversed() {
let copy = self.attributedSubstring(from: match.range)
let text = copy.string
let attributedText = NSMutableAttributedString(string: text.replacingOccurrences(of: "[[s[", with: "").replacingOccurrences(of: "]s]]", with: ""), attributes: copy.attributes(at: 0, effectiveRange: nil))
attributedText.yy_textBackgroundBorder = YYTextBorder(fill: color, cornerRadius: 3)
attributedText.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: NSRange(location: 0, length: attributedText.length))
let highlight = YYTextHighlight()
highlight.userInfo = ["spoiler": true]
attributedText.yy_setTextHighlight(highlight, range: NSRange(location: 0, length: attributedText.length))
self.replaceCharacters(in: match.range, with: attributedText)
}
}
}
}
// Helper function inserted by Swift 4.2 migrator.
private func convertToNSAttributedStringKey(_ input: String) -> NSAttributedString.Key {
return NSAttributedString.Key(rawValue: input)
}
// Helper function inserted by Swift 4.2 migrator.
private func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
guard let input = input else { return nil }
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value) })
}
// Helper function inserted by Swift 4.2 migrator.
private func convertToNSAttributedStringKeyDictionary(_ input: [String: Any]) -> [NSAttributedString.Key: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value) })
}
// Helper function inserted by Swift 4.2 migrator.
private func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String {
return input.rawValue
}
| apache-2.0 |
gewill/Feeyue | Feeyue/Helpers/ModelHelper.swift | 1 | 2783 |
//
// ModelHelper.swift
// Feeyue
//
// Created by Will on 2018/7/16.
// Copyright © 2018 Will. All rights reserved.
//
import Foundation
import SwiftyJSON
import Kanna
struct DateHelper {
static func convert(_ json: JSON) -> Date {
return DateHelper.dateFormatter.date(from: json.stringValue) ?? Date.distantPast
}
static let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE MMM d HH:mm:ss Z yyyy"
dateFormatter.locale = Locale(identifier: "en_US")
return dateFormatter
}()
}
struct SourceHelper {
static func convert(_ json: JSON) -> String {
var sourceString = json.stringValue
if let doc = try? HTML(html: sourceString, encoding: .utf8) {
sourceString = doc.body?.text ?? ""
}
return sourceString
}
}
extension String {
var small: String {
return self + ":small"
}
var large: String {
return self + ":large"
}
var medium: String {
return self + ":medium"
}
func twitterSubstring(startIndex: Int, endIndex: Int) -> String {
guard let start = self.precomposedStringWithCanonicalMapping.unicodeScalars.index(self.startIndex, offsetBy: startIndex, limitedBy: self.endIndex) else { return "" }
guard let end = self.precomposedStringWithCanonicalMapping.unicodeScalars.index(self.startIndex, offsetBy: endIndex, limitedBy: self.endIndex) else { return "" }
return String(self.precomposedStringWithCanonicalMapping.unicodeScalars[start..<end])
}
/// Twitter sub string by given indices: [Int, Int].
/// Twitter JSON is encoded using UTF-8 characters.
/// https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/intro-to-tweet-json
/// https://developer.twitter.com/en/docs/basics/counting-characterse
func twitterSubstring(range: [Int]) -> String {
guard range.count == 2 else { return "" }
return self.twitterSubstring(startIndex: range[0], endIndex: range[1])
}
func replace(range: [Int], with string: String) -> String {
guard range.count == 2 else { return "" }
let startIndex = range[0]
let endIndex = range[1]
guard let start = self.precomposedStringWithCanonicalMapping.unicodeScalars.index(self.startIndex, offsetBy: startIndex, limitedBy: self.endIndex) else { return "" }
guard let end = self.precomposedStringWithCanonicalMapping.unicodeScalars.index(self.startIndex, offsetBy: endIndex, limitedBy: self.endIndex) else { return "" }
var text = self.precomposedStringWithCanonicalMapping.unicodeScalars
text.replaceSubrange(start..<end, with: string.unicodeScalars)
return String(text)
}
}
| mit |
tlax/looper | looper/Model/Camera/More/MCameraMoreItemInfo.swift | 1 | 452 | import UIKit
class MCameraMoreItemInfo:MCameraMoreItem
{
let attributedString:NSAttributedString
private let kCellHeight:CGFloat = 40
init(attributedString:NSAttributedString)
{
self.attributedString = attributedString
let reusableIdentifier:String = VCameraMoreCellInfo.reusableIdentifier
super.init(
reusableIdentifier:reusableIdentifier,
cellHeight:kCellHeight)
}
}
| mit |
arbitur/Func | source/Decoding/Decodable.swift | 1 | 5434 | //
// FuncJSON.swift
// Pods
//
// Created by Philip Fryklund on 27/Jul/17.
//
//
import Foundation
// MARK: - Protocols
public typealias Codable = Decodable & Encodable
public protocol Decodable {
init(json: Dict) throws
}
public protocol Encodable {
func encoded() -> Dict
}
// MARK: - Parse functions
private func getParse <T> (_ json: Dict, key: String) throws -> T {
guard let value: Any = json.valueFor(path: key) else {
throw DecodingError.missingKey(key: key)
}
guard let parsed = value as? T else {
throw DecodingError.parseFailed(key: key, value: value, valueType: T.self)
}
return parsed
}
// MARK: - Private decode function
private func decode <T> (_ json: Dict, _ key: String) throws -> T {
return try getParse(json, key: key)
}
//private func decode <T> (_ json: Dict, _ key: String) throws -> [T] {
// return try getParse(json, key: key)
//}
private func decode <T> (_ json: Dict, _ key: String) throws -> T where T: Func.Decodable {
let dict: Dict = try getParse(json, key: key)
return try T(json: dict)
}
private func decode <T> (_ json: Dict, _ key: String) throws -> T where T: RangeReplaceableCollection, T.Element: Decodable {
let dicts: [Dict] = try getParse(json, key: key)
var arr: T = T()
for dict in dicts {
arr.append(try T.Element.init(json: dict))
}
return arr
}
private func decode <T> (_ json: Dict, _ key: String) throws -> T where T: RawRepresentable {
let raw: T.RawValue = try getParse(json, key: key)
guard let enumm = T(rawValue: raw) else {
throw DecodingError.parseFailed(key: key, value: raw, valueType: T.self)
}
return enumm
}
private func decode <T> (_ json: Dict, _ key: String) throws -> T where T: RangeReplaceableCollection, T.Element: RawRepresentable {
let raws: [T.Element.RawValue] = try getParse(json, key: key)
var arr: T = T()
for raw in raws {
guard let element = T.Element.init(rawValue: raw) else {
throw DecodingError.parseFailed(key: key, value: raw, valueType: T.Element.self)
}
arr.append(element)
}
return arr
}
private func decode(_ json: Dict, _ key: String) throws -> URL {
let str: String = try getParse(json, key: key)
guard let url: URL = URL(string: str) else {
throw DecodingError.parseFailed(key: key, value: str, valueType: URL.self)
}
return url
}
private func decode(_ json: Dict, _ key: String) throws -> [URL] {
let strs: [String] = try getParse(json, key: key)
return strs.compactMap(URL.init)
}
private func decode(_ json: Dict, _ key: String, format: DateFormat = .dateTime) throws -> Date {
let str: String = try getParse(json, key: key)
guard let date = Date.init(str, format: format) else {
throw DecodingError.dateFormat(key: key, value: str, format: format.rawValue)
}
return date
}
// MARK: - Public decode functions
public extension Dictionary where Key == String {
// Any
func decode <T> (_ key: String) throws -> T {
return try Func.decode(self, key)
}
// func decode <T> (_ key: String) throws -> T? {
// return try? self.decode(key)
// }
// Decodable
func decode <T> (_ key: String) throws -> T where T: Decodable {
return try Func.decode(self, key)
}
func decode <T> (_ key: String) throws -> T? where T: Decodable {
return try? self.decode(key) as T
}
func decode <T> (_ key: String) throws -> T where T: RangeReplaceableCollection, T.Element: Decodable {
return try Func.decode(self, key)
}
func decode <T> (_ key: String) throws -> T? where T: RangeReplaceableCollection, T.Element: Decodable {
return try? self.decode(key) as T
}
// RawRepresentable
func decode <T> (_ key: String) throws -> T where T: RawRepresentable {
return try Func.decode(self, key)
}
func decode <T> (_ key: String) throws -> T? where T: RawRepresentable {
return try? self.decode(key) as T
}
func decode <T> (_ key: String) throws -> T where T: RangeReplaceableCollection, T.Element: RawRepresentable {
return try Func.decode(self, key)
}
func decode <T> (_ key: String) throws -> T? where T: RangeReplaceableCollection, T.Element: RawRepresentable {
return try? self.decode(key) as T
}
// URL
func decode (_ key: String) throws -> URL {
return try Func.decode(self, key)
}
func decode (_ key: String) throws -> URL? {
return try? self.decode(key) as URL
}
func decode (_ key: String) throws -> [URL] {
return try Func.decode(self, key)
}
func decode (_ key: String) throws -> [URL]? {
return try? self.decode(key) as [URL]
}
// Date
func decode (_ key: String, format: DateFormat = .dateTime) throws -> Date {
return try Func.decode(self, key, format: format)
}
func decode (_ key: String, format: DateFormat = .dateTime) throws -> Date? {
return try? self.decode(key, format: format) as Date
}
}
public enum DecodingError: LocalizedError {
case missingKey(key: String)
case parseFailed(key: String, value: Any, valueType: Any.Type)
case dateFormat(key: String, value: String, format: String)
case any(String)
public var errorDescription: String? {
switch self {
case .missingKey(let key): return "\"\(key)\" does not exist"
case .parseFailed(let key, let value, let type): return "Expected \"\(key)\" to be of type: \(type) but was \(Swift.type(of: value))"
case .dateFormat(let key, let value, let format): return "Expected \"\(key)\" \(value) to be of format \(format)"
case .any(let description): return description
}
}
}
| mit |
olbartek/BODropdownMenu | BODropdownMenu/BODropdownMenu.swift | 1 | 40135 | //
// BODropdownMenu.swift
// BODropdownMenu
//
// Created by Bartosz Olszanowski on 05.11.2015.
// Copyright (c) 2015 Bartosz Olszanowski. 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
//MARK: Constants
private struct Constants {
static let TextMargin : CGFloat = 10
static let ViewInitialHeight = 40
static let ViewInitialWidth = 150
}
//MARK: BODropdownMenuDelegate
public protocol BODropdownMenuDelegate {
func menuWillShow(menu: BODropdownMenu)
func menuDidShow(menu: BODropdownMenu)
func menuWillHide(menu: BODropdownMenu)
func menuDidHide(menu: BODropdownMenu)
func menu(menu: BODropdownMenu, didSelectElementAtIndexPath indexPath: NSIndexPath)
}
//MARK: BODropdownMenu
public class BODropdownMenu: UIView {
//MARK: Public Properties
// Elements of menu view
public var elements : [String]! {
didSet {
if let actionButton = actionButton, menuVC = menuVC {
if elements.count > 0 {
actionButton.setTitle(self.elements.first, forState: .Normal)
menuVC.elements = elements
}
}
}
}
// Delegate
public var delegate : BODropdownMenuDelegate?
// The color of menu background. Default: grayColor()
public var menuViewBackgroundColor : UIColor! {
get {
return self.configuration.MenuViewBackgroundColor
}
set(value) {
self.configuration.MenuViewBackgroundColor = value
self.configureActionButtonAppearance()
}
}
// The border width of menu view. Default: 1
public var menuViewBorderWidth : CGFloat! {
get {
return self.configuration.MenuViewBorderWidth
}
set(value) {
self.configuration.MenuViewBorderWidth = value
self.configureActionButtonAppearance()
self.configureSeparatorViewAppearance()
}
}
// Enable/Disable border of menu view. Default: true
public var borderVisible : Bool {
get {
return self.configuration.MenuViewBorderVisible
}
set(value) {
self.configuration.MenuViewBorderVisible = value
self.configureActionButtonAppearance()
self.configureSeparatorViewAppearance()
self.menuVC?.configureTableViewAppearance()
}
}
// Enable/Disable separator view separating title and arrow. Default: true
public var separatorVisible : Bool {
get {
return self.configuration.MenuViewSeparatorVisible
}
set(value) {
self.configuration.MenuViewSeparatorVisible = value
self.configureSeparatorViewAppearance()
self.menuVC?.configureTableViewAppearance()
}
}
// The border color of menu view. Default: whiteColor()
public var menuViewBorderColor : UIColor! {
get {
return self.configuration.MenuViewBorderColor
}
set(value) {
self.configuration.MenuViewBorderColor = value
self.configureActionButtonAppearance()
self.configureSeparatorViewAppearance()
}
}
// The radius of menu view. Default: 5
public var menuViewCornerRadius : CGFloat! {
get {
return self.configuration.MenuViewCornerRadius
}
set(value) {
self.configuration.MenuViewCornerRadius = value
self.configureActionButtonAppearance()
}
}
// The color of menu label title. Default is whiteColor()
public var menuLabelTintColor : UIColor! {
get {
return self.configuration.MenuLabelTintColor
}
set(value) {
self.configuration.MenuLabelTintColor = value
self.configureActionButtonAppearance()
}
}
// The color of menu label background. Default is grayColor()
public var menuLabelBackgroundColor : UIColor! {
get {
return self.configuration.MenuLabelBackgroundColor
}
set(value) {
self.configuration.MenuLabelBackgroundColor = value
self.configureActionButtonAppearance()
}
}
// The color of menu label background. Default is system font, size: 17
public var menuLabelFont : UIFont! {
get {
return self.configuration.MenuLabelFont
}
set(value) {
self.configuration.MenuLabelFont = value
self.configureActionButtonAppearance()
}
}
// Enable/Disable menu view shadow. Default: true
public var shadowVisible : Bool {
get {
return self.configuration.MenuViewShadowVisible
}
set(value) {
self.configuration.MenuViewShadowVisible = value
menuVC?.configureTableViewAppearance()
}
}
// The shadow offset of menu view. Default: (-5,5)
public var menuViewShadowOffset : CGSize! {
get {
return self.configuration.MenuViewShadowOffset
}
set(value) {
self.configuration.MenuViewShadowOffset = value
menuVC?.configureTableViewAppearance()
}
}
// The shadow radius of menu view. Default: 5
public var menuViewShadowRadius : CGFloat! {
get {
return self.configuration.MenuViewShadowRadius
}
set(value) {
self.configuration.MenuViewShadowRadius = value
menuVC?.configureTableViewAppearance()
}
}
// The shadow opacity of menu view. Default: 0.5
public var menuViewShadowOpacity : Float! {
get {
return self.configuration.MenuViewShadowOpacity
}
set(value) {
self.configuration.MenuViewShadowOpacity = value
menuVC?.configureTableViewAppearance()
}
}
// Enable/Disable damping animation
public var animateWithDamping : Bool {
get {
return self.configuration.AnimateWithDamping
}
set(value) {
self.configuration.AnimateWithDamping = value
}
}
// Menu view animation duration, Default: 0.5
public var animationDuration : NSTimeInterval! {
get {
return self.configuration.AnimationDuration
}
set(value) {
self.configuration.AnimationDuration = value
}
}
// Menu view damping, Default: 0.6
public var animationDamping : CGFloat! {
get {
return self.configuration.Damping
}
set(value) {
self.configuration.Damping = value
}
}
// Menu view velocity, Default: 0.5
public var animationVelocity : CGFloat! {
get {
return self.configuration.Velocity
}
set(value) {
self.configuration.Velocity = value
}
}
// The cell hieght of menu view. Default: height of dropdown menu frame
public var menuViewCellHeight : CGFloat! {
get {
return self.configuration.CellHeight
}
set(value) {
self.configuration.CellHeight = value
self.menuVC?.tableView.endUpdates()
self.menuVC?.tableView.reloadData()
}
}
// The cell separator color. Default: blackColor()
public var menuViewCellSeparatorColor : UIColor! {
get {
return self.configuration.CellSeparatorColor
}
set(value) {
self.configuration.CellSeparatorColor = value
self.configureSeparatorViewAppearance()
}
}
// The cell text color. Default: whiteColor()
public var menuViewCellTextColor : UIColor! {
get {
return self.configuration.CellTextLabelColor
}
set(value) {
self.configuration.CellTextLabelColor = value
self.menuVC?.tableView.endUpdates()
self.menuVC?.tableView.reloadData()
}
}
// The cell text font. Default: system font, size: 15
public var menuViewCellFont : UIFont! {
get {
return self.configuration.CellTextLabelFont
}
set(value) {
self.configuration.CellTextLabelFont = value
self.menuVC?.tableView.endUpdates()
self.menuVC?.tableView.reloadData()
}
}
// The cell selection color. Default: clearColor()
public var menuViewCellSelectionColor : UIColor! {
get {
return self.configuration.CellSelectionColor
}
set(value) {
self.configuration.CellSelectionColor = value
self.menuVC?.tableView.endUpdates()
self.menuVC?.tableView.reloadData()
}
}
// The arrow image. Default: default arrow image from bundle
public var arrowImage : UIImage! {
get {
return self.configuration.ArrowImage
}
set(value) {
self.configuration.ArrowImage = value
self.configureMenuArrowAppearance()
}
}
// The arrow visibility. Default: true
public var arrowVisible : Bool {
get {
return self.configuration.ArrowVisible
}
set(value) {
self.configuration.ArrowVisible = value
self.configureMenuArrowAppearance()
}
}
// Mask background color. Default: blackColor()
public var maskBackgroundColor : UIColor! {
get {
return self.configuration.MaskBackgroundColor
}
set(value) {
self.configuration.MaskBackgroundColor = value
}
}
// Mask background opacity. Default: 0.3
public var maskBackgroundOpacity : CGFloat! {
get {
return self.configuration.MaskBackgroundOpacity
}
set(value) {
self.configuration.MaskBackgroundOpacity = value
}
}
//MARK: Private Properties
private var menuVC : BOMenuViewController?
private var actionButton : UIButton!
private var menuHidden = true
private var currentSelectedIndexPath = NSIndexPath(forRow: 0, inSection: 0)
private var menuArrow : UIImageView!
private var configuration = BOConfiguration()
private var separatorView : UIView?
//MARK: Initialization
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.elements = []
defaultSetup()
}
public init(elements: [String]) {
super.init(frame: CGRect(x: 0, y: 0, width: Constants.ViewInitialWidth, height: Constants.ViewInitialHeight))
if let superview = superview {
self.translatesAutoresizingMaskIntoConstraints = false
self.constrain(.CenterX, .Equal, superview, .CenterX, constant: 0, multiplier: 1)?.constrain(.CenterY, .Equal, superview, .CenterY, constant: 0, multiplier: 1)
}
self.elements = elements
defaultSetup()
}
//MARK: Appearance
public override func layoutSubviews() {
super.layoutSubviews()
}
//MARK: Actions
public override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
if let menuVC = menuVC {
var pointForTargetView = point
if !menuHidden { pointForTargetView.y += self.bounds.size.height }
print("\(pointForTargetView)")
if CGRectContainsPoint(menuVC.tableView.bounds, pointForTargetView) {
if (pointForTargetView.y <= self.bounds.size.height) {
return actionButton.hitTest(pointForTargetView, withEvent: event)
} else {
return menuVC.tableView.hitTest(point, withEvent: event)
}
} else if CGRectContainsPoint(menuVC.tableView.bounds, point) {
return menuVC.tableView.hitTest(point, withEvent: event)
}
}
return super.hitTest(point, withEvent: event)
}
//MARK: Configuration
private func defaultSetup() {
self.configuration.CellHeight = self.frame.size.height
configureActionButton()
configureMenuArrow()
configureMenuVC()
}
//MARK: Private functions
private func configureActionButton() {
actionButton = UIButton(frame: CGRectZero)
actionButton.translatesAutoresizingMaskIntoConstraints = false
addSubview(actionButton)
guard let superview = actionButton.superview else {
assert(false, "ActionButton adding to superview failed.")
return
}
// Constraints
actionButton.constrain(.Leading, .Equal, superview, .Leading, constant: 0, multiplier: 1)?.constrain(.Trailing, .Equal, superview, .Trailing, constant: 0, multiplier: 1)?.constrain(.Top, .Equal, superview, .Top, constant: 0, multiplier: 1)?.constrain(.Bottom, .Equal, superview, .Bottom, constant: 0, multiplier: 1)
// Appearance
configureActionButtonAppearance()
// Actions
actionButton.addTarget(self, action: #selector(BODropdownMenu.menuAction(_:)), forControlEvents: .TouchUpInside)
}
private func configureActionButtonAppearance() {
actionButton.setTitleColor(configuration.MenuLabelTintColor, forState: .Normal)
actionButton.titleLabel?.font = configuration.MenuLabelFont
actionButton.backgroundColor = configuration.MenuLabelBackgroundColor
actionButton.opaque = false
actionButton.contentHorizontalAlignment = .Left
actionButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: Constants.TextMargin, bottom: 0, right: 0)
if configuration.MenuViewBorderVisible {
actionButton.layer.cornerRadius = configuration.MenuViewCornerRadius
actionButton.layer.borderColor = configuration.MenuViewBorderColor.CGColor
actionButton.layer.borderWidth = configuration.MenuViewBorderWidth
actionButton.clipsToBounds = true
} else {
actionButton.layer.cornerRadius = configuration.MenuViewCornerRadius
actionButton.layer.borderColor = UIColor.clearColor().CGColor
actionButton.layer.borderWidth = 0
actionButton.clipsToBounds = true
}
}
private func configureMenuArrow() {
menuArrow = UIImageView(frame: CGRectZero)
menuArrow.translatesAutoresizingMaskIntoConstraints = false
actionButton.addSubview(menuArrow)
guard let superview = actionButton.superview else {
assert(false, "MenuArrow adding to superview failed.")
return
}
// Constraints
menuArrow.constrain(.Trailing, .Equal, superview, .Trailing, constant: 0, multiplier: 1)?.constrain(.Top, .Equal, superview, .Top, constant: 0, multiplier: 1)?.constrain(.Bottom, .Equal, superview, .Bottom, constant: 0, multiplier: 1)?.constrain(.Width, .Equal, menuArrow, .Height, constant: 0, multiplier: 1)
// Appearance
configureMenuArrowAppearance()
}
private func configureMenuArrowAppearance() {
if configuration.ArrowVisible && menuArrow != nil {
menuArrow.image = self.configuration.ArrowImage
if configuration.MenuViewBorderVisible {
configureSeparatorView()
}
} else {
menuArrow.removeFromSuperview()
menuArrow = nil
}
}
private func configureSeparatorView() {
if separatorView == nil {
separatorView = UIView(frame: CGRectZero)
guard let separatorView = separatorView else {
return
}
separatorView.translatesAutoresizingMaskIntoConstraints = false
actionButton.addSubview(separatorView)
guard let separatorSuperview = separatorView.superview else {
assert(false, "SeparatorView adding to superview failed.")
return
}
// Constraints
separatorView.constrain(.Top, .Equal, separatorSuperview, .Top, constant: 0, multiplier: 1)?.constrain(.Bottom, .Equal, separatorSuperview, .Bottom, constant: 0, multiplier: 1)?.constrain(.Width, .Equal, constant: 1)
if let menuArrowView = menuArrow {
let relationConstraint = NSLayoutConstraint(item: separatorView, attribute: .Trailing, relatedBy: .Equal, toItem: menuArrowView, attribute: .Leading, multiplier: 1, constant: 0)
actionButton.addConstraint(relationConstraint)
}
// Appearance
configureSeparatorViewAppearance()
}
}
private func configureSeparatorViewAppearance() {
if let separatorView = separatorView {
if configuration.MenuViewBorderVisible {
if configuration.MenuViewSeparatorVisible {
separatorView.backgroundColor = self.configuration.MenuViewBorderColor
} else {
separatorView.removeFromSuperview()
self.separatorView = nil
}
} else {
separatorView.removeFromSuperview()
self.separatorView = nil
}
}
}
private func configureMenuVC() {
menuVC = BOMenuViewController(elements: elements, configuration: configuration)
guard let menuVC = menuVC else {
return
}
menuVC.delegate = self
menuVC.view.translatesAutoresizingMaskIntoConstraints = false
addSubview(menuVC.view)
guard let menuViewSuperview = menuVC.view.superview else {
assert(false, "MenuView adding to superview failed.")
return
}
// Constraints
menuVC.view.constrain(.Trailing, .Equal, menuViewSuperview, .Trailing, constant: 0, multiplier: 1)?.constrain(.Top, .Equal, menuViewSuperview, .Bottom, constant: 0, multiplier: 1)?.constrain(.Leading, .Equal, menuViewSuperview, .Leading, constant: 0, multiplier: 1)
menuVC.tvHeightConstraint = NSLayoutConstraint(item: menuVC.view, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 0)
menuVC.view.addConstraint(menuVC.tvHeightConstraint)
}
//MARK: Public functions
public func setMenuTitle(title: String) {
actionButton.setTitle(title, forState: .Normal)
}
public func showMenu() {
menuAction(nil)
}
public func hideMenu() {
menuAction(nil)
}
public func showOrHideMenu() {
menuAction(nil)
}
public func isMenuHidden() -> Bool {
return menuHidden
}
public func isPoint(point: CGPoint, withinTableViewBoundsFromReferencingView view: UIView) -> (isPoint: Bool, pointForTargetView: CGPoint?) {
if let menuVC = menuVC {
if !self.isMenuHidden() {
let pointForTargetView = menuVC.tableView.convertPoint(point, fromView: view)
let wrapperFrame = CGRect(origin: CGPoint(x: 0, y: -self.bounds.size.height), size: CGSize(width: menuVC.tableView.bounds.size.width, height: menuVC.tableView.bounds.size.height + self.bounds.size.height))
return (CGRectContainsPoint(wrapperFrame, pointForTargetView), pointForTargetView)
}
}
return (false, nil)
}
//MARK: Animations
@IBAction public func menuAction(sender: UIButton?) {
guard let menuVC = menuVC else {
return
}
if menuHidden {
menuVC.tableView.reloadData()
rotateArrow()
showMenuWithCompletionBlock() { (succeeded: Bool) -> Void in
if succeeded {
self.delegate?.menuDidShow(self)
self.menuHidden = false
}
}
} else {
rotateArrow()
hideMenuWithCompletionBlock() { (succeeded: Bool) -> Void in
if succeeded {
self.delegate?.menuDidHide(self)
self.menuHidden = true
}
}
}
}
private func showMenuWithCompletionBlock(completion: (succeeded: Bool) -> Void) {
guard let menuVC = menuVC else {
completion(succeeded: false)
return
}
delegate?.menuWillShow(self)
let tvHeight = configuration.CellHeight * CGFloat(elements.count)
menuVC.tvHeightConstraint.constant = tvHeight
if animateWithDamping {
UIView.animateWithDuration(configuration.AnimationDuration, delay: 0, usingSpringWithDamping: configuration.Damping, initialSpringVelocity: configuration.Velocity, options: .CurveEaseInOut, animations: { () -> Void in
menuVC.view.layoutIfNeeded()
}, completion: { (finished) -> Void in
if finished {
completion(succeeded: true)
}
})
} else {
UIView.animateWithDuration(configuration.AnimationDuration, animations: { () -> Void in
menuVC.view.layoutIfNeeded()
}) { (finished) -> Void in
if finished {
completion(succeeded: true)
}
}
}
}
private func hideMenuWithCompletionBlock(completion: (succeeded: Bool) -> Void) {
guard let menuVC = menuVC else {
completion(succeeded: false)
return
}
delegate?.menuWillHide(self)
menuVC.tvHeightConstraint.constant = 0
if animateWithDamping {
UIView.animateWithDuration(configuration.AnimationDuration, delay: 0, usingSpringWithDamping: configuration.Damping, initialSpringVelocity: configuration.Velocity, options: .CurveEaseInOut, animations: { () -> Void in
menuVC.view.layoutIfNeeded()
}, completion: { (finished) -> Void in
if finished {
completion(succeeded: true)
}
})
} else {
UIView.animateWithDuration(configuration.AnimationDuration, animations: { () -> Void in
menuVC.view.layoutIfNeeded()
}, completion: { (finished) -> Void in
if finished {
completion(succeeded: true)
}
})
}
}
private func performRowSelectionForIndexPath(indexPath: NSIndexPath) {
currentSelectedIndexPath = indexPath
actionButton.setTitle(elements[indexPath.row], forState: .Normal)
rotateArrow()
hideMenuWithCompletionBlock { [weak self] (succeeded: Bool) -> Void in
if succeeded {
guard let strongSelf = self else {
return
}
strongSelf.delegate?.menuDidHide(strongSelf)
strongSelf.menuHidden = true
}
}
}
private func rotateArrow() {
if configuration.ArrowVisible && menuArrow != nil {
UIView.animateWithDuration(self.configuration.AnimationDuration) { [weak self] () -> () in
if let strongSelf = self {
strongSelf.menuArrow.transform = CGAffineTransformRotate(strongSelf.menuArrow.transform, 180 * CGFloat(M_PI / 180))
}
}
}
}
}
extension BODropdownMenu: BOMenuViewControllerDelegate {
private func tableView(tableView: UITableView, didSelectElementAtIndexPath indexPath: NSIndexPath) {
delegate?.menu(self, didSelectElementAtIndexPath: indexPath)
performRowSelectionForIndexPath(indexPath)
}
}
//MARK: BODropdownMenuDelegate
private protocol BOMenuViewControllerDelegate {
func tableView(tableView: UITableView, didSelectElementAtIndexPath indexPath: NSIndexPath)
}
private class BOMenuViewController: UIViewController {
//MARK: Properties
var tableView : BOTableView!
var configuration : BOConfiguration
var tvHeightConstraint : NSLayoutConstraint!
var elements : [String] {
didSet {
if elements.count > 0 {
tableView.reloadData()
}
}
}
var delegate : BOMenuViewControllerDelegate?
//MARK: Initialization
required init(elements: [String], configuration: BOConfiguration) {
self.elements = elements
self.configuration = configuration
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: VC's Lifecycle
private override func viewDidLoad() {
configureTableView()
}
//MARK: Configuration
private func configureTableView() {
// Create tableView
tableView = BOTableView(frame: CGRectZero, items: elements, configuration: configuration)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
// Appearance
if let _ = tableView {
configureTableViewAppearance()
}
//Constraints
guard let tableViewSuperview = tableView.superview else {
assert(false, "TableView adding to superview failed.")
return
}
tableView.constrain(.Trailing, .Equal, tableViewSuperview, .Trailing)?.constrain(.Top, .Equal, tableViewSuperview, .Top)?.constrain(.Leading, .Equal, tableViewSuperview, .Leading)?.constrain(.Bottom, .Equal, tableViewSuperview, .Bottom)
}
private func configureTableViewAppearance() {
if configuration.MenuViewShadowVisible {
view.layer.shadowOffset = configuration.MenuViewShadowOffset
view.layer.shadowRadius = configuration.MenuViewShadowRadius
view.layer.shadowOpacity = configuration.MenuViewShadowOpacity
} else {
view.layer.shadowOffset = CGSize(width: 0, height: -3)
view.layer.shadowRadius = 3
view.layer.shadowOpacity = 0
}
if configuration.MenuViewBorderVisible {
tableView.layer.cornerRadius = configuration.MenuViewCornerRadius
tableView.layer.borderColor = configuration.MenuViewBorderColor.CGColor
tableView.layer.borderWidth = configuration.MenuViewBorderWidth
} else {
tableView.layer.cornerRadius = configuration.MenuViewCornerRadius
tableView.layer.borderColor = UIColor.clearColor().CGColor
tableView.layer.borderWidth = 0
}
}
}
//MARK: UITableView delegate & datasource
extension BOMenuViewController: UITableViewDelegate, UITableViewDataSource {
@objc private func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return elements.count
}
@objc private func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = BODropdownMenuCell(style: .Default, reuseIdentifier: BODropdownMenuCell.boCellIdentifier(), configuration: self.configuration)
cell.textLabel?.text = self.elements[indexPath.row]
cell.textLabel?.textAlignment = .Left
cell.textLabel?.textColor = self.configuration.CellTextLabelColor
cell.textLabel?.font = self.configuration.CellTextLabelFont
cell.contentView.backgroundColor = self.configuration.MenuViewBackgroundColor
let cellSelectionColor = self.configuration.CellSelectionColor
if cellSelectionColor.isEqual(UIColor.clearColor()) {
cell.selectionStyle = .None
} else {
let bgView = UIView()
bgView.backgroundColor = self.configuration.CellSelectionColor
cell.selectedBackgroundView = bgView
}
cell.lineView.backgroundColor = self.configuration.CellSeparatorColor
return cell
}
@objc private func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return self.configuration.CellHeight
}
@objc private func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let delegate = delegate {
delegate.tableView(tableView, didSelectElementAtIndexPath: indexPath)
}
}
@objc private func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.respondsToSelector(Selector("setSeparatorInset:")) {
cell.separatorInset = UIEdgeInsetsZero
}
if cell.respondsToSelector(Selector("setLayoutMargins:")) {
cell.layoutMargins = UIEdgeInsetsZero
}
if cell.respondsToSelector(Selector("setPreservesSuperviewLayoutMargins:")) {
cell.preservesSuperviewLayoutMargins = false
}
}
}
// MARK: BOConfiguration
private class BOConfiguration {
var MenuViewBackgroundColor : UIColor!
var MenuViewCornerRadius : CGFloat!
var MenuViewBorderVisible : Bool
var MenuViewSeparatorVisible : Bool
var MenuViewBorderWidth : CGFloat!
var MenuViewBorderColor : UIColor!
var MenuViewShadowVisible : Bool
var MenuViewShadowOffset : CGSize!
var MenuViewShadowRadius : CGFloat!
var MenuViewShadowOpacity : Float!
var MenuLabelTintColor : UIColor!
var MenuLabelBackgroundColor : UIColor!
var MenuLabelFont : UIFont!
var CellHeight : CGFloat!
var CellSeparatorColor : UIColor!
var CellTextLabelColor : UIColor!
var CellTextLabelFont : UIFont!
var CellSelectionColor : UIColor!
var ArrowImage : UIImage!
var ArrowVisible : Bool
var AnimateWithDamping : Bool
var AnimationDuration : NSTimeInterval!
var Damping : CGFloat!
var Velocity : CGFloat!
var MaskBackgroundColor : UIColor!
var MaskBackgroundOpacity : CGFloat!
init() {
MenuViewBorderVisible = true
MenuViewShadowVisible = true
AnimateWithDamping = true
MenuViewSeparatorVisible = true
ArrowVisible = true
defaultValue()
}
func defaultValue() {
// Arrow image
let bundle = NSBundle(forClass: BODropdownMenu.self)
let url = bundle.URLForResource("BODropdownMenu", withExtension: "bundle")
let imageBundle = NSBundle(URL: url!)
let arrowImagePath = imageBundle?.pathForResource("arrow", ofType: "png")
ArrowImage = UIImage(contentsOfFile: arrowImagePath!)
// Border & Colors
MenuViewBackgroundColor = UIColor.grayColor()
MenuViewCornerRadius = 5
MenuViewBorderWidth = 1
MenuViewBorderColor = UIColor.whiteColor()
MenuLabelTintColor = UIColor.whiteColor()
MenuLabelBackgroundColor = UIColor.grayColor()
MenuLabelFont = UIFont.systemFontOfSize(17)
// Shadow
MenuViewShadowOffset = CGSize(width: -5, height: 5)
MenuViewShadowRadius = 5
MenuViewShadowOpacity = 0.5
// Cells' configuration
CellSeparatorColor = UIColor.blackColor()
CellTextLabelColor = UIColor.whiteColor()
CellTextLabelFont = UIFont.systemFontOfSize(15)
CellSelectionColor = UIColor.clearColor()
CellHeight = 30
// Animation
AnimationDuration = 0.5
Damping = 0.6
Velocity = 0.5
// Masks
MaskBackgroundColor = UIColor.blackColor()
MaskBackgroundOpacity = 0.3
}
}
//MARK: BODropdownMenuTVC
private class BODropdownMenuCell: UITableViewCell {
var configuration : BOConfiguration!
var cellContentFrame : CGRect!
var lineView : UIView!
// MARK: Initialization
init(style: UITableViewCellStyle, reuseIdentifier: String?, configuration: BOConfiguration) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.configuration = configuration
configureLineView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: Appearance
func configureLineView() {
lineView = UIView(frame: CGRectZero)
self.contentView.addSubview(lineView)
guard let superview = lineView.superview else {
assert(false, "LineView adding to superview failed.")
return
}
// Constraints
lineView.translatesAutoresizingMaskIntoConstraints = false
lineView.constrain(.Trailing, .Equal, superview, .Trailing)?.constrain(.Leading, .Equal, superview, .Leading)?.constrain(.Bottom, .Equal, superview, .Bottom)
let heightConstraint = NSLayoutConstraint(item: lineView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 1)
lineView.addConstraint(heightConstraint)
}
}
//MARK: UITableViewCell + CellIdentifier
extension UITableViewCell {
class func boCellIdentifier() -> String! {
return NSStringFromClass(self).componentsSeparatedByString(".").last!
}
}
//MARK: BOTableView
private class BOTableView: UITableView {
// Public properties
var configuration : BOConfiguration!
// Private properties
private var items : [String]!
private var selectedIndexPath : NSIndexPath!
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(frame: CGRect, items: [String], configuration: BOConfiguration) {
super.init(frame: frame, style: UITableViewStyle.Plain)
self.items = items
self.selectedIndexPath = NSIndexPath(forRow: 0, inSection: 0)
self.configuration = configuration
// Setup table view
self.opaque = false
self.backgroundView?.backgroundColor = configuration.MenuViewBackgroundColor
self.backgroundColor = configuration.MenuViewBackgroundColor
self.scrollEnabled = false
self.separatorStyle = .None
if configuration.MenuViewBorderVisible {
self.layer.cornerRadius = configuration.MenuViewCornerRadius
self.layer.borderColor = configuration.MenuViewBorderColor.CGColor
self.layer.borderWidth = configuration.MenuViewBorderWidth
}
self.clipsToBounds = true
}
}
// MARK: UIView + Constraints
extension UIView {
/**
:returns: true if v is in this view's super view chain
*/
public func isSuper(v : UIView) -> Bool
{
var s: UIView? = self
while (s != nil) {
if(v == s) { return true }
s = s?.superview
}
return false
}
public func constrain(attribute: NSLayoutAttribute, _ relation: NSLayoutRelation, _ otherView: UIView, _ otherAttribute: NSLayoutAttribute, constant: CGFloat = 0.0, multiplier : CGFloat = 1.0) -> UIView?
{
let c = NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relation, toItem: otherView, attribute: otherAttribute, multiplier: multiplier, constant: constant)
if isSuper(otherView) {
otherView.addConstraint(c)
return self
}
else if(otherView.isSuper(self) || otherView == self)
{
self.addConstraint(c)
return self
}
assert(false)
return nil
}
public func constrain(attribute: NSLayoutAttribute, _ relation: NSLayoutRelation, constant: CGFloat, multiplier : CGFloat = 1.0) -> UIView?
{
let c = NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relation, toItem: nil, attribute: .NotAnAttribute, multiplier: multiplier, constant: constant)
self.addConstraint(c)
return self
}
} | mit |
czechboy0/XcodeServerSDK | XcodeServerSDKTests/RepositoryTests.swift | 1 | 4681 | //
// Repository.swift
// XcodeServerSDK
//
// Created by Mateusz Zając on 28.06.2015.
// Copyright © 2015 Honza Dvorsky. All rights reserved.
//
import XCTest
import XcodeServerSDK
class RepositoryTests: XCTestCase {
let json = [
"readAccessExternalIDs": [],
"writeAccessExternalIDs": [
"FDF283F5-B9C3-4B43-9000-EF6A54934D4E",
"ABCDEFAB-CDEF-ABCD-EFAB-CDEF00000050"
],
"name": "Test",
"posixPermissions": 1,
"httpAccessType": 1
]
// MARK: Initialization
func testInit() throws {
let repo = try Repository(json: json)
XCTAssertEqual(repo.name, "Test")
XCTAssertEqual(repo.httpAccess, Repository.HTTPAccessType.LoggedIn)
XCTAssertEqual(repo.sshAccess, Repository.SSHAccessType.LoggedInReadSelectedWrite)
XCTAssertEqual(repo.writeAccessExternalIds, [ "FDF283F5-B9C3-4B43-9000-EF6A54934D4E", "ABCDEFAB-CDEF-ABCD-EFAB-CDEF00000050" ])
XCTAssertEqual(repo.readAccessExternalIds, [])
}
func testManualInit() {
let repo = Repository(name: "Test", httpAccess: .LoggedIn, sshAccess: .LoggedInReadSelectedWrite, writeAccessExternalIds: [ "FDF283F5-B9C3-4B43-9000-EF6A54934D4E", "ABCDEFAB-CDEF-ABCD-EFAB-CDEF00000050" ], readAccessExternalIds: [])
XCTAssertEqual(repo.name, "Test")
XCTAssertEqual(repo.httpAccess, Repository.HTTPAccessType.LoggedIn)
XCTAssertEqual(repo.sshAccess, Repository.SSHAccessType.LoggedInReadSelectedWrite)
XCTAssertEqual(repo.writeAccessExternalIds, [ "FDF283F5-B9C3-4B43-9000-EF6A54934D4E", "ABCDEFAB-CDEF-ABCD-EFAB-CDEF00000050" ])
XCTAssertEqual(repo.readAccessExternalIds, [])
}
func testConvenienceInit() {
let repo = Repository(name: "Test")
XCTAssertEqual(repo.name, "Test")
XCTAssertEqual(repo.httpAccess, Repository.HTTPAccessType.None)
XCTAssertEqual(repo.sshAccess, Repository.SSHAccessType.LoggedInReadWrite)
XCTAssertEqual(repo.writeAccessExternalIds, [])
XCTAssertEqual(repo.readAccessExternalIds, [])
}
// MARK: JSONifying
func testDictionarify() {
let repo = Repository(name: "Test", httpAccess: .LoggedIn, sshAccess: .LoggedInReadSelectedWrite, writeAccessExternalIds: [ "FDF283F5-B9C3-4B43-9000-EF6A54934D4E", "ABCDEFAB-CDEF-ABCD-EFAB-CDEF00000050" ], readAccessExternalIds: [])
XCTAssertEqual(repo.dictionarify(), json)
}
// MARK: Enum tests
func testHTTPEnum() {
var httpEnum = Repository.HTTPAccessType.None
XCTAssertEqual(httpEnum.toString(), "No users are not allowed to read or write")
httpEnum = .LoggedIn
XCTAssertEqual(httpEnum.toString(), "Logged in users are allowed to read and write")
}
func testSSHEnum() {
var sshEnum = Repository.SSHAccessType.SelectedReadWrite
XCTAssertEqual(sshEnum.toString(), "Only selected users can read and/or write")
sshEnum = .LoggedInReadSelectedWrite
XCTAssertEqual(sshEnum.toString(), "Only selected users can write but all logged in can read")
sshEnum = .LoggedInReadWrite
XCTAssertEqual(sshEnum.toString(), "All logged in users can read and write")
}
// MARK: API Routes tests
func testGetRepositories() {
let expectation = self.expectationWithDescription("Get Repositories")
let server = self.getRecordingXcodeServer("get_repositories")
server.getRepositories() { (repositories, error) in
XCTAssertNil(error, "Error should be nil")
XCTAssertNotNil(repositories, "Repositories shouldn't be nil")
if let repos = repositories {
XCTAssertEqual(repos.count, 2, "There should be two repositories available")
let reposNames = Set(repos.map { $0.name })
let reposSSHAccess = Set(repos.map { $0.sshAccess.rawValue })
let writeAccessExternalIDs = Set(repos.flatMap { $0.writeAccessExternalIds })
for (index, _) in repos.enumerate() {
XCTAssertTrue(reposNames.contains("Test\(index + 1)"))
XCTAssertTrue(reposSSHAccess.elementsEqual(Set([2, 0])))
XCTAssertTrue(writeAccessExternalIDs.elementsEqual(Set([ "ABCDEFAB-CDEF-ABCD-EFAB-CDEF00000050", "D024C308-CEBE-4E72-BE40-E1E4115F38F9" ])))
}
}
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(10.0, handler: nil)
}
}
| mit |
brentdax/swift | test/IRGen/class_bounded_generics.swift | 2 | 17211 | // RUN: %target-swift-frontend -module-name class_bounded_generics -enable-objc-interop -emit-ir -primary-file %s -disable-objc-attr-requires-foundation-module | %FileCheck %s -DINT=i%target-ptrsize
// REQUIRES: CPU=x86_64
protocol ClassBound : class {
func classBoundMethod()
}
protocol ClassBound2 : class {
func classBoundMethod2()
}
protocol ClassBoundBinary : ClassBound {
func classBoundBinaryMethod(_ x: Self)
}
@objc protocol ObjCClassBound {
func objCClassBoundMethod()
}
@objc protocol ObjCClassBound2 {
func objCClassBoundMethod2()
}
protocol NotClassBound {
func notClassBoundMethod()
func notClassBoundBinaryMethod(_ x: Self)
}
struct ClassGenericFieldStruct<T:ClassBound> {
var x : Int
var y : T
var z : Int
}
struct ClassProtocolFieldStruct {
var x : Int
var y : ClassBound
var z : Int
}
class ClassGenericFieldClass<T:ClassBound> {
final var x : Int = 0
final var y : T
final var z : Int = 0
init(t: T) {
y = t
}
}
class ClassProtocolFieldClass {
var x : Int = 0
var y : ClassBound
var z : Int = 0
init(classBound cb: ClassBound) {
y = cb
}
}
// CHECK-DAG: %T22class_bounded_generics017ClassGenericFieldD0C = type <{ %swift.refcounted, %TSi, %objc_object*, %TSi }>
// CHECK-DAG: %T22class_bounded_generics23ClassGenericFieldStructV = type <{ %TSi, %objc_object*, %TSi }>
// CHECK-DAG: %T22class_bounded_generics24ClassProtocolFieldStructV = type <{ %TSi, %T22class_bounded_generics10ClassBoundP, %TSi }>
// CHECK-LABEL: define hidden swiftcc %objc_object* @"$s22class_bounded_generics0a1_B10_archetype{{[_0-9a-zA-Z]*}}F"(%objc_object*, %swift.type* %T, i8** %T.ClassBound)
func class_bounded_archetype<T : ClassBound>(_ x: T) -> T {
return x
}
class SomeClass {}
class SomeSubclass : SomeClass {}
// CHECK-LABEL: define hidden swiftcc %T22class_bounded_generics9SomeClassC* @"$s22class_bounded_generics011superclass_B10_archetype{{[_0-9a-zA-Z]*}}F"(%T22class_bounded_generics9SomeClassC*, %swift.type* %T)
func superclass_bounded_archetype<T : SomeClass>(_ x: T) -> T {
return x
}
// CHECK-LABEL: define hidden swiftcc { %T22class_bounded_generics9SomeClassC*, %T22class_bounded_generics12SomeSubclassC* } @"$s22class_bounded_generics011superclass_B15_archetype_call{{[_0-9a-zA-Z]*}}F"(%T22class_bounded_generics9SomeClassC*, %T22class_bounded_generics12SomeSubclassC*)
func superclass_bounded_archetype_call(_ x: SomeClass, y: SomeSubclass) -> (SomeClass, SomeSubclass) {
return (superclass_bounded_archetype(x),
superclass_bounded_archetype(y));
// CHECK: [[SOMECLASS_RESULT:%.*]] = call swiftcc %T22class_bounded_generics9SomeClassC* @"$s22class_bounded_generics011superclass_B10_archetype{{[_0-9a-zA-Z]*}}F"(%T22class_bounded_generics9SomeClassC* {{%.*}}, {{.*}})
// CHECK: [[SOMESUPERCLASS_IN:%.*]] = bitcast %T22class_bounded_generics12SomeSubclassC* {{%.*}} to %T22class_bounded_generics9SomeClassC*
// CHECK: [[SOMESUPERCLASS_RESULT:%.*]] = call swiftcc %T22class_bounded_generics9SomeClassC* @"$s22class_bounded_generics011superclass_B10_archetype{{[_0-9a-zA-Z]*}}F"(%T22class_bounded_generics9SomeClassC* [[SOMESUPERCLASS_IN]], {{.*}})
// CHECK: bitcast %T22class_bounded_generics9SomeClassC* [[SOMESUPERCLASS_RESULT]] to %T22class_bounded_generics12SomeSubclassC*
}
// CHECK-LABEL: define hidden swiftcc void @"$s22class_bounded_generics0a1_B17_archetype_method{{[_0-9a-zA-Z]*}}F"(%objc_object*, %objc_object*, %swift.type* %T, i8** %T.ClassBoundBinary)
func class_bounded_archetype_method<T : ClassBoundBinary>(_ x: T, y: T) {
x.classBoundMethod()
// CHECK: [[INHERITED_GEP:%.*]] = getelementptr inbounds i8*, i8** %T.ClassBoundBinary, i32 1
// CHECK: [[INHERITED:%.*]] = load i8*, i8** [[INHERITED_GEP]]
// CHECK: [[INHERITED_WTBL:%.*]] = bitcast i8* [[INHERITED]] to i8**
// CHECK: [[WITNESS_GEP:%.*]] = getelementptr inbounds i8*, i8** [[INHERITED_WTBL]], i32 1
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_GEP]], align 8
// CHECK: [[WITNESS_FUNC:%.*]] = bitcast i8* [[WITNESS]] to void (%objc_object*, %swift.type*, i8**)
// CHECK: call swiftcc void [[WITNESS_FUNC]](%objc_object* swiftself %0, %swift.type* {{.*}}, i8** [[INHERITED_WTBL]])
x.classBoundBinaryMethod(y)
// CHECK-NOT: call %objc_object* @swift_unknownObjectRetain(%objc_object* returned [[Y:%.*]])
// CHECK: [[WITNESS_ENTRY:%.*]] = getelementptr inbounds i8*, i8** %T.ClassBoundBinary, i32 2
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ENTRY]], align 8
// CHECK: [[WITNESS_FUNC:%.*]] = bitcast i8* [[WITNESS]] to void (%objc_object*, %objc_object*, %swift.type*, i8**)
// CHECK: call swiftcc void [[WITNESS_FUNC]](%objc_object* %1, %objc_object* swiftself %0, %swift.type* %T, i8** %T.ClassBoundBinary)
}
// CHECK-LABEL: define hidden swiftcc { %objc_object*, %objc_object* } @"$s22class_bounded_generics0a1_B16_archetype_tuple{{[_0-9a-zA-Z]*}}F"(%objc_object*, %swift.type* %T, i8** %T.ClassBound)
func class_bounded_archetype_tuple<T : ClassBound>(_ x: T) -> (T, T) {
return (x, x)
}
class ConcreteClass : ClassBoundBinary, NotClassBound {
func classBoundMethod() {}
func classBoundBinaryMethod(_ x: ConcreteClass) {}
func notClassBoundMethod() {}
func notClassBoundBinaryMethod(_ x: ConcreteClass) {}
}
// CHECK-LABEL: define hidden swiftcc %T22class_bounded_generics13ConcreteClassC* @"$s22class_bounded_generics05call_a1_B10_archetype{{[_0-9a-zA-Z]*}}F"(%T22class_bounded_generics13ConcreteClassC*) {{.*}} {
func call_class_bounded_archetype(_ x: ConcreteClass) -> ConcreteClass {
return class_bounded_archetype(x)
// CHECK: [[IN:%.*]] = bitcast %T22class_bounded_generics13ConcreteClassC* {{%.*}} to %objc_object*
// CHECK: [[OUT_ORIG:%.*]] = call swiftcc %objc_object* @"$s22class_bounded_generics0a1_B10_archetype{{[_0-9a-zA-Z]*}}F"(%objc_object* [[IN]], {{.*}})
// CHECK: [[OUT:%.*]] = bitcast %objc_object* [[OUT_ORIG]] to %T22class_bounded_generics13ConcreteClassC*
// CHECK: ret %T22class_bounded_generics13ConcreteClassC* [[OUT]]
}
// CHECK: define hidden swiftcc void @"$s22class_bounded_generics04not_a1_B10_archetype{{[_0-9a-zA-Z]*}}F"(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.NotClassBound)
func not_class_bounded_archetype<T : NotClassBound>(_ x: T) -> T {
return x
}
// CHECK-LABEL: define hidden swiftcc %objc_object* @"$s22class_bounded_generics0a1_b18_archetype_to_not_a1_B0{{[_0-9a-zA-Z]*}}F"(%objc_object*, %swift.type* %T, i8** %T.ClassBound, i8** %T.NotClassBound) {{.*}} {
func class_bounded_archetype_to_not_class_bounded
<T: ClassBound & NotClassBound>(_ x:T) -> T {
// CHECK: alloca %objc_object*, align 8
return not_class_bounded_archetype(x)
}
/* TODO Abstraction remapping to non-class-bounded witnesses
func class_and_not_class_bounded_archetype_methods
<T: ClassBound & NotClassBound>(_ x:T, y:T) {
x.classBoundMethod()
x.classBoundBinaryMethod(y)
x.notClassBoundMethod()
x.notClassBoundBinaryMethod(y)
}
*/
// CHECK-LABEL: define hidden swiftcc { %objc_object*, i8** } @"$s22class_bounded_generics0a1_B8_erasure{{[_0-9a-zA-Z]*}}F"(%T22class_bounded_generics13ConcreteClassC*) {{.*}} {
func class_bounded_erasure(_ x: ConcreteClass) -> ClassBound {
return x
// CHECK: [[INSTANCE_OPAQUE:%.*]] = bitcast %T22class_bounded_generics13ConcreteClassC* [[INSTANCE:%.*]] to %objc_object*
// CHECK: [[T0:%.*]] = insertvalue { %objc_object*, i8** } undef, %objc_object* [[INSTANCE_OPAQUE]], 0
// CHECK: [[T1:%.*]] = insertvalue { %objc_object*, i8** } [[T0]], i8** getelementptr inbounds ([2 x i8*], [2 x i8*]* @"$s22class_bounded_generics13ConcreteClassCAA0E5BoundAAWP", i32 0, i32 0), 1
// CHECK: ret { %objc_object*, i8** } [[T1]]
}
// CHECK-LABEL: define hidden swiftcc void @"$s22class_bounded_generics0a1_B16_protocol_method{{[_0-9a-zA-Z]*}}F"(%objc_object*, i8**) {{.*}} {
func class_bounded_protocol_method(_ x: ClassBound) {
x.classBoundMethod()
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_getObjectType(%objc_object* %0)
// CHECK: [[WITNESS_GEP:%.*]] = getelementptr inbounds i8*, i8** [[WITNESS_TABLE:%.*]], i32 1
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_GEP]], align 8
// CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] to void (%objc_object*, %swift.type*, i8**)
// CHECK: call swiftcc void [[WITNESS_FN]](%objc_object* swiftself %0, %swift.type* [[METADATA]], i8** [[WITNESS_TABLE]])
}
// CHECK-LABEL: define hidden swiftcc %T22class_bounded_generics13ConcreteClassC* @"$s22class_bounded_generics0a1_B15_archetype_cast{{[_0-9a-zA-Z]*}}F"(%objc_object*, %swift.type* %T, i8** %T.ClassBound)
func class_bounded_archetype_cast<T : ClassBound>(_ x: T) -> ConcreteClass {
return x as! ConcreteClass
// CHECK: [[IN_PTR:%.*]] = bitcast %objc_object* {{%.*}} to i8*
// CHECK: [[T0R:%.*]] = call swiftcc %swift.metadata_response @"$s22class_bounded_generics13ConcreteClassCMa"([[INT]] 0)
// CHECK: [[T0:%.*]] = extractvalue %swift.metadata_response [[T0R]], 0
// CHECK: [[T1:%.*]] = bitcast %swift.type* [[T0]] to i8*
// CHECK: [[OUT_PTR:%.*]] = call i8* @swift_dynamicCastClassUnconditional(i8* [[IN_PTR]], i8* [[T1]])
// CHECK: [[OUT:%.*]] = bitcast i8* [[OUT_PTR]] to %T22class_bounded_generics13ConcreteClassC*
// CHECK: ret %T22class_bounded_generics13ConcreteClassC* [[OUT]]
}
// CHECK-LABEL: define hidden swiftcc %T22class_bounded_generics13ConcreteClassC* @"$s22class_bounded_generics0a1_B14_protocol_cast{{[_0-9a-zA-Z]*}}F"(%objc_object*, i8**)
func class_bounded_protocol_cast(_ x: ClassBound) -> ConcreteClass {
return x as! ConcreteClass
// CHECK: [[IN_PTR:%.*]] = bitcast %objc_object* {{%.*}} to i8*
// CHECK: [[T0R:%.*]] = call swiftcc %swift.metadata_response @"$s22class_bounded_generics13ConcreteClassCMa"([[INT]] 0)
// CHECK: [[T0:%.*]] = extractvalue %swift.metadata_response [[T0R]], 0
// CHECK: [[T1:%.*]] = bitcast %swift.type* [[T0]] to i8*
// CHECK: [[OUT_PTR:%.*]] = call i8* @swift_dynamicCastClassUnconditional(i8* [[IN_PTR]], i8* [[T1]])
// CHECK: [[OUT:%.*]] = bitcast i8* [[OUT_PTR]] to %T22class_bounded_generics13ConcreteClassC*
// CHECK: ret %T22class_bounded_generics13ConcreteClassC* [[OUT]]
}
// CHECK-LABEL: define hidden swiftcc { %objc_object*, i8** } @"$s22class_bounded_generics0a1_B22_protocol_conversion_{{.*}}"(%objc_object*, i8**, i8**) {{.*}} {
func class_bounded_protocol_conversion_1(_ x: ClassBound & ClassBound2)
-> ClassBound {
return x
}
// CHECK-LABEL: define hidden swiftcc { %objc_object*, i8** } @"$s22class_bounded_generics0a1_B22_protocol_conversion_{{.*}}"(%objc_object*, i8**, i8**) {{.*}} {
func class_bounded_protocol_conversion_2(_ x: ClassBound & ClassBound2)
-> ClassBound2 {
return x
}
// CHECK-LABEL: define hidden swiftcc { %objc_object*, i8** } @"$s22class_bounded_generics05objc_a1_B22_protocol_conversion_{{.*}}"(%objc_object*, i8**) {{.*}} {
func objc_class_bounded_protocol_conversion_1
(_ x: ClassBound & ObjCClassBound) -> ClassBound {
return x
}
// CHECK-LABEL: define hidden swiftcc %objc_object* @"$s22class_bounded_generics05objc_a1_B22_protocol_conversion_{{.*}}"(%objc_object*, i8**) {{.*}} {
func objc_class_bounded_protocol_conversion_2
(_ x: ClassBound & ObjCClassBound) -> ObjCClassBound {
return x
}
// CHECK-LABEL: define hidden swiftcc %objc_object* @"$s22class_bounded_generics05objc_a1_B22_protocol_conversion_{{.*}}"(%objc_object*)
func objc_class_bounded_protocol_conversion_3
(_ x: ObjCClassBound & ObjCClassBound2) -> ObjCClassBound {
return x
}
// CHECK-LABEL: define hidden swiftcc %objc_object* @"$s22class_bounded_generics05objc_a1_B22_protocol_conversion_{{.*}}"(%objc_object*)
func objc_class_bounded_protocol_conversion_4
(_ x: ObjCClassBound & ObjCClassBound2) -> ObjCClassBound2 {
return x
}
// CHECK-LABEL: define hidden swiftcc { i64, %objc_object*, i64 } @"$s22class_bounded_generics0A28_generic_field_struct_fields{{[_0-9a-zA-Z]*}}F"(i64, %objc_object*, i64, %swift.type* %T, i8** %T.ClassBound)
func class_generic_field_struct_fields<T>
(_ x:ClassGenericFieldStruct<T>) -> (Int, T, Int) {
return (x.x, x.y, x.z)
}
// CHECK-LABEL: define hidden swiftcc { i64, %objc_object*, i8**, i64 } @"$s22class_bounded_generics0A29_protocol_field_struct_fields{{[_0-9a-zA-Z]*}}F"(i64, %objc_object*, i8**, i64)
func class_protocol_field_struct_fields
(_ x:ClassProtocolFieldStruct) -> (Int, ClassBound, Int) {
return (x.x, x.y, x.z)
}
// CHECK-LABEL: define hidden swiftcc { i64, %objc_object*, i64 } @"$s22class_bounded_generics0a15_generic_field_A7_fields{{[_0-9a-zA-Z]*}}F"(%T22class_bounded_generics017ClassGenericFieldD0C*)
func class_generic_field_class_fields<T>
(_ x:ClassGenericFieldClass<T>) -> (Int, T, Int) {
return (x.x, x.y, x.z)
// CHECK: getelementptr inbounds %T22class_bounded_generics017ClassGenericFieldD0C, %T22class_bounded_generics017ClassGenericFieldD0C* %0, i32 0, i32 1
// CHECK: getelementptr inbounds %T22class_bounded_generics017ClassGenericFieldD0C, %T22class_bounded_generics017ClassGenericFieldD0C* %0, i32 0, i32 2
// CHECK: getelementptr inbounds %T22class_bounded_generics017ClassGenericFieldD0C, %T22class_bounded_generics017ClassGenericFieldD0C* %0, i32 0, i32 3
}
// CHECK-LABEL: define hidden swiftcc { i64, %objc_object*, i8**, i64 } @"$s22class_bounded_generics0a16_protocol_field_A7_fields{{[_0-9a-zA-Z]*}}F"(%T22class_bounded_generics018ClassProtocolFieldD0C*)
func class_protocol_field_class_fields(_ x: ClassProtocolFieldClass)
-> (Int, ClassBound, Int) {
return (x.x, x.y, x.z)
// CHECK: = call swiftcc i64 %{{[0-9]+}}
// CHECK: = call swiftcc { %objc_object*, i8** } %{{[0-9]+}}
// CHECK: = call swiftcc i64 %{{[0-9]+}}
}
class SomeSwiftClass {
class func foo() {}
}
// T must have a Swift layout, so we can load this metatype with a direct access.
// CHECK-LABEL: define hidden swiftcc void @"$s22class_bounded_generics0a1_B9_metatype{{[_0-9a-zA-Z]*}}F"
// CHECK: [[T0:%.*]] = getelementptr inbounds %T22class_bounded_generics14SomeSwiftClassC, %T22class_bounded_generics14SomeSwiftClassC* {{%.*}}, i32 0, i32 0, i32 0
// CHECK-NEXT: [[T1:%.*]] = load %swift.type*, %swift.type** [[T0]], align 8
// CHECK-NEXT: [[T2:%.*]] = bitcast %swift.type* [[T1]] to void (%swift.type*)**
// CHECK-NEXT: [[T3:%.*]] = getelementptr inbounds void (%swift.type*)*, void (%swift.type*)** [[T2]], i64 10
// CHECK-NEXT: load void (%swift.type*)*, void (%swift.type*)** [[T3]], align 8
func class_bounded_metatype<T: SomeSwiftClass>(_ t : T) {
type(of: t).foo()
}
class WeakRef<T: AnyObject> {
weak var value: T?
}
class A<T> {
required init() {}
}
class M<T, S: A<T>> {
private var s: S
init() {
// Don't crash generating the reference to 's'.
s = S.init()
}
}
// CHECK-LABEL: define hidden swiftcc void @"$s22class_bounded_generics14takes_metatypeyyxmlF"(%swift.type*, %swift.type* %T)
func takes_metatype<T>(_: T.Type) {}
// CHECK-LABEL: define hidden swiftcc void @"$s22class_bounded_generics023archetype_with_generic_A11_constraint1tyx_tAA1ACyq_GRbzr0_lF"(%T22class_bounded_generics1AC.1*, %swift.type* %T)
// CHECK: [[ISA_ADDR:%.*]] = bitcast %T22class_bounded_generics1AC.1* %0 to %swift.type**
// CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]]
// CHECK: call swiftcc void @"$s22class_bounded_generics14takes_metatypeyyxmlF"(%swift.type* %T, %swift.type* %T)
// CHECK-NEXT: [[ISA_PTR:%.*]] = bitcast %swift.type* [[ISA]] to %swift.type**
// CHECK-NEXT: [[U_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[ISA_PTR]], i64 10
// CHECK-NEXT: [[U:%.*]] = load %swift.type*, %swift.type** [[U_ADDR]]
// CHECK: call swiftcc void @"$s22class_bounded_generics14takes_metatypeyyxmlF"(%swift.type* %U, %swift.type* %U)
// CHECK: ret void
func archetype_with_generic_class_constraint<T, U>(t: T) where T : A<U> {
takes_metatype(T.self)
takes_metatype(U.self)
}
// CHECK-LABEL: define hidden swiftcc void @"$s22class_bounded_generics029calls_archetype_with_generic_A11_constraint1ayAA1ACyxG_tlF"(%T22class_bounded_generics1AC*) #0 {
// CHECK: alloca
// CHECK: memset
// CHECK: [[ISA_ADDR:%.*]] = getelementptr inbounds %T22class_bounded_generics1AC, %T22class_bounded_generics1AC* %0, i32 0, i32 0, i32 0
// CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]]
// CHECK: [[ISA_PTR:%.*]] = bitcast %swift.type* [[ISA]] to %swift.type**
// CHECK-NEXT: [[T_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[ISA_PTR]], i64 10
// CHECK-NEXT: [[T:%.*]] = load %swift.type*, %swift.type** [[T_ADDR]]
// CHECK: [[SELF:%.*]] = bitcast %T22class_bounded_generics1AC* %0 to %T22class_bounded_generics1AC.1*
// CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s22class_bounded_generics1ACMa"([[INT]] 0, %swift.type* [[T]])
// CHECK-NEXT: [[A_OF_T:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: call swiftcc void @"$s22class_bounded_generics023archetype_with_generic_A11_constraint1tyx_tAA1ACyq_GRbzr0_lF"(%T22class_bounded_generics1AC.1* [[SELF]], %swift.type* [[A_OF_T]])
// CHECK: ret void
func calls_archetype_with_generic_class_constraint<T>(a: A<T>) {
archetype_with_generic_class_constraint(t: a)
}
| apache-2.0 |
tkremenek/swift | validation-test/compiler_crashers_fixed/00449-swift-typechecker-validatedecl.swift | 65 | 472 | // 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
// RUN: not %target-swift-frontend %s -typecheck
func g<T>(f: I) {
class C> Void>? = F
class B : C {
private class A : A")
| apache-2.0 |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Utility/DesignatedRequirement.swift | 1 | 2952 | //
// DesignatedRequirement.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Foundation
public func SecRequirement(forURL url: URL) -> SecRequirement? {
var osStatus = noErr
var codeRef: SecStaticCode?
osStatus = SecStaticCodeCreateWithPath(url as CFURL, [], &codeRef)
guard osStatus == noErr, let code = codeRef else {
Log.shared.error(message: "Failed to create static code with path: \(url.path)", category: String(describing: #function))
if let osStatusError = SecCopyErrorMessageString(osStatus, nil) {
Log.shared.error(message: osStatusError as String, category: String(describing: #function))
}
return nil
}
let flags: SecCSFlags = SecCSFlags(rawValue: 0)
var requirementRef: SecRequirement?
osStatus = SecCodeCopyDesignatedRequirement(code, flags, &requirementRef)
guard osStatus == noErr, let requirement = requirementRef else {
Log.shared.error(message: "Failed to copy designated requirement.", category: String(describing: #function))
if let osStatusError = SecCopyErrorMessageString(osStatus, nil) {
Log.shared.error(message: osStatusError as String, category: String(describing: #function))
}
return nil
}
return requirement
}
public func SecRequirementCopyData(forURL url: URL) -> Data? {
guard let requirement = SecRequirement(forURL: url) else {
return nil
}
var osStatus = noErr
let flags: SecCSFlags = SecCSFlags(rawValue: 0)
var requirementDataRef: CFData?
osStatus = SecRequirementCopyData(requirement, flags, &requirementDataRef)
guard osStatus == noErr, let requirementData = requirementDataRef as Data? else {
Log.shared.error(message: "Failed to copy requirement data.", category: String(describing: #function))
if let osStatusError = SecCopyErrorMessageString(osStatus, nil) {
Log.shared.error(message: osStatusError as String, category: String(describing: #function))
}
return nil
}
return requirementData
}
public func SecRequirementCopyString(forURL url: URL) -> String? {
guard let requirement = SecRequirement(forURL: url) else {
return nil
}
var osStatus = noErr
let flags: SecCSFlags = SecCSFlags(rawValue: 0)
var requirementStringRef: CFString?
osStatus = SecRequirementCopyString(requirement, flags, &requirementStringRef)
guard osStatus == noErr, let requirementString = requirementStringRef as String? else {
Log.shared.error(message: "Failed to copy requirement string.", category: String(describing: #function))
if let osStatusError = SecCopyErrorMessageString(osStatus, nil) {
Log.shared.error(message: osStatusError as String, category: String(describing: #function))
}
return nil
}
return requirementString
}
| mit |
kaltura/playkit-ios | Classes/Player/Media/PKMediaEntry+Copying.swift | 1 | 1683 | // ===================================================================================================
// 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
extension PKMediaEntry: NSCopying {
public func copy(with zone: NSZone? = nil) -> Any {
let sources = self.sources?.compactMap{ $0.copy() as? PKMediaSource }
let entry = PKMediaEntry(self.id,
sources: sources,
duration: self.duration)
entry.mediaType = self.mediaType
entry.metadata = self.metadata
entry.name = self.name
entry.externalSubtitles = self.externalSubtitles
entry.thumbnailUrl = self.thumbnailUrl
entry.tags = self.tags
return entry
}
}
extension PKMediaSource: NSCopying {
public func copy(with zone: NSZone? = nil) -> Any {
let source = PKMediaSource(self.id,
contentUrl: self.contentUrl,
mimeType: self.mimeType,
drmData: self.drmData,
mediaFormat: self.mediaFormat)
source.externalSubtitle = self.externalSubtitle
source.contentRequestAdapter = self.contentRequestAdapter
return source
}
}
| agpl-3.0 |
twtstudio/WePeiYang-iOS | WePeiYang/Bicycle/View/BicycleFitnessTrackerViewCell.swift | 1 | 4037 | //
// BicycleFitnessTrackerViewCell.swift
// WePeiYang
//
// Created by Allen X on 12/8/16.
// Copyright © 2016 Qin Yubo. All rights reserved.
//
import Foundation
import Charts
enum TrackerCellType {
case Move(text: String, color: UIColor)
case Exercise(text: String, color: UIColor)
case Stand(text: String, color: UIColor)
}
class BicycleFitnessTrackerViewCell: UITableViewCell, ChartViewDelegate {
var lineChartView: LineChartView!
convenience init(cellType: TrackerCellType) {
self.init()
self.contentView.backgroundColor = .blackColor()
self.selectionStyle = .None
switch cellType {
case .Move(let text, let color):
self.textLabel?.text = text
self.textLabel?.textColor = color
let label = UILabel(text: "450/400 calories", color: .whiteColor())
self.contentView.addSubview(label)
label.snp_makeConstraints {
make in
make.left.equalTo(self.textLabel!)
make.top.equalTo((self.textLabel?.snp_bottom)!).offset(1)
}
case .Exercise(let text, let color):
self.textLabel?.text = text
self.textLabel?.textColor = color
let label = UILabel(text: "45/55 minutes", color: .whiteColor())
self.contentView.addSubview(label)
label.snp_makeConstraints {
make in
make.left.equalTo(self.textLabel!)
make.top.equalTo((self.textLabel?.snp_bottom)!).offset(1)
}
case .Stand(let text, let color):
self.textLabel?.text = text
self.textLabel?.textColor = color
let label = UILabel(text: "10/12 hours", color: .whiteColor())
self.contentView.addSubview(label)
label.snp_makeConstraints {
make in
make.left.equalTo(self.textLabel!)
make.top.equalTo((self.textLabel?.snp_bottom)!).offset(1)
}
}
}
func renderChart() {
self.lineChartView.delegate = self
self.lineChartView.descriptionText = ""
self.lineChartView.noDataTextDescription = "暂无数据可显示"
self.lineChartView.dragEnabled = true;
//X-Axis Limit Line
let llXAxis = ChartLimitLine(limit: 10.0, label: "Index 10")
llXAxis.lineWidth = 4.0
llXAxis.lineDashLengths = [10.0, 10.0, 0.0]
llXAxis.labelPosition = .RightBottom
llXAxis.valueFont = UIFont.systemFontOfSize(10.0)
lineChartView.xAxis.addLimitLine(llXAxis)
//Y-Axis Limit Line
let ll1 = ChartLimitLine(limit: 50.0, label: "Lower Limit")
ll1.lineWidth = 4.0
ll1.lineDashLengths = [5.0, 5.0]
ll1.labelPosition = .RightBottom
ll1.valueFont = UIFont.systemFontOfSize(10.0)
let ll2 = ChartLimitLine(limit: 350.0, label: "Upper Limit")
ll2.lineWidth = 4.0
ll2.lineDashLengths = [5.0, 5.0]
ll2.labelPosition = .RightTop
ll2.valueFont = UIFont.systemFontOfSize(10.0)
let leftAxis = lineChartView.leftAxis
leftAxis.removeAllLimitLines()
leftAxis.addLimitLine(ll1)
leftAxis.addLimitLine(ll2)
leftAxis.axisMaxValue = 500.0
leftAxis.axisMinValue = 0.0
leftAxis.gridLineDashLengths = [5.0, 5.0]
leftAxis.drawZeroLineEnabled = false;
leftAxis.drawLimitLinesBehindDataEnabled = true
lineChartView.rightAxis.enabled = false
lineChartView.legend.form = .Line
lineChartView.animate(xAxisDuration: 2.5, easingOption: .EaseInOutQuart)
}
func setDataCount(count: Int, range: Double) {
var xVals: [String?] = []
for i in 0..<count {
xVals.append("\(i+1)")
}
lineChartView.data?.xVals = xVals
}
func insertData(yVals: [String?]) {
}
}
| mit |
treejames/firefox-ios | Client/Application/AppDelegate.swift | 3 | 11686 | /* 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 Shared
import Storage
import AVFoundation
import XCGLogger
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var browserViewController: BrowserViewController!
var rootViewController: UINavigationController!
weak var profile: BrowserProfile?
var tabManager: TabManager!
let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Set the Firefox UA for browsing.
setUserAgent()
// Start the keyboard helper to monitor and cache keyboard state.
KeyboardHelper.defaultHelper.startObserving()
// Create a new sync log file on cold app launch
Logger.syncLogger.newLogWithDate(NSDate())
let profile = getProfile(application)
// Set up a web server that serves us static content. Do this early so that it is ready when the UI is presented.
setUpWebServer(profile)
// for aural progress bar: play even with silent switch on, and do not stop audio from other apps (like music)
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers, error: nil)
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
let defaultRequest = NSURLRequest(URL: UIConstants.AboutHomeURL)
self.tabManager = TabManager(defaultNewTabRequest: defaultRequest, profile: profile)
browserViewController = BrowserViewController(profile: profile, tabManager: self.tabManager)
// Add restoration class, the factory that will return the ViewController we
// will restore with.
browserViewController.restorationIdentifier = NSStringFromClass(BrowserViewController.self)
browserViewController.restorationClass = AppDelegate.self
browserViewController.automaticallyAdjustsScrollViewInsets = false
rootViewController = UINavigationController(rootViewController: browserViewController)
rootViewController.automaticallyAdjustsScrollViewInsets = false
rootViewController.delegate = self
rootViewController.navigationBarHidden = true
self.window!.rootViewController = rootViewController
self.window!.backgroundColor = UIConstants.AppBackgroundColor
activeCrashReporter = BreakpadCrashReporter(breakpadInstance: BreakpadController.sharedInstance())
configureActiveCrashReporter(profile.prefs.boolForKey("crashreports.send.always"))
NSNotificationCenter.defaultCenter().addObserverForName(FSReadingListAddReadingListItemNotification, object: nil, queue: nil) { (notification) -> Void in
if let userInfo = notification.userInfo, url = userInfo["URL"] as? NSURL, absoluteString = url.absoluteString {
let title = (userInfo["Title"] as? String) ?? ""
profile.readingList?.createRecordWithURL(absoluteString, title: title, addedBy: UIDevice.currentDevice().name)
}
}
// check to see if we started 'cos someone tapped on a notification.
if let localNotification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification {
viewURLInNewTab(localNotification)
}
return true
}
/**
* We maintain a weak reference to the profile so that we can pause timed
* syncs when we're backgrounded.
*
* The long-lasting ref to the profile lives in BrowserViewController,
* which we set in application:willFinishLaunchingWithOptions:.
*
* If that ever disappears, we won't be able to grab the profile to stop
* syncing... but in that case the profile's deinit will take care of things.
*/
func getProfile(application: UIApplication) -> Profile {
if let profile = self.profile {
return profile
}
let p = BrowserProfile(localName: "profile", app: application)
self.profile = p
return p
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
self.window!.makeKeyAndVisible()
return true
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
if let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) {
if components.scheme != "firefox" && components.scheme != "firefox-x-callback" {
return false
}
var url: String?
var appName: String?
var callbackScheme: String?
for item in components.queryItems as? [NSURLQueryItem] ?? [] {
switch item.name {
case "url":
url = item.value
case "x-source":
callbackScheme = item.value
case "x-source-name":
appName = item.value
default: ()
}
}
if let url = url,
newURL = NSURL(string: url.unescape()) {
self.browserViewController.openURLInNewTab(newURL)
return true
}
}
return false
}
// We sync in the foreground only, to avoid the possibility of runaway resource usage.
// Eventually we'll sync in response to notifications.
func applicationDidBecomeActive(application: UIApplication) {
self.profile?.syncManager.beginTimedSyncs()
// We could load these here, but then we have to futz with the tab counter
// and making NSURLRequests.
self.browserViewController.loadQueuedTabs()
}
func applicationDidEnterBackground(application: UIApplication) {
self.profile?.syncManager.endTimedSyncs()
let taskId = application.beginBackgroundTaskWithExpirationHandler { _ in }
self.profile?.shutdown()
application.endBackgroundTask(taskId)
}
private func setUpWebServer(profile: Profile) {
let server = WebServer.sharedInstance
ReaderModeHandlers.register(server, profile: profile)
ErrorPageHelper.register(server)
AboutHomeHandler.register(server)
AboutLicenseHandler.register(server)
SessionRestoreHandler.register(server)
server.start()
}
private func setUserAgent() {
// Note that we use defaults here that are readable from extensions, so they
// can just used the cached identifier.
let defaults = NSUserDefaults(suiteName: AppInfo.sharedContainerIdentifier())!
let firefoxUA = UserAgent.defaultUserAgent(defaults)
// Set the UA for WKWebView (via defaults), the favicon fetcher, and the image loader.
// This only needs to be done once per runtime.
defaults.registerDefaults(["UserAgent": firefoxUA])
FaviconFetcher.userAgent = firefoxUA
SDWebImageDownloader.sharedDownloader().setValue(firefoxUA, forHTTPHeaderField: "User-Agent")
}
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) {
if let actionId = identifier {
if let action = SentTabAction(rawValue: actionId) {
viewURLInNewTab(notification)
switch(action) {
case .Bookmark:
addBookmark(notification)
break
case .ReadingList:
addToReadingList(notification)
break
default:
break
}
} else {
println("ERROR: Unknown notification action received")
}
} else {
println("ERROR: Unknown notification received")
}
}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
viewURLInNewTab(notification)
}
private func viewURLInNewTab(notification: UILocalNotification) {
if let alertURL = notification.userInfo?[TabSendURLKey] as? String {
if let urlToOpen = NSURL(string: alertURL) {
browserViewController.openURLInNewTab(urlToOpen)
}
}
}
private func addBookmark(notification: UILocalNotification) {
if let alertURL = notification.userInfo?[TabSendURLKey] as? String,
let title = notification.userInfo?[TabSendTitleKey] as? String {
browserViewController.addBookmark(alertURL, title: title)
}
}
private func addToReadingList(notification: UILocalNotification) {
if let alertURL = notification.userInfo?[TabSendURLKey] as? String,
let title = notification.userInfo?[TabSendTitleKey] as? String {
if let urlToOpen = NSURL(string: alertURL) {
NSNotificationCenter.defaultCenter().postNotificationName(FSReadingListAddReadingListItemNotification, object: self, userInfo: ["URL": urlToOpen, "Title": title])
}
}
}
}
// MARK: - Root View Controller Animations
extension AppDelegate: UINavigationControllerDelegate {
func navigationController(navigationController: UINavigationController,
animationControllerForOperation operation: UINavigationControllerOperation,
fromViewController fromVC: UIViewController,
toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if operation == UINavigationControllerOperation.Push {
return BrowserToTrayAnimator()
} else if operation == UINavigationControllerOperation.Pop {
return TrayToBrowserAnimator()
} else {
return nil
}
}
}
var activeCrashReporter: CrashReporter?
func configureActiveCrashReporter(optedIn: Bool?) {
if let reporter = activeCrashReporter {
configureCrashReporter(reporter, optedIn: optedIn)
}
}
public func configureCrashReporter(reporter: CrashReporter, #optedIn: Bool?) {
let configureReporter: () -> () = {
let addUploadParameterForKey: String -> Void = { key in
if let value = NSBundle.mainBundle().objectForInfoDictionaryKey(key) as? String {
reporter.addUploadParameter(value, forKey: key)
}
}
addUploadParameterForKey("AppID")
addUploadParameterForKey("BuildID")
addUploadParameterForKey("ReleaseChannel")
addUploadParameterForKey("Vendor")
}
if let optedIn = optedIn {
// User has explicitly opted-in for sending crash reports. If this is not true, then the user has
// explicitly opted-out of crash reporting so don't bother starting breakpad or stop if it was running
if optedIn {
reporter.start(true)
configureReporter()
reporter.setUploadingEnabled(true)
} else {
reporter.stop()
}
}
// We haven't asked the user for their crash reporting preference yet. Log crashes anyways but don't send them.
else {
reporter.start(true)
configureReporter()
}
}
| mpl-2.0 |
kzaher/RxSwift | RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift | 5 | 1346 | //
// RxTabBarDelegateProxy.swift
// RxCocoa
//
// Created by Jesse Farless on 5/14/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
import RxSwift
extension UITabBar: HasDelegate {
public typealias Delegate = UITabBarDelegate
}
/// For more information take a look at `DelegateProxyType`.
open class RxTabBarDelegateProxy
: DelegateProxy<UITabBar, UITabBarDelegate>
, DelegateProxyType
, UITabBarDelegate {
/// Typed parent object.
public weak private(set) var tabBar: UITabBar?
/// - parameter tabBar: Parent object for delegate proxy.
public init(tabBar: ParentObject) {
self.tabBar = tabBar
super.init(parentObject: tabBar, delegateProxy: RxTabBarDelegateProxy.self)
}
// Register known implementations
public static func registerKnownImplementations() {
self.register { RxTabBarDelegateProxy(tabBar: $0) }
}
/// For more information take a look at `DelegateProxyType`.
open class func currentDelegate(for object: ParentObject) -> UITabBarDelegate? {
object.delegate
}
/// For more information take a look at `DelegateProxyType`.
open class func setCurrentDelegate(_ delegate: UITabBarDelegate?, to object: ParentObject) {
object.delegate = delegate
}
}
#endif
| mit |
niunaruto/DeDaoAppSwift | testSwift/Pods/Kingfisher/Sources/Cache/Storage.swift | 4 | 3238 | //
// Storage.swift
// Kingfisher
//
// Created by Wei Wang on 2018/10/15.
//
// Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// Represents the expiration strategy used in storage.
///
/// - never: The item never expires.
/// - seconds: The item expires after a time duration of given seconds from now.
/// - days: The item expires after a time duration of given days from now.
/// - date: The item expires after a given date.
public enum StorageExpiration {
/// The item never expires.
case never
/// The item expires after a time duration of given seconds from now.
case seconds(TimeInterval)
/// The item expires after a time duration of given days from now.
case days(Int)
/// The item expires after a given date.
case date(Date)
/// Indicates the item is already expired. Use this to skip cache.
case expired
func estimatedExpirationSince(_ date: Date) -> Date {
switch self {
case .never: return .distantFuture
case .seconds(let seconds): return date.addingTimeInterval(seconds)
case .days(let days): return date.addingTimeInterval(TimeInterval(60 * 60 * 24 * days))
case .date(let ref): return ref
case .expired: return .distantPast
}
}
var estimatedExpirationSinceNow: Date {
return estimatedExpirationSince(Date())
}
var isExpired: Bool {
return timeInterval <= 0
}
var timeInterval: TimeInterval {
switch self {
case .never: return .infinity
case .seconds(let seconds): return seconds
case .days(let days): return TimeInterval(60 * 60 * 24 * days)
case .date(let ref): return ref.timeIntervalSinceNow
case .expired: return -(.infinity)
}
}
}
/// Represents types which cost in memory can be calculated.
public protocol CacheCostCalculable {
var cacheCost: Int { get }
}
/// Represents types which can be converted to and from data.
public protocol DataTransformable {
func toData() throws -> Data
static func fromData(_ data: Data) throws -> Self
static var empty: Self { get }
}
| mit |
algal/TouchVisualizer | TouchVisualizer/ForcePropertiesGestureRecognizer/ALGInitialTouchGestureRecognizer.swift | 1 | 5664 | //
// MonotouchGestureRecognizer.swift
// TouchVisualizer
//
// Created by Alexis Gallagher on 2015-10-30.
// Copyright © 2015 Alexis Gallagher. All rights reserved.
//
import UIKit.UIGestureRecognizerSubclass
/**
This recognizes an "initial touch sequence", which is essentially the part of a multitouch sequence that concerns only the single finger which initiated it.
Given a valid multitouch sequence, that multitouch sequence contains an initial touch sequence if and only if it begins with a single-finger touch. The initial touch sequence then consists only of `UITouch`s instance values representing that finger. It ends when that finger leaves the screen or when the entire multitouch sequence is cancelled.
Some valid multitouch sequences do not contain initial touch sequences -- for instance, if the multitouch sequence begins with 2 or more simultaneous touches.
Some multitouch sequences outlast their initial touch sequence, for instance, if the multitouch sequence begins with one finger, adds a second finger, removes the first finger, and then moves the second finger, then only the first three actions constitute an initial touch sequence.
When it calls its action method, the property `currentTouch` will be populated with the `UITouch` object of the initial touch sequence
*/
class ALGInitialTouchSequenceGestureRecognizer: UIGestureRecognizer
{
fileprivate enum ExtendedState {
case possible,began(UITouch),failed,changed(UITouch),ended(UITouch),canceled(UITouch)
}
/// contains the `UITouch` object, and will be non-nil whenever the receiver fires its action callback
var currentTouch:UITouch? {
switch self.extendedState {
case .possible,.failed: return nil
case .began(let touch): return touch
case .changed(let touch): return touch
case .ended(let touch): return touch
case .canceled(let touch): return touch
}
}
fileprivate var extendedState:ExtendedState = .possible { didSet {
switch extendedState {
case .possible: self.state = .possible
case .failed: self.state = .failed
case .began(_): self.state = .began
case .changed(_): self.state = .changed
case .ended(_): self.state = .ended
case .canceled(_): self.state = .cancelled
}
}
}
fileprivate func touchesWithAction(_ touches: Set<UITouch>, withEvent event: UIEvent, phase:UITouchPhase)
{
switch (self.extendedState,phase)
{
// assert: .Possible -> [.Began,.Failed]
case (.possible, UITouchPhase.began):
if touches.count == 1 {
self.extendedState = .began(touches.first!)
}
else {
// ignore multitouch sequences which begin with more than two simultaneous touches
self.extendedState = .failed
}
case (.possible, _):
assertionFailure("unexpected call to non-touchesBegan when UIGestureRecognizer was in .Possible state")
self.extendedState = .failed
break
// assert: .Began -> [.Changed]
case (.began(let currentTouch),_):
self.extendedState = .changed(currentTouch)
// assert: .Changes -> [.Changed, .Canceled, .Ended]
case (.changed(let touch), .began):
// if a touch began, it must not be the touch we are recognizing which already began
for irrelevantTouch in touches.filter({ $0 != touch }) {
self.ignore(irrelevantTouch, for: event)
}
case (.changed(let touch),.moved) where touches.contains(touch):
self.extendedState = .changed(touch)
case (.changed(let touch),.stationary) where touches.contains(touch):
self.extendedState = .changed(touch)
case (.changed(let touch),.ended) where touches.contains(touch):
self.extendedState = .ended(touch)
case (.changed(let touch),.cancelled) where touches.contains(touch):
self.extendedState = .canceled(touch)
case (.changed(let touch),_) where !touches.contains(touch):
// NSLog("touches%@ called a Changed gesture recognizer with an ignored touch. Event: %@",method.description,event)
break
case (.changed(_),let phase):
assertionFailure("Should be unreachable")
NSLog("unexpected call to touches\(phase.description) for this event \(event)")
break
// assert: no transition requirements from .Failed, .Ended, .Canceled
case (.failed,_): fallthrough
case (.ended(_),_): fallthrough
case (.canceled(_),_):
break
}
}
//
// MARK: overrides
//
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesBegan(touches, with: event)
self.touchesWithAction(touches, withEvent: event, phase: .began)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesMoved(touches, with: event)
self.touchesWithAction(touches, withEvent: event, phase: .moved)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesEnded(touches, with: event)
self.touchesWithAction(touches, withEvent: event, phase: .ended)
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesCancelled(touches, with: event)
self.touchesWithAction(touches, withEvent: event, phase: .cancelled)
}
override func reset() {
super.reset()
self.extendedState = .possible
}
}
// MARK: logging
extension UITouchPhase {
var description:String {
switch self {
case .began: return "Began"
case .cancelled: return "Cancelled"
case .ended: return "Ended"
case .moved: return "Moved"
case .stationary: return "Stationary"
}
}
}
| mit |
lorentey/swift | validation-test/compiler_crashers_fixed/13737-swift-availabilityattr-isunavailable.swift | 65 | 457 | // 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
// RUN: not %target-swift-frontend %s -typecheck
class C<T{enum S<T{let a{{}enum A:a{protocol a{func a((T.e
| apache-2.0 |
haitran2011/Rocket.Chat.iOS | Rocket.Chat/Managers/LogManager.swift | 2 | 299 | //
// LogManager.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/6/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import Foundation
final class Log {
static func debug(_ text: String?) {
guard let text = text else { return }
print(text)
}
}
| mit |
Candyroot/DesignPattern | factory/factory/RedPepper.swift | 1 | 184 | //
// RedPepper.swift
// factory
//
// Created by Bing Liu on 11/3/14.
// Copyright (c) 2014 UnixOSS. All rights reserved.
//
import Foundation
class RedPepper: Veggies {
}
| apache-2.0 |
brightify/torch | Source/Property/PropertyArrayType.swift | 1 | 452 | //
// PropertyArrayType.swift
// Torch
//
// Created by Filip Dolnik on 22.07.16.
// Copyright © 2016 Brightify. All rights reserved.
//
// TODO Refactor if needed
public protocol PropertyArrayType: PropertyType {
associatedtype Element
var values: [Element] { get }
subscript(index: Int) -> Element { get set }
}
extension Array: PropertyArrayType {
public var values: [Element] {
return self
}
} | mit |
Ranxan/NetworkService | Example/NetworkService/ViewController.swift | 1 | 557 | //
// ViewController.swift
// NetworkService
//
// Created by Ranxan on 06/12/2017.
// Copyright (c) 2017 Ranxan. All rights reserved.
//
import UIKit
import NetworkService
class ViewController: UIViewController {
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.
}
func callAPIForList() {
}
}
| mit |
gregomni/swift | validation-test/compiler_crashers_fixed/00228-swift-clangimporter-loadextensions.swift | 3 | 764 | // 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
// RUN: not %target-swift-frontend %s -typecheck -requirement-machine-inferred-signatures=on
func s() -> o {
r q {
}
protocol p {
typealias m = q
}
m r : p {
}
func r<s : t, o : p where o.m == s> (s: o) {
}
func r<s : p where s.m == s> (s: s) {
}
m s<p : u> {
}
class t<s : s, r : s where s.t == r> : q {
}
class t<s, r> {
}
protocol s {
func r() {
}
}
func t(s) -> <p>(() -> p) {
}
class q<m : t
| apache-2.0 |
agrippa1994/iOS-PLC | Pods/Charts/Charts/Classes/Renderers/LineChartRenderer.swift | 4 | 25085 | //
// LineChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
@objc
public protocol LineChartRendererDelegate
{
func lineChartRendererData(renderer: LineChartRenderer) -> LineChartData!
func lineChartRenderer(renderer: LineChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer!
func lineChartRendererFillFormatter(renderer: LineChartRenderer) -> ChartFillFormatter
func lineChartDefaultRendererValueFormatter(renderer: LineChartRenderer) -> NSNumberFormatter!
func lineChartRendererChartYMax(renderer: LineChartRenderer) -> Double
func lineChartRendererChartYMin(renderer: LineChartRenderer) -> Double
func lineChartRendererChartXMax(renderer: LineChartRenderer) -> Double
func lineChartRendererChartXMin(renderer: LineChartRenderer) -> Double
func lineChartRendererMaxVisibleValueCount(renderer: LineChartRenderer) -> Int
}
public class LineChartRenderer: LineScatterCandleRadarChartRenderer
{
public weak var delegate: LineChartRendererDelegate?
public init(delegate: LineChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.delegate = delegate
}
public override func drawData(context context: CGContext?)
{
let lineData = delegate!.lineChartRendererData(self)
if (lineData === nil)
{
return
}
for (var i = 0; i < lineData.dataSetCount; i++)
{
let set = lineData.getDataSetByIndex(i)
if (set !== nil && set!.isVisible)
{
drawDataSet(context: context, dataSet: set as! LineChartDataSet)
}
}
}
internal struct CGCPoint
{
internal var x: CGFloat = 0.0
internal var y: CGFloat = 0.0
/// x-axis distance
internal var dx: CGFloat = 0.0
/// y-axis distance
internal var dy: CGFloat = 0.0
internal init(x: CGFloat, y: CGFloat)
{
self.x = x
self.y = y
}
}
internal func drawDataSet(context context: CGContext?, dataSet: LineChartDataSet)
{
let entries = dataSet.yVals
if (entries.count < 1)
{
return
}
CGContextSaveGState(context)
CGContextSetLineWidth(context, dataSet.lineWidth)
if (dataSet.lineDashLengths != nil)
{
CGContextSetLineDash(context, dataSet.lineDashPhase, dataSet.lineDashLengths, dataSet.lineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
// if drawing cubic lines is enabled
if (dataSet.isDrawCubicEnabled)
{
drawCubic(context: context, dataSet: dataSet, entries: entries)
}
else
{ // draw normal (straight) lines
drawLinear(context: context, dataSet: dataSet, entries: entries)
}
CGContextRestoreGState(context)
}
internal func drawCubic(context context: CGContext?, dataSet: LineChartDataSet, entries: [ChartDataEntry])
{
let trans = delegate?.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency)
let entryFrom = dataSet.entryForXIndex(_minX)
let entryTo = dataSet.entryForXIndex(_maxX)
let minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0)
let maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count)
let phaseX = _animator.phaseX
let phaseY = _animator.phaseY
// get the color that is specified for this position from the DataSet
let drawingColor = dataSet.colors.first!
let intensity = dataSet.cubicIntensity
// the path for the cubic-spline
let cubicPath = CGPathCreateMutable()
var valueToPixelMatrix = trans!.valueToPixelMatrix
let size = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx)))
if (size - minx >= 2)
{
var prevDx: CGFloat = 0.0
var prevDy: CGFloat = 0.0
var curDx: CGFloat = 0.0
var curDy: CGFloat = 0.0
var prevPrev = entries[minx]
var prev = entries[minx]
var cur = entries[minx]
var next = entries[minx + 1]
// let the spline start
CGPathMoveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY)
prevDx = CGFloat(cur.xIndex - prev.xIndex) * intensity
prevDy = CGFloat(cur.value - prev.value) * intensity
curDx = CGFloat(next.xIndex - cur.xIndex) * intensity
curDy = CGFloat(next.value - cur.value) * intensity
// the first cubic
CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix,
CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY,
CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY,
CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY)
for (var j = minx + 1, count = min(size, entries.count - 1); j < count; j++)
{
prevPrev = entries[j == 1 ? 0 : j - 2]
prev = entries[j - 1]
cur = entries[j]
next = entries[j + 1]
prevDx = CGFloat(cur.xIndex - prevPrev.xIndex) * intensity
prevDy = CGFloat(cur.value - prevPrev.value) * intensity
curDx = CGFloat(next.xIndex - prev.xIndex) * intensity
curDy = CGFloat(next.value - prev.value) * intensity
CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY,
CGFloat(cur.xIndex) - curDx,
(CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY)
}
if (size > entries.count - 1)
{
prevPrev = entries[entries.count - (entries.count >= 3 ? 3 : 2)]
prev = entries[entries.count - 2]
cur = entries[entries.count - 1]
next = cur
prevDx = CGFloat(cur.xIndex - prevPrev.xIndex) * intensity
prevDy = CGFloat(cur.value - prevPrev.value) * intensity
curDx = CGFloat(next.xIndex - prev.xIndex) * intensity
curDy = CGFloat(next.value - prev.value) * intensity
// the last cubic
CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY,
CGFloat(cur.xIndex) - curDx,
(CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY)
}
}
CGContextSaveGState(context)
if (dataSet.isDrawFilledEnabled)
{
drawCubicFill(context: context, dataSet: dataSet, spline: cubicPath, matrix: valueToPixelMatrix, from: minx, to: size)
}
CGContextBeginPath(context)
CGContextAddPath(context, cubicPath)
CGContextSetStrokeColorWithColor(context, drawingColor.CGColor)
CGContextStrokePath(context)
CGContextRestoreGState(context)
}
internal func drawCubicFill(context context: CGContext?, dataSet: LineChartDataSet, spline: CGMutablePath, matrix: CGAffineTransform, from: Int, to: Int)
{
CGContextSaveGState(context)
let fillMin = delegate!.lineChartRendererFillFormatter(self).getFillLinePosition(
dataSet: dataSet,
data: delegate!.lineChartRendererData(self),
chartMaxY: delegate!.lineChartRendererChartYMax(self),
chartMinY: delegate!.lineChartRendererChartYMin(self))
var pt1 = CGPoint(x: CGFloat(to - 1), y: fillMin)
var pt2 = CGPoint(x: CGFloat(from), y: fillMin)
pt1 = CGPointApplyAffineTransform(pt1, matrix)
pt2 = CGPointApplyAffineTransform(pt2, matrix)
CGContextBeginPath(context)
CGContextAddPath(context, spline)
CGContextAddLineToPoint(context, pt1.x, pt1.y)
CGContextAddLineToPoint(context, pt2.x, pt2.y)
CGContextClosePath(context)
CGContextSetFillColorWithColor(context, dataSet.fillColor.CGColor)
CGContextSetAlpha(context, dataSet.fillAlpha)
CGContextFillPath(context)
CGContextRestoreGState(context)
}
private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint())
internal func drawLinear(context context: CGContext?, dataSet: LineChartDataSet, entries: [ChartDataEntry])
{
let trans = delegate!.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
let phaseX = _animator.phaseX
let phaseY = _animator.phaseY
CGContextSaveGState(context)
let entryFrom = dataSet.entryForXIndex(_minX)
let entryTo = dataSet.entryForXIndex(_maxX)
let minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0)
let maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count)
// more than 1 color
if (dataSet.colors.count > 1)
{
if (_lineSegments.count != 2)
{
_lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint())
}
for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++)
{
if (count > 1 && j == count - 1)
{ // Last point, we have already drawn a line to this point
break
}
var e = entries[j]
_lineSegments[0].x = CGFloat(e.xIndex)
_lineSegments[0].y = CGFloat(e.value) * phaseY
_lineSegments[0] = CGPointApplyAffineTransform(_lineSegments[0], valueToPixelMatrix)
if (j + 1 < count)
{
e = entries[j + 1]
_lineSegments[1].x = CGFloat(e.xIndex)
_lineSegments[1].y = CGFloat(e.value) * phaseY
_lineSegments[1] = CGPointApplyAffineTransform(_lineSegments[1], valueToPixelMatrix)
}
else
{
_lineSegments[1] = _lineSegments[0]
}
if (!viewPortHandler.isInBoundsRight(_lineSegments[0].x))
{
break
}
// make sure the lines don't do shitty things outside bounds
if (!viewPortHandler.isInBoundsLeft(_lineSegments[1].x)
|| (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y))
|| (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y)))
{
continue
}
// get the color that is set for this line-segment
CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor)
CGContextStrokeLineSegments(context, _lineSegments, 2)
}
}
else
{ // only one color per dataset
var e1: ChartDataEntry!
var e2: ChartDataEntry!
if (_lineSegments.count != max((entries.count - 1) * 2, 2))
{
_lineSegments = [CGPoint](count: max((entries.count - 1) * 2, 2), repeatedValue: CGPoint())
}
e1 = entries[minx]
let count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx)))
for (var x = count > 1 ? minx + 1 : minx, j = 0; x < count; x++)
{
e1 = entries[x == 0 ? 0 : (x - 1)]
e2 = entries[x]
_lineSegments[j++] = CGPointApplyAffineTransform(CGPoint(x: CGFloat(e1.xIndex), y: CGFloat(e1.value) * phaseY), valueToPixelMatrix)
_lineSegments[j++] = CGPointApplyAffineTransform(CGPoint(x: CGFloat(e2.xIndex), y: CGFloat(e2.value) * phaseY), valueToPixelMatrix)
}
let size = max((count - minx - 1) * 2, 2)
CGContextSetStrokeColorWithColor(context, dataSet.colorAt(0).CGColor)
CGContextStrokeLineSegments(context, _lineSegments, size)
}
CGContextRestoreGState(context)
// if drawing filled is enabled
if (dataSet.isDrawFilledEnabled && entries.count > 0)
{
drawLinearFill(context: context, dataSet: dataSet, entries: entries, minx: minx, maxx: maxx, trans: trans)
}
}
internal func drawLinearFill(context context: CGContext?, dataSet: LineChartDataSet, entries: [ChartDataEntry], minx: Int, maxx: Int, trans: ChartTransformer)
{
CGContextSaveGState(context)
CGContextSetFillColorWithColor(context, dataSet.fillColor.CGColor)
// filled is usually drawn with less alpha
CGContextSetAlpha(context, dataSet.fillAlpha)
let filled = generateFilledPath(
entries,
fillMin: delegate!.lineChartRendererFillFormatter(self).getFillLinePosition(
dataSet: dataSet,
data: delegate!.lineChartRendererData(self),
chartMaxY: delegate!.lineChartRendererChartYMax(self),
chartMinY: delegate!.lineChartRendererChartYMin(self)),
from: minx,
to: maxx,
matrix: trans.valueToPixelMatrix)
CGContextBeginPath(context)
CGContextAddPath(context, filled)
CGContextFillPath(context)
CGContextRestoreGState(context)
}
/// Generates the path that is used for filled drawing.
private func generateFilledPath(entries: [ChartDataEntry], fillMin: CGFloat, from: Int, to: Int, var matrix: CGAffineTransform) -> CGPath
{
let phaseX = _animator.phaseX
let phaseY = _animator.phaseY
let filled = CGPathCreateMutable()
CGPathMoveToPoint(filled, &matrix, CGFloat(entries[from].xIndex), fillMin)
CGPathAddLineToPoint(filled, &matrix, CGFloat(entries[from].xIndex), CGFloat(entries[from].value) * phaseY)
// create a new path
for (var x = from + 1, count = Int(ceil(CGFloat(to - from) * phaseX + CGFloat(from))); x < count; x++)
{
let e = entries[x]
CGPathAddLineToPoint(filled, &matrix, CGFloat(e.xIndex), CGFloat(e.value) * phaseY)
}
// close up
CGPathAddLineToPoint(filled, &matrix, CGFloat(entries[max(min(Int(ceil(CGFloat(to - from) * phaseX + CGFloat(from))) - 1, entries.count - 1), 0)].xIndex), fillMin)
CGPathCloseSubpath(filled)
return filled
}
public override func drawValues(context context: CGContext?)
{
let lineData = delegate!.lineChartRendererData(self)
if (lineData === nil)
{
return
}
let defaultValueFormatter = delegate!.lineChartDefaultRendererValueFormatter(self)
if (CGFloat(lineData.yValCount) < CGFloat(delegate!.lineChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX)
{
var dataSets = lineData.dataSets
for (var i = 0; i < dataSets.count; i++)
{
let dataSet = dataSets[i] as! LineChartDataSet
if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0
{
continue
}
let valueFont = dataSet.valueFont
let valueTextColor = dataSet.valueTextColor
var formatter = dataSet.valueFormatter
if (formatter === nil)
{
formatter = defaultValueFormatter
}
let trans = delegate!.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency)
// make sure the values do not interfear with the circles
var valOffset = Int(dataSet.circleRadius * 1.75)
if (!dataSet.isDrawCirclesEnabled)
{
valOffset = valOffset / 2
}
var entries = dataSet.yVals
let entryFrom = dataSet.entryForXIndex(_minX)
let entryTo = dataSet.entryForXIndex(_maxX)
let minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0)
let maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count)
var positions = trans.generateTransformedValuesLine(
entries,
phaseX: _animator.phaseX,
phaseY: _animator.phaseY,
from: minx,
to: maxx)
for (var j = 0, count = positions.count; j < count; j++)
{
if (!viewPortHandler.isInBoundsRight(positions[j].x))
{
break
}
if (!viewPortHandler.isInBoundsLeft(positions[j].x) || !viewPortHandler.isInBoundsY(positions[j].y))
{
continue
}
let val = entries[j + minx].value
ChartUtils.drawText(context: context, text: formatter!.stringFromNumber(val)!, point: CGPoint(x: positions[j].x, y: positions[j].y - CGFloat(valOffset) - valueFont.lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor])
}
}
}
}
public override func drawExtras(context context: CGContext?)
{
drawCircles(context: context)
}
private func drawCircles(context context: CGContext?)
{
let phaseX = _animator.phaseX
let phaseY = _animator.phaseY
let lineData = delegate!.lineChartRendererData(self)
let dataSets = lineData.dataSets
var pt = CGPoint()
var rect = CGRect()
CGContextSaveGState(context)
for (var i = 0, count = dataSets.count; i < count; i++)
{
let dataSet = lineData.getDataSetByIndex(i) as! LineChartDataSet!
if (!dataSet.isVisible || !dataSet.isDrawCirclesEnabled)
{
continue
}
let trans = delegate!.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
var entries = dataSet.yVals
let circleRadius = dataSet.circleRadius
let circleDiameter = circleRadius * 2.0
let circleHoleDiameter = circleRadius
let circleHoleRadius = circleHoleDiameter / 2.0
let isDrawCircleHoleEnabled = dataSet.isDrawCircleHoleEnabled
let entryFrom = dataSet.entryForXIndex(_minX)!
let entryTo = dataSet.entryForXIndex(_maxX)!
let minx = max(dataSet.entryIndex(entry: entryFrom, isEqual: true), 0)
let maxx = min(dataSet.entryIndex(entry: entryTo, isEqual: true) + 1, entries.count)
for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++)
{
let e = entries[j]
pt.x = CGFloat(e.xIndex)
pt.y = CGFloat(e.value) * phaseY
pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix)
if (!viewPortHandler.isInBoundsRight(pt.x))
{
break
}
// make sure the circles don't do shitty things outside bounds
if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y))
{
continue
}
CGContextSetFillColorWithColor(context, dataSet.getCircleColor(j)!.CGColor)
rect.origin.x = pt.x - circleRadius
rect.origin.y = pt.y - circleRadius
rect.size.width = circleDiameter
rect.size.height = circleDiameter
CGContextFillEllipseInRect(context, rect)
if (isDrawCircleHoleEnabled)
{
CGContextSetFillColorWithColor(context, dataSet.circleHoleColor.CGColor)
rect.origin.x = pt.x - circleHoleRadius
rect.origin.y = pt.y - circleHoleRadius
rect.size.width = circleHoleDiameter
rect.size.height = circleHoleDiameter
CGContextFillEllipseInRect(context, rect)
}
}
}
CGContextRestoreGState(context)
}
var _highlightPtsBuffer = [CGPoint](count: 4, repeatedValue: CGPoint())
public override func drawHighlighted(context context: CGContext?, indices: [ChartHighlight])
{
let lineData = delegate!.lineChartRendererData(self)
let chartXMax = delegate!.lineChartRendererChartXMax(self)
let chartYMax = delegate!.lineChartRendererChartYMax(self)
let chartYMin = delegate!.lineChartRendererChartYMin(self)
CGContextSaveGState(context)
for (var i = 0; i < indices.count; i++)
{
let set = lineData.getDataSetByIndex(indices[i].dataSetIndex) as! LineChartDataSet!
if (set === nil || !set.isHighlightEnabled)
{
continue
}
CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor)
CGContextSetLineWidth(context, set.highlightLineWidth)
if (set.highlightLineDashLengths != nil)
{
CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
let xIndex = indices[i].xIndex; // get the x-position
if (CGFloat(xIndex) > CGFloat(chartXMax) * _animator.phaseX)
{
continue
}
let yValue = set.yValForXIndex(xIndex)
if (yValue.isNaN)
{
continue
}
let y = CGFloat(yValue) * _animator.phaseY; // get the y-position
_highlightPtsBuffer[0] = CGPoint(x: CGFloat(xIndex), y: CGFloat(chartYMax))
_highlightPtsBuffer[1] = CGPoint(x: CGFloat(xIndex), y: CGFloat(chartYMin))
_highlightPtsBuffer[2] = CGPoint(x: CGFloat(delegate!.lineChartRendererChartXMin(self)), y: y)
_highlightPtsBuffer[3] = CGPoint(x: CGFloat(chartXMax), y: y)
let trans = delegate!.lineChartRenderer(self, transformerForAxis: set.axisDependency)
trans.pointValuesToPixel(&_highlightPtsBuffer)
// draw the lines
drawHighlightLines(context: context, points: _highlightPtsBuffer,
horizontal: set.isHorizontalHighlightIndicatorEnabled, vertical: set.isVerticalHighlightIndicatorEnabled)
}
CGContextRestoreGState(context)
}
} | mit |
nasser0099/Express | Express/StencilViewEngine.swift | 1 | 4259 | //===--- StencilViewEngine.swift -----------------------------------------===//
//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express.
//
//Swift Express is free software: you can redistribute it and/or modify
//it under the terms of the GNU Lesser General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//Swift Express is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public License
//along with Swift Express. If not, see <http://www.gnu.org/licenses/>.
//
//===----------------------------------------------------------------------===//
import Foundation
import PathKit
import Stencil
private extension Path {
var containerDir: Path {
return Path(NSString(string: String(self)).stringByDeletingLastPathComponent)
}
}
typealias StencilEdible = [String: Any]
private protocol StencilCookable {
func cook() -> StencilEdible
}
private protocol StencilNormalizable {
func normalizeValue(value:Any) -> Any
func normalize() -> Any
}
extension StencilNormalizable {
func normalizeValue(value:Any) -> Any {
let normalizable = value as? StencilNormalizable
return normalizable.map {$0.normalize()} .getOrElse(value)
}
}
extension Array : StencilNormalizable {
func normalize() -> Any {
return self.map(normalizeValue)
}
}
extension Dictionary : StencilNormalizable {
func normalize() -> Any {
let normalized = self.map { (k, v) in
(k, normalizeValue(v))
}
return toMap(normalized)
}
}
extension Dictionary : StencilCookable {
func cook() -> StencilEdible {
return self.map { (k,v) in
return (String(k), normalizeValue(v))
}
}
}
private let loaderKey = "loader"
class StencilView : ViewType {
let template:Template
let loader:TemplateLoader?
init(template:Template, loader:TemplateLoader? = nil) {
self.template = template
self.loader = loader
}
func render<C>(context:C?) throws -> FlushableContentType {
do {
let edibleOption = context.flatMap{$0 as? StencilCookable }?.cook()
let contextSupplied:[String:Any] = edibleOption.getOrElse(Dictionary())
let loader = contextSupplied.findFirst { (k, v) in
k == loaderKey
}.map{$1}
if let loader = loader {
guard let loader = loader as? TemplateLoader else {
throw ExpressError.Render(description: "'loader' is a reserved key and can be of TemplateLoader type only", line: nil, cause: nil)
}
print("OK, loader: ", loader)
//TODO: merge loaders
}
let contextLoader:[String:Any] = self.loader.map{["loader": $0]}.getOrElse(Dictionary())
let finalContext = contextSupplied ++ contextLoader
let stencilContext = Context(dictionary: finalContext)
let render = try template.render(stencilContext)
return AnyContent(str:render, contentType: "text/html")!
} catch let e as TemplateSyntaxError {
throw ExpressError.Render(description: e.description, line: nil, cause: e)
}
}
}
public class StencilViewEngine : ViewEngineType {
public init() {
}
public func extensions() -> Array<String> {
return ["stencil"]
}
public func view(filePath:String) throws -> ViewType {
do {
let path = Path(filePath)
let dir = path.containerDir
let loader = TemplateLoader(paths: [dir])
let template = try Template(path: path)
return StencilView(template: template, loader: loader)
} catch let e as TemplateSyntaxError {
throw ExpressError.Render(description: e.description, line: nil, cause: e)
}
}
}
| gpl-3.0 |
tavultesoft/keymanweb | ios/engine/KMEI/KeymanEngine/Classes/kmp.json/KMPSystem.swift | 1 | 679 | //
// KMPSystem.swift
// KeymanEngine
//
// Created by Joshua Horton on 6/1/20.
// Copyright © 2020 SIL International. All rights reserved.
//
import Foundation
struct KMPSystem: Codable {
public var keymanDeveloperVersion: String?
public var fileVersion: String
enum CodingKeys: String, CodingKey {
case keymanDeveloperVersion
case fileVersion
}
init?(forPackageType packageType: KMPMetadata.PackageType) {
keymanDeveloperVersion = nil
switch packageType {
case .Keyboard:
fileVersion = "7.0"
return
case .LexicalModel:
fileVersion = "12.0"
return
default:
return nil
}
}
}
| apache-2.0 |
bi3mer/WorkSpace | Swift/functionHelloWorld/functionHelloWorld/main.swift | 1 | 933 | //
// main.swift
// functionHelloWorld
//
// Created by colan biemer on 3/28/15.
// Copyright (c) 2015 colan biemer. All rights reserved.
//
import Foundation
func hello() -> Void
{
println("hello world!")
}
func hello(printVal: String)
{
println("overload worked: " + printVal)
}
func returnHello() -> String
{
return "hello world!"
}
func returnHello(str: String, str2: String) -> String
{
return str + " " + str2
}
func minMax(arr: [Int]) -> (min: Int, max: Int)
{
var min = arr[0]
var max = arr[0]
for val in arr
{
if( val > max )
{
max = val
}
else if(val < min)
{
min = val
}
}
return (min,max)
}
hello()
hello("value")
println(returnHello())
println(returnHello("one", "two"))
var arr = [2,3,1235,6,123,123901,23,-123,123,-1234 ]
var mm = minMax(arr)
println("min: \(mm.0) max: \(mm.1)")
| mit |
groue/GRDB.swift | GRDB/Record/FetchableRecord.swift | 1 | 33687 | import Foundation
/// A type that can decode itself from a database row.
///
/// To conform to `FetchableRecord`, provide an implementation for the
/// ``init(row:)-9w9yp`` initializer. This implementation is ready-made for
/// `Decodable` types.
///
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord, Decodable {
/// var name: String
/// var score: Int
/// }
///
/// if let row = try Row.fetchOne(db, sql: "SELECT * FROM player") {
/// let player = try Player(row: row)
/// }
/// ```
///
/// If you add conformance to ``TableRecord``, the record type can generate
/// SQL queries for you:
///
/// ```swift
/// struct Player: FetchableRecord, TableRecord, Decodable {
/// var name: String
/// var score: Int
/// }
///
/// let players = try Player.fetchAll(db)
/// let players = try Player.order(Column("score")).fetchAll(db)
/// ```
///
/// ## Topics
///
/// ### Initializers
///
/// - ``init(row:)-9w9yp``
///
/// ### Fetching Records
/// - ``fetchCursor(_:)``
/// - ``fetchAll(_:)``
/// - ``fetchSet(_:)``
/// - ``fetchOne(_:)``
///
/// ### Fetching Records from Raw SQL
///
/// - ``fetchCursor(_:sql:arguments:adapter:)``
/// - ``fetchAll(_:sql:arguments:adapter:)``
/// - ``fetchSet(_:sql:arguments:adapter:)``
/// - ``fetchOne(_:sql:arguments:adapter:)``
///
/// ### Fetching Records from a Prepared Statement
///
/// - ``fetchCursor(_:arguments:adapter:)``
/// - ``fetchAll(_:arguments:adapter:)``
/// - ``fetchSet(_:arguments:adapter:)``
/// - ``fetchOne(_:arguments:adapter:)``
///
/// ### Fetching Records from a Request
///
/// - ``fetchCursor(_:_:)``
/// - ``fetchAll(_:_:)``
/// - ``fetchSet(_:_:)``
/// - ``fetchOne(_:_:)``
///
/// ### Fetching Records by Primary Key
///
/// - ``fetchCursor(_:ids:)``
/// - ``fetchAll(_:ids:)``
/// - ``fetchSet(_:ids:)``
/// - ``fetchOne(_:id:)``
/// - ``fetchCursor(_:keys:)-2jrm1``
/// - ``fetchAll(_:keys:)-4c8no``
/// - ``fetchSet(_:keys:)-e6uy``
/// - ``fetchOne(_:key:)-3f3hc``
///
/// ### Fetching Record by Key
///
/// - ``fetchCursor(_:keys:)-5u9hu``
/// - ``fetchAll(_:keys:)-2addp``
/// - ``fetchSet(_:keys:)-8no3x``
/// - ``fetchOne(_:key:)-92b9m``
///
/// ### Configuring Row Decoding for the Standard Decodable Protocol
///
/// - ``databaseColumnDecodingStrategy-6uefz``
/// - ``databaseDateDecodingStrategy-78y03``
/// - ``databaseDecodingUserInfo-77jim``
/// - ``databaseJSONDecoder(for:)-7lmxd``
/// - ``DatabaseColumnDecodingStrategy``
/// - ``DatabaseDateDecodingStrategy``
///
/// ### Supporting Types
///
/// - ``RecordCursor``
public protocol FetchableRecord {
// MARK: - Row Decoding
/// Creates a record from `row`.
///
/// The row argument may be reused during the iteration of database results.
/// If you want to keep the row for later use, make sure to store a copy:
/// `row.copy()`.
///
/// - throws: An error is thrown if the record can't be decoded from the
/// database row.
init(row: Row) throws
// MARK: - Customizing the Format of Database Columns
/// Contextual information made available to the
/// `Decodable.init(from:)` initializer.
///
/// For example:
///
/// ```swift
/// // A key that holds a decoder's name
/// let decoderName = CodingUserInfoKey(rawValue: "decoderName")!
///
/// // A FetchableRecord + Decodable record
/// struct Player: FetchableRecord, Decodable {
/// // Customize the decoder name when decoding a database row
/// static let databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [decoderName: "Database"]
///
/// init(from decoder: Decoder) throws {
/// // Print the decoder name
/// print(decoder.userInfo[decoderName])
/// ...
/// }
/// }
///
/// // prints "Database"
/// let player = try Player.fetchOne(db, ...)
///
/// // prints "JSON"
/// let decoder = JSONDecoder()
/// decoder.userInfo = [decoderName: "JSON"]
/// let player = try decoder.decode(Player.self, from: ...)
/// ```
static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] { get }
/// Returns the `JSONDecoder` that decodes the value for a given column.
///
/// This method is dedicated to ``FetchableRecord`` types that also conform
/// to the standard `Decodable` protocol and use the default
/// ``init(row:)-4ptlh`` implementation.
static func databaseJSONDecoder(for column: String) -> JSONDecoder
/// The strategy for decoding `Date` columns.
///
/// This property is dedicated to ``FetchableRecord`` types that also
/// conform to the standard `Decodable` protocol and use the default
/// ``init(row:)-4ptlh`` implementation.
///
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord, Decodable {
/// static let databaseDateDecodingStrategy = DatabaseDateDecodingStrategy.timeIntervalSince1970
///
/// // Decoded from an epoch timestamp
/// var creationDate: Date
/// }
/// ```
static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get }
/// The strategy for converting column names to coding keys.
///
/// This property is dedicated to ``FetchableRecord`` types that also
/// conform to the standard `Decodable` protocol and use the default
/// ``init(row:)-4ptlh`` implementation.
///
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord, Decodable {
/// static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.convertFromSnakeCase
///
/// // Decoded from the 'player_id' column
/// var playerID: String
/// }
/// ```
static var databaseColumnDecodingStrategy: DatabaseColumnDecodingStrategy { get }
}
extension FetchableRecord {
/// Contextual information made available to the
/// `Decodable.init(from:)` initializer.
///
/// The default implementation returns an empty dictionary.
public static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] {
[:]
}
/// Returns the `JSONDecoder` that decodes the value for a given column.
///
/// The default implementation returns a `JSONDecoder` with the
/// following properties:
///
/// - `dataDecodingStrategy`: `.base64`
/// - `dateDecodingStrategy`: `.millisecondsSince1970`
/// - `nonConformingFloatDecodingStrategy`: `.throw`
public static func databaseJSONDecoder(for column: String) -> JSONDecoder {
let decoder = JSONDecoder()
decoder.dataDecodingStrategy = .base64
decoder.dateDecodingStrategy = .millisecondsSince1970
decoder.nonConformingFloatDecodingStrategy = .throw
decoder.userInfo = databaseDecodingUserInfo
return decoder
}
/// The default strategy for decoding `Date` columns is
/// ``DatabaseDateDecodingStrategy/deferredToDate``.
public static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy {
.deferredToDate
}
/// The default strategy for converting column names to coding keys is
/// ``DatabaseColumnDecodingStrategy/useDefaultKeys``.
public static var databaseColumnDecodingStrategy: DatabaseColumnDecodingStrategy {
.useDefaultKeys
}
}
extension FetchableRecord {
// MARK: Fetching From Prepared Statement
/// Returns a cursor over records fetched from a prepared statement.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT * FROM player WHERE lastName = ?"
/// let statement = try db.makeStatement(sql: sql)
/// let players = try Player.fetchCursor(statement, arguments: [lastName])
/// while let player = try players.next() {
/// print(player.name)
/// }
/// }
/// ```
///
/// The returned cursor is valid only during the remaining execution of the
/// database access. Do not store or return the cursor for later use.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A ``RecordCursor`` over fetched records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> RecordCursor<Self>
{
try RecordCursor(statement: statement, arguments: arguments, adapter: adapter)
}
/// Returns an array of records fetched from a prepared statement.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT * FROM player WHERE lastName = ?"
/// let statement = try db.makeStatement(sql: sql)
/// let players = try Player.fetchAll(statement, arguments: [lastName])
/// }
/// ```
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> [Self]
{
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
/// Returns a single record fetched from a prepared statement.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT * FROM player WHERE lastName = ? LIMIT 1"
/// let statement = try db.makeStatement(sql: sql)
/// let player = try Player.fetchOne(statement, arguments: [lastName])
/// }
/// ```
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Self?
{
try fetchCursor(statement, arguments: arguments, adapter: adapter).next()
}
}
extension FetchableRecord where Self: Hashable {
/// Returns a set of records fetched from a prepared statement.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT * FROM player WHERE lastName = ?"
/// let statement = try db.makeStatement(sql: sql)
/// let players = try Player.fetchSet(statement, arguments: [lastName])
/// }
/// ```
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A set of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Set<Self>
{
try Set(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
}
extension FetchableRecord {
// MARK: Fetching From SQL
/// Returns a cursor over records fetched from an SQL query.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT * FROM player WHERE lastName = ?"
/// let players = try Player.fetchCursor(db, sql: sql, arguments: [lastName])
/// while let player = try players.next() {
/// print(player.name)
/// }
/// }
/// ```
///
/// The returned cursor is valid only during the remaining execution of the
/// database access. Do not store or return the cursor for later use.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL string.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A ``RecordCursor`` over fetched records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
throws -> RecordCursor<Self>
{
try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of records fetched from an SQL query.
///
/// For example:
///
/// ```swift
/// let players = try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT * FROM player WHERE lastName = ?"
/// return try Player.fetchAll(db, sql: sql, arguments: [lastName])
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL string.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
throws -> [Self]
{
try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns a single record fetched from an SQL query.
///
/// For example:
///
/// ```swift
/// let player = try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT * FROM player WHERE lastName = ? LIMIT 1"
/// return try Player.fetchOne(db, sql: sql, arguments: [lastName])
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL string.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
throws -> Self?
{
try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
}
}
extension FetchableRecord where Self: Hashable {
/// Returns a set of records fetched from an SQL query.
///
/// For example:
///
/// ```swift
/// let players = try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT * FROM player WHERE lastName = ?"
/// return try Player.fetchSet(db, sql: sql, arguments: [lastName])
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL string.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A set of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
throws -> Set<Self>
{
try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
}
}
extension FetchableRecord {
// MARK: Fetching From FetchRequest
/// Returns a cursor over records fetched from a fetch request.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
///
/// // SQL request
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// """
///
/// let players = try Player.fetchCursor(db, request)
/// while let player = try players.next() {
/// print(player.name)
/// }
/// }
/// ```
///
/// The returned cursor is valid only during the remaining execution of the
/// database access. Do not store or return the cursor for later use.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// - parameters:
/// - db: A database connection.
/// - sql: a FetchRequest.
/// - returns: A ``RecordCursor`` over fetched records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> RecordCursor<Self> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
precondition(request.supplementaryFetch == nil, "Not implemented: fetchCursor with supplementary fetch")
return try fetchCursor(request.statement, adapter: request.adapter)
}
/// Returns an array of records fetched from a fetch request.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
///
/// // SQL request
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// """
///
/// let players = try Player.fetchAll(db, request)
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - sql: a FetchRequest.
/// - returns: An array of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
if let supplementaryFetch = request.supplementaryFetch {
let rows = try Row.fetchAll(request.statement, adapter: request.adapter)
try supplementaryFetch(db, rows)
return try rows.map(Self.init(row:))
} else {
return try fetchAll(request.statement, adapter: request.adapter)
}
}
/// Returns a single record fetched from a fetch request.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
///
/// // SQL request
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE lastName = \(lastName) LIMIT 1
/// """
///
/// let player = try Player.fetchOne(db, request)
/// }
/// ```
/// - parameters:
/// - db: A database connection.
/// - sql: a FetchRequest.
/// - returns: An optional record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
let request = try request.makePreparedRequest(db, forSingleResult: true)
if let supplementaryFetch = request.supplementaryFetch {
guard let row = try Row.fetchOne(request.statement, adapter: request.adapter) else {
return nil
}
try supplementaryFetch(db, [row])
return try .init(row: row)
} else {
return try fetchOne(request.statement, adapter: request.adapter)
}
}
}
extension FetchableRecord where Self: Hashable {
/// Returns a set of records fetched from a fetch request.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
///
/// // SQL request
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// """
///
/// let players = try Player.fetchSet(db, request)
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - sql: a FetchRequest.
/// - returns: A set of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
if let supplementaryFetch = request.supplementaryFetch {
let rows = try Row.fetchAll(request.statement, adapter: request.adapter)
try supplementaryFetch(db, rows)
return try Set(rows.lazy.map(Self.init(row:)))
} else {
return try fetchSet(request.statement, adapter: request.adapter)
}
}
}
// MARK: - FetchRequest
extension FetchRequest where RowDecoder: FetchableRecord {
// MARK: Fetching Records
/// Returns a cursor over fetched records.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
///
/// // SQL request
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// """
///
/// let players = try request.fetchCursor(db)
/// while let player = try players.next() {
/// print(player.name)
/// }
/// }
/// ```
///
/// The returned cursor is valid only during the remaining execution of the
/// database access. Do not store or return the cursor for later use.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// - parameters:
/// - db: A database connection.
/// - sql: a FetchRequest.
/// - returns: A ``RecordCursor`` over fetched records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> RecordCursor<RowDecoder> {
try RowDecoder.fetchCursor(db, self)
}
/// Returns an array of fetched records.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
///
/// // SQL request
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// """
///
/// let players = try request.fetchAll(db)
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - sql: a FetchRequest.
/// - returns: An array of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
try RowDecoder.fetchAll(db, self)
}
/// Returns a single record.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
///
/// // SQL request
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE lastName = \(lastName) LIMIT 1
/// """
///
/// let player = try request.fetchOne(db)
/// }
/// ```
/// - parameters:
/// - db: A database connection.
/// - sql: a FetchRequest.
/// - returns: An optional record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
try RowDecoder.fetchOne(db, self)
}
}
extension FetchRequest where RowDecoder: FetchableRecord & Hashable {
/// Returns a set of fetched records.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
///
/// // SQL request
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// """
///
/// let players = try request.fetchSet(db)
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - sql: a FetchRequest.
/// - returns: A set of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
try RowDecoder.fetchSet(db, self)
}
}
// MARK: - RecordCursor
/// A cursor of records.
///
/// A `RecordCursor` iterates all rows from a database request. Its
/// elements are the records decoded from each fetched row.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let players: RecordCursor<Player> = try Player.fetchCursor(db, sql: "SELECT * FROM player")
/// while let player = try players.next() {
/// print(player.name)
/// }
/// }
/// ```
public final class RecordCursor<Record: FetchableRecord>: DatabaseCursor {
public typealias Element = Record
public let _statement: Statement
public var _isDone = false
@usableFromInline
let _row: Row // Instantiated once, reused for performance
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
self._statement = statement
_row = try Row(statement: statement).adapted(with: adapter, layout: statement)
try statement.reset(withArguments: arguments)
}
deinit {
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? _statement.reset()
}
@inlinable
public func _element(sqliteStatement: SQLiteStatement) throws -> Record {
try Record(row: _row)
}
}
// MARK: - DatabaseDateDecodingStrategy
/// `DatabaseDateDecodingStrategy` specifies how `FetchableRecord` types that
/// also adopt the standard `Decodable` protocol decode their
/// `Date` properties.
///
/// For example:
///
/// struct Player: FetchableRecord, Decodable {
/// static let databaseDateDecodingStrategy = DatabaseDateDecodingStrategy.timeIntervalSince1970
///
/// var name: String
/// var registrationDate: Date // decoded from epoch timestamp
/// }
public enum DatabaseDateDecodingStrategy {
/// The strategy that uses formatting from the Date structure.
///
/// It decodes numeric values as a number of seconds since Epoch
/// (midnight UTC on January 1st, 1970).
///
/// It decodes strings in the following formats, assuming UTC time zone.
/// Missing components are assumed to be zero:
///
/// - `YYYY-MM-DD`
/// - `YYYY-MM-DD HH:MM`
/// - `YYYY-MM-DD HH:MM:SS`
/// - `YYYY-MM-DD HH:MM:SS.SSS`
/// - `YYYY-MM-DDTHH:MM`
/// - `YYYY-MM-DDTHH:MM:SS`
/// - `YYYY-MM-DDTHH:MM:SS.SSS`
case deferredToDate
/// Decodes numeric values as a number of seconds between the date and
/// midnight UTC on 1 January 2001
case timeIntervalSinceReferenceDate
/// Decodes numeric values as a number of seconds between the date and
/// midnight UTC on 1 January 1970
case timeIntervalSince1970
/// Decodes numeric values as a number of milliseconds between the date and
/// midnight UTC on 1 January 1970
case millisecondsSince1970
/// Decodes dates according to the ISO 8601 standards
case iso8601
/// Decodes a String, according to the provided formatter
case formatted(DateFormatter)
/// Decodes according to the user-provided function.
///
/// If the database value does not contain a suitable value, the function
/// must return nil (GRDB will interpret this nil result as a conversion
/// error, and react accordingly).
case custom((DatabaseValue) -> Date?)
}
// MARK: - DatabaseColumnDecodingStrategy
/// `DatabaseColumnDecodingStrategy` specifies how `FetchableRecord` types that
/// also adopt the standard `Decodable` protocol look for the database columns
/// that match their coding keys.
///
/// For example:
///
/// struct Player: FetchableRecord, Decodable {
/// static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.convertFromSnakeCase
///
/// // Decoded from the player_id column
/// var playerID: Int
/// }
public enum DatabaseColumnDecodingStrategy {
/// A key decoding strategy that doesn’t change key names during decoding.
case useDefaultKeys
/// A key decoding strategy that converts snake-case keys to camel-case keys.
case convertFromSnakeCase
/// A key decoding strategy defined by the closure you supply.
case custom((String) -> CodingKey)
func key<K: CodingKey>(forColumn column: String) -> K? {
switch self {
case .useDefaultKeys:
return K(stringValue: column)
case .convertFromSnakeCase:
return K(stringValue: Self._convertFromSnakeCase(column))
case let .custom(key):
return K(stringValue: key(column).stringValue)
}
}
// Copied straight from
// https://github.com/apple/swift-corelibs-foundation/blob/8d6398d76eaf886a214e0bb2bd7549d968f7b40e/Sources/Foundation/JSONDecoder.swift#L103
static func _convertFromSnakeCase(_ stringKey: String) -> String {
//===----------------------------------------------------------------------===//
//
// This function is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
guard !stringKey.isEmpty else { return stringKey }
// Find the first non-underscore character
guard let firstNonUnderscore = stringKey.firstIndex(where: { $0 != "_" }) else {
// Reached the end without finding an _
return stringKey
}
// Find the last non-underscore character
var lastNonUnderscore = stringKey.index(before: stringKey.endIndex)
while lastNonUnderscore > firstNonUnderscore && stringKey[lastNonUnderscore] == "_" {
stringKey.formIndex(before: &lastNonUnderscore)
}
let keyRange = firstNonUnderscore...lastNonUnderscore
let leadingUnderscoreRange = stringKey.startIndex..<firstNonUnderscore
let trailingUnderscoreRange = stringKey.index(after: lastNonUnderscore)..<stringKey.endIndex
let components = stringKey[keyRange].split(separator: "_")
let joinedString: String
if components.count == 1 {
// No underscores in key, leave the word as is - maybe already camel cased
joinedString = String(stringKey[keyRange])
} else {
joinedString = ([components[0].lowercased()] + components[1...].map { $0.capitalized }).joined()
}
// Do a cheap isEmpty check before creating and appending potentially empty strings
let result: String
if leadingUnderscoreRange.isEmpty && trailingUnderscoreRange.isEmpty {
result = joinedString
} else if !leadingUnderscoreRange.isEmpty && !trailingUnderscoreRange.isEmpty {
// Both leading and trailing underscores
result = String(stringKey[leadingUnderscoreRange])
+ joinedString
+ String(stringKey[trailingUnderscoreRange])
} else if !leadingUnderscoreRange.isEmpty {
// Just leading
result = String(stringKey[leadingUnderscoreRange]) + joinedString
} else {
// Just trailing
result = joinedString + String(stringKey[trailingUnderscoreRange])
}
return result
}
}
| mit |
andrebocchini/SwiftChatty | SwiftChatty/Responses/Messages/MarkMessageReadResponse.swift | 1 | 316 | //
// MarkMessageReadResponse.swift
// SwiftChatty
//
// Created by Andre Bocchini on 1/24/16.
// Copyright © 2016 Andre Bocchini. All rights reserved.//
/// -SeeAlso: http://winchatty.com/v2/readme#_Toc421451694
public struct MarkMessageReadResponse: CommonSuccessResponse {
public var result: String
}
| mit |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Models/ThemeIdHelper.swift | 2 | 926 | import Foundation
/// Helper class for adding and removing the '-wpcom' suffix from themeIds
///
class ThemeIdHelper: NSObject {
private static let WPComThemesIDSuffix = "-wpcom"
@objc static func themeIdWithWPComSuffix(_ themeId: String) -> String {
return themeId.appending(WPComThemesIDSuffix)
}
@objc static func themeIdWithWPComSuffixRemoved(_ themeId: String, forBlog blog: Blog) -> String {
if blog.supports(.customThemes) && themeIdHasWPComSuffix(themeId) {
// When a WP.com theme is used on a JP site, its themeId is modified to themeId-wpcom,
// we need to remove this to be able to match it on the theme list
return String(themeId.dropLast(WPComThemesIDSuffix.count))
}
return themeId
}
@objc static func themeIdHasWPComSuffix(_ themeId: String) -> Bool {
return themeId.hasSuffix(WPComThemesIDSuffix)
}
}
| gpl-2.0 |
royhsu/tiny-core | Sources/Core/HTTP/HTTPRequest+URLRequestRepresentable.swift | 1 | 894 | //
// HTTPRequest+URLRequestRepresentable.swift
// TinyCore
//
// Created by Roy Hsu on 2019/1/26.
// Copyright © 2019 TinyWorld. All rights reserved.
//
// MARK: - URLRequestRepresentable
extension HTTPRequest: URLRequestRepresentable {
public func urlRequest() throws -> URLRequest {
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
var headers = self.headers
if let body = body {
request.httpBody = try bodyEncoder.encode(body)
let mime: MIMEType
switch bodyEncoder {
case is JSONEncoder: mime = .json
default: fatalError("Unsupported HTTP Body Encoder.")
}
let header = try mime.httpHeader()
headers[header.field] = header.value
}
request.setHTTPHeaders(headers)
return request
}
}
| mit |
robzimpulse/mynurzSDK | Example/mynurzSDK/CardViewViewController.swift | 1 | 1148 | //
// CardViewViewController.swift
// mynurzSDK
//
// Created by Robyarta on 6/10/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
class CardViewViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
@IBDesignable
class CardView: UIView {
@IBInspectable var cornerRadius: CGFloat = 2
@IBInspectable var shadowOffsetWidth: Int = 0
@IBInspectable var shadowOffsetHeight: Int = 3
@IBInspectable var shadowColor: UIColor? = UIColor.black
@IBInspectable var shadowOpacity: Float = 0.5
override func layoutSubviews() {
layer.cornerRadius = cornerRadius
let shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius)
layer.masksToBounds = false
layer.shadowColor = shadowColor?.cgColor
layer.shadowOffset = CGSize(width: shadowOffsetWidth, height: shadowOffsetHeight);
layer.shadowOpacity = shadowOpacity
layer.shadowPath = shadowPath.cgPath
}
}
| mit |
magnetsystems/message-samples-ios | QuickStart/QuickStart/ChannelCell.swift | 1 | 1830 | /*
* Copyright (c) 2015 Magnet Systems, Inc.
* 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 MagnetMax
class ChannelCell: UITableViewCell {
// MARK: Outlets
@IBOutlet weak var ivPrivate: UIImageView!
@IBOutlet weak var lblChannelName: UILabel!
@IBOutlet weak var lblLastTime: UILabel!
@IBOutlet weak var lblTags: UILabel!
// MARK: Public properties
var channel : MMXChannel! {
didSet {
lblChannelName.text = channel.name
ivPrivate.image = channel.isPublic ? nil : UIImage(named: "lock-7.png")
let formatter = NSDateFormatter()
formatter.timeStyle = .ShortStyle
lblLastTime.text = formatter.stringFromDate(channel.lastTimeActive)
channel.tagsWithSuccess({ (tags) -> Void in
var stringForTags = ""
for tag in tags {
stringForTags.appendContentsOf("\(tag) ")
}
self.lblTags.text = stringForTags
}) { (error) -> Void in
print(error)
}
}
}
// MARK: Overrides
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.